UNPKG

@azowl/agentops-sdk

Version:

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

102 lines (99 loc) • 4.88 kB
import { randomUUID } from 'node:crypto'; import { setTimeout as sleep } from 'node:timers/promises'; import { AgentClient } from './agent.js'; import { apiRequest, localOrigin, queueDirectory, readCredential, workerKey, uuidPattern } from './local-queue.js'; // This adapter polls on behalf of an already running standalone AZWOL Agent. // The existing agent, in its own process, performs the assignment and tool policy checks. export async function connectAgent({ baseUrl, directory, runnerId, agentId, agentUrl, pollMs = 500, once = false, signal, onEvent = () => {} }) { const origin = localOrigin(baseUrl); const target = localOrigin(agentUrl ?? 'http://127.0.0.1:43179'); if (target === origin || !Number.isInteger(pollMs) || pollMs < 50 || pollMs > 60000) { throw new TypeError('Invalid agent address or polling interval.'); } const key = workerKey(runnerId, agentId); const folder = queueDirectory(origin, directory); const api = async (route, body) => apiRequest(origin, await readCredential(folder, key), route, body); const agent = new AgentClient({ baseUrl: target }); // Check availability and authentication without submitting a tool request. try { await agent.tasks.get(randomUUID()); } catch (error) { if (error.status !== 404) throw error; } async function processOne() { const pending = await api('/runtime/task?status=pending&limit=1'); const next = pending.tasks[0]; if (!next) return false; if (!uuidPattern.test(next.task_id) || next.runnerId !== runnerId || next.agentId !== agentId) { throw new Error('Queue returned work for an unexpected assignment.'); } const resource = '/runtime/task/' + next.task_id; let lease; try { lease = await api(resource + '/claim', { observed_revision: next.revision }); } catch (error) { if (error.status === 409) return false; throw error; } const task = lease.task; if (task.id !== next.task_id || task.runnerId !== runnerId || task.agentId !== agentId || !uuidPattern.test(lease.lease_id) || !Number.isFinite(Date.parse(lease.lease_expires_at))) { throw new Error('Invalid queue lease.'); } const leaseBody = { lease_id: lease.lease_id }; const stopRenewal = new AbortController(); let expiration = Date.parse(lease.lease_expires_at); let fenced = false; const renewal = (async () => { while (!stopRenewal.signal.aborted) { const delay = Math.max(50, Math.floor((expiration - Date.now()) / 3)); await sleep(delay, undefined, { signal: stopRenewal.signal }).catch(() => {}); if (stopRenewal.signal.aborted) return; try { const renewed = await api(resource + '/renew-lease', leaseBody); if (renewed.lease_id !== lease.lease_id || !Number.isFinite(Date.parse(renewed.lease_expires_at))) { fenced = true; return; } expiration = Date.parse(renewed.lease_expires_at); } catch (error) { if (error.status === 409 || error.status === 404 || Date.now() >= expiration) { fenced = true; return; } } } })(); try { onEvent({ event: 'claimed', id: task.id, runnerId, agentId }); // Submit exactly once: a lost HTTP response may still have executed the tool. const receipt = await agent.tasks.create({ runnerId, agentId, tool: task.tool, input: task.input }); for (let attempt = 0; ; attempt++) { if (fenced || Date.now() >= expiration) throw new Error('Lease expired before the receipt was confirmed.'); try { const action = receipt.status === 'completed' ? '/complete' : '/fail'; const confirmation = await api(resource + action, { ...leaseBody, receipt }); if (!confirmation.accepted || confirmation.task_id !== task.id || confirmation.status !== receipt.status) { throw new Error('Invalid receipt confirmation.'); } break; } catch (error) { if (attempt >= 2 || (error.status && error.status < 500)) throw error; await sleep(120 * (attempt + 1)); } } onEvent({ event: 'finished', id: task.id, receiptId: receipt.id, status: receipt.status }); } catch (error) { onEvent({ event: 'unconfirmed', id: task.id, code: error.code || 'UNCONFIRMED' }); throw error; } finally { stopRenewal.abort(); await renewal; } return true; } while (!signal?.aborted) { try { const worked = await processOne(); if (once) return worked; if (worked) continue; } catch (error) { if (once || error.status === 401 || error.status === 403) throw error; onEvent({ event: 'poll-error', code: error.code || 'UNAVAILABLE' }); } try { await sleep(pollMs, undefined, { signal }); } catch (error) { if (!signal?.aborted) throw error; } } return false; }