@azowl/agentops-sdk
Version:
AgentOps REST client and local task execution SDK for Node.js
303 lines (274 loc) • 11.5 kB
JavaScript
'use strict';
const { createHash, randomUUID } = require('node:crypto');
const { types } = require('node:util');
const DEFAULT_HISTORY_LIMIT = 100;
const MAX_JSON_DEPTH = 64;
const MAX_JSON_VALUES = 10000;
const MAX_JSON_TEXT_BYTES = 1024 * 1024;
// Adapted from the desktop artifact receipt check. See LICENSE.desktop and NOTICE.
function verifyArtifactReceipt(input) {
if (input === null || typeof input !== 'object') return false;
try {
const { bytes, sizeBytes, sha256 } = input;
if (!types.isUint8Array(bytes) || !Number.isSafeInteger(sizeBytes) || sizeBytes < 0 ||
typeof sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(sha256) || bytes.byteLength !== sizeBytes) {
return false;
}
// Hash the same byte snapshot whose length we check, including for sliced views.
const snapshot = new Uint8Array(bytes);
return snapshot.byteLength === sizeBytes && createHash('sha256').update(snapshot).digest('hex') === sha256;
} catch {
return false;
}
}
function assertName(name, kind) {
if (typeof name !== 'string' || !name.trim() || name.length > 128 || /[\u0000-\u001f\u007f]/.test(name)) {
throw new TypeError(`Expected a nonempty ${kind} of at most 128 characters without control characters.`);
}
}
function toolNames(names) {
if (!Array.isArray(names)) throw new TypeError('Expected an array of tool names.');
const result = new Set();
for (const name of names) {
assertName(name, 'tool name');
result.add(name);
}
return result;
}
// Build a detached JSON value without invoking accessors or silently dropping data.
function copyJson(value) {
const ancestors = new Set();
let values = 0;
let textBytes = 0;
function countText(text) {
textBytes += Buffer.byteLength(text, 'utf8');
if (textBytes > MAX_JSON_TEXT_BYTES) throw new TypeError();
}
function property(object, key) {
const descriptor = Object.getOwnPropertyDescriptor(object, key);
if (!descriptor?.enumerable || !Object.hasOwn(descriptor, 'value')) throw new TypeError();
return copy(descriptor.value);
}
function copy(item) {
if (++values > MAX_JSON_VALUES) throw new TypeError();
if (typeof item === 'string') {
countText(item);
return item;
}
if (item === null || typeof item === 'boolean' || Number.isFinite(item)) return item;
if (typeof item !== 'object' || types.isProxy(item) || ancestors.has(item) || ancestors.size >= MAX_JSON_DEPTH) {
throw new TypeError();
}
const array = Array.isArray(item);
const prototype = Object.getPrototypeOf(item);
if (array ? prototype !== Array.prototype : prototype !== null && prototype !== Object.prototype) throw new TypeError();
ancestors.add(item);
const keys = Reflect.ownKeys(item);
let result;
if (array) {
if (keys.length !== item.length + 1 || item.length > MAX_JSON_VALUES - values) throw new TypeError();
result = Array.from({ length: item.length }, (_, index) => property(item, String(index)));
} else {
if (keys.length > MAX_JSON_VALUES - values) throw new TypeError();
result = Object.fromEntries(keys.map(key => {
if (typeof key !== 'string') throw new TypeError();
countText(key);
return [key, property(item, key)];
}));
}
ancestors.delete(item);
return result;
}
return copy(value);
}
function isJsonObject(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function readToolMetadata(metadata, tools) {
let snapshot;
try {
snapshot = copyJson(metadata);
} catch {
throw new TypeError('Expected toolMetadata to contain plain JSON data within the local core size limits.');
}
if (!isJsonObject(snapshot)) throw new TypeError('Expected toolMetadata keyed by tool name.');
const entries = new Map(Object.entries(snapshot));
for (const [name, info] of entries) {
if (!tools.has(name)) throw new TypeError(`Metadata for unregistered tool: ${name}`);
if (!isJsonObject(info) || !Object.hasOwn(info, 'description') ||
typeof info.description !== 'string' || !info.description.trim()) {
throw new TypeError(`Expected a nonempty tool description for ${name}.`);
}
if (Object.hasOwn(info, 'inputSchema') && !isJsonObject(info.inputSchema)) {
throw new TypeError(`Expected inputSchema for ${name} to be a JSON object.`);
}
if (Object.keys(info).some(key => key !== 'description' && key !== 'inputSchema')) {
throw new TypeError(`Unknown tool metadata field for ${name}.`);
}
}
return entries;
}
// Keep the existing task API separate from its policy evidence.
function taskSnapshot({ policy, ...task }) {
return structuredClone(task);
}
function readModelDecision(value) {
const action = copyJson(value);
if (!isJsonObject(action) || !Object.hasOwn(action, 'type')) throw new TypeError();
const keys = Object.keys(action);
if (action.type === 'final' && keys.length === 2 && Object.hasOwn(action, 'text') &&
typeof action.text === 'string' && action.text.trim()) return action;
if (action.type === 'tool_call' && keys.length === 3 &&
Object.hasOwn(action, 'name') && Object.hasOwn(action, 'input')) {
assertName(action.name, 'tool name');
return action;
}
throw new TypeError();
}
class LocalAgent {
#tools = new Map();
#toolMetadata;
#allowed;
#blocked;
#profile;
#rulesSha256;
#running = new Map();
#history = new Map();
#historyLimit;
constructor({ tools, toolMetadata = {}, allowedTools, blockedTools = [], profileId, historyLimit = DEFAULT_HISTORY_LIMIT }) {
if (tools === null || typeof tools !== 'object' || Array.isArray(tools)) throw new TypeError('Expected a tool registry.');
if (!Number.isSafeInteger(historyLimit) || historyLimit < 0) throw new RangeError('Expected a nonnegative history limit.');
if (profileId !== undefined) assertName(profileId, 'profile ID');
for (const name of Object.keys(tools)) {
assertName(name, 'tool name');
const descriptor = Object.getOwnPropertyDescriptor(tools, name);
if (typeof descriptor.value !== 'function') throw new TypeError('Expected a tool handler function.');
this.#tools.set(name, descriptor.value);
}
this.#toolMetadata = readToolMetadata(toolMetadata, this.#tools);
this.#allowed = toolNames(allowedTools);
this.#blocked = toolNames(blockedTools);
this.#profile = profileId ?? null;
this.#rulesSha256 = createHash('sha256').update(JSON.stringify({
allowedTools: [...this.#allowed].sort(),
blockedTools: [...this.#blocked].sort(),
})).digest('hex');
this.#historyLimit = historyLimit;
}
#lookup(taskId) {
return this.#running.get(taskId) ?? this.#history.get(taskId);
}
listTools() {
const catalog = [];
for (const name of this.#tools.keys()) {
if (this.#policyFor(name).decision === 'allow') {
catalog.push({ name, ...this.#toolMetadata.get(name) });
}
}
return structuredClone(catalog);
}
get(taskId) {
const task = this.#lookup(taskId);
return task === undefined ? undefined : taskSnapshot(task);
}
getReceipt(taskId) {
const task = this.#lookup(taskId);
if (task === undefined) return undefined;
return this.#receipt(task, task.policy);
}
#receipt(task, policy) {
return structuredClone({
...task,
policy: { ...policy, profile: this.#profile, rulesSha256: this.#rulesSha256 },
});
}
#policyFor(tool) {
if (this.#blocked.has(tool)) return { decision: 'deny', reason: 'explicitly_blocked' };
if (!this.#allowed.has(tool)) return { decision: 'deny', reason: 'not_in_allowlist' };
if (!this.#tools.has(tool)) return { decision: 'deny', reason: 'not_registered' };
return { decision: 'allow', reason: 'in_allowlist' };
}
start(tool, input) {
return this.#start(tool, input);
}
#start(tool, input) {
assertName(tool, 'tool name');
const id = randomUUID();
const policy = Object.freeze(this.#policyFor(tool));
const task = { id, tool, status: 'running', result: null, error: null, policy };
if (policy.decision === 'deny') {
return { id, policy, done: Promise.resolve(this.#finish(task, 'blocked', null, 'tool_blocked')) };
}
this.#running.set(id, task);
const done = Promise.resolve().then(() => this.#execute(task, input));
return { id, policy, done };
}
async run(tool, input) {
return this.start(tool, input).done;
}
async runWithModel(prompt, model, options = {}) {
if (typeof prompt !== 'string' || !prompt.trim() || Buffer.byteLength(prompt, 'utf8') > MAX_JSON_TEXT_BYTES) {
throw new TypeError('Expected a nonempty prompt of at most 1 MiB.');
}
if (typeof model !== 'function') throw new TypeError('Expected a model adapter function.');
if (!isJsonObject(options)) throw new TypeError('Expected model run options.');
const { maxToolCalls = 4 } = options;
if (!Number.isSafeInteger(maxToolCalls) || maxToolCalls < 0 || maxToolCalls > 16) {
throw new RangeError('Expected maxToolCalls to be an integer from 0 through 16.');
}
const messages = [{ role: 'user', text: prompt }];
const receipts = [];
const catalog = this.listTools();
while (true) {
let response;
try {
const returned = model(structuredClone({ messages, tools: catalog }));
response = types.isPromise(returned) ? await returned : returned;
} catch {
return { status: 'failed', error: { code: 'model_failed' }, receipts };
}
let action;
try {
action = readModelDecision(response);
} catch {
return { status: 'failed', error: { code: 'invalid_model_response' }, receipts };
}
if (action.type === 'final') return { status: 'completed', text: action.text, receipts };
if (receipts.length >= maxToolCalls) {
return { status: 'failed', error: { code: 'tool_limit_reached' }, receipts };
}
const run = this.#start(action.name, structuredClone(action.input));
const task = await run.done;
receipts.push(this.#receipt(task, run.policy));
if (task.status !== 'completed') return { status: task.status, error: task.error, receipts };
messages.push({ role: 'tool', taskId: task.id, name: task.tool, input: action.input, result: task.result });
}
}
async #execute(task, input) {
let value;
try {
const handler = this.#tools.get(task.tool);
const returned = handler(input, { taskId: task.id, tool: task.tool });
// Only await a promise. A data object may contain an untrusted `then` accessor.
value = types.isPromise(returned) ? await returned : returned;
} catch {
return this.#finish(task, 'failed', null, 'tool_failed');
}
let result;
try {
result = copyJson(value);
} catch {
return this.#finish(task, 'failed', null, 'invalid_result');
}
return this.#finish(task, 'completed', result, null);
}
#finish(task, status, result, errorCode) {
this.#running.delete(task.id);
const record = { ...task, status, result, error: errorCode === null ? null : { code: errorCode } };
this.#history.set(task.id, record);
if (this.#history.size > this.#historyLimit) this.#history.delete(this.#history.keys().next().value);
return taskSnapshot(record);
}
}
exports.LocalAgent = LocalAgent;
exports.verifyArtifactReceipt = verifyArtifactReceipt;