@adonis-agora/agent
Version:
Governed, durable-backed AI agent (chat + tool-calling + governance) for AdonisJS — part of the Agora ecosystem.
96 lines • 4.4 kB
JavaScript
import { throwForResponse } from './company.js';
import { PoppyError } from './errors.js';
import { readJson } from './http.js';
import { sendWithOperations } from './operations.js';
import { requireSecureUrl } from './util.js';
/** API types this client understands (section 7). Others are skipped. */
export const KNOWN_API_TYPES = ['openapi', 'mcp'];
export function listApis(company) {
return (company.document.apis ?? []).filter((a) => a && KNOWN_API_TYPES.includes(a.type) && typeof a.url === 'string');
}
export function pickApi(company, type, index) {
const apis = listApis(company).filter((a) => a.type === type);
if (apis.length === 0)
throw new PoppyError('no_api', `Company lists no ${type} API`);
const api = apis[index ?? 0];
if (!api)
throw new PoppyError('no_api', `no ${type} API at index ${index}`);
requireSecureUrl(api.url, `${type} url`, company.security);
return api;
}
/** Loads an OpenAPI description. Tried as a public document first; through the Session if that's refused. */
export async function loadOpenApi(company, api) {
const res = await company.http.request(api.url, { headers: { accept: 'application/json' } });
if (res.ok)
return (await readJson(res)) ?? {};
if (res.status === 401 || res.status === 403) {
const { body } = await company.json(api.url, {
headers: { accept: 'application/json' },
service: api.url,
});
return body ?? {};
}
throw new PoppyError(`http_${res.status}`, `could not load ${api.url}`);
}
/** The API's base URL: `servers[0].url` resolved against the description's URL. */
export function apiBaseUrl(doc, api) {
const server = doc.servers?.[0]?.url;
return new URL(server ?? '/', api.url).toString().replace(/\/+$/, '');
}
/**
* Calls an endpoint of a listed OpenAPI API (section 7), through the Session and, when signed in,
* with an access token. Refuses absolute URLs outside the API's own origin, so nothing goes to a
* third party.
*
* With the Operations extension, an action the Company wants approved comes back as an operation:
* it is decided (`operations.approve`, or `options.approve`) and the same request goes again with
* `Poppy-Approval`. `operation` then says how it ended; the action was done only when it is
* `performed`.
*/
export async function callOpenApi(company, input, options = {}) {
const api = pickApi(company, 'openapi', input.apiIndex);
const doc = await loadOpenApi(company, api);
const base = apiBaseUrl(doc, api);
const url = /^https?:\/\//i.test(input.path)
? new URL(input.path)
: new URL(base + (input.path.startsWith('/') ? input.path : `/${input.path}`));
const allowed = new Set([new URL(base).origin, new URL(api.url).origin]);
if (!allowed.has(url.origin)) {
throw new PoppyError('foreign_origin', `${url.origin} is not this API's origin; refusing to send credentials`);
}
requireSecureUrl(url.toString(), 'API URL', company.security);
const headers = { accept: 'application/json' };
if (input.body !== undefined)
headers['content-type'] = 'application/json';
const method = input.method.toUpperCase();
const content = input.body === undefined ? undefined : JSON.stringify(input.body);
// 6: the same method, target URI and content each time; only the approval header is added.
const { response: res, outcome } = await sendWithOperations(company, 'api', { method, url: url.toString(), body: input.body }, (approval) => company.fetch(url.toString(), {
method,
headers: approval ? { ...headers, 'poppy-approval': approval } : headers,
body: content,
service: base,
scope: input.scope,
}), options);
if ((res.status === 401 || res.status === 403) && res.headers.get('www-authenticate')) {
await throwForResponse(res);
}
if (res.status === 400) {
const refused = await readJson(res.clone());
if (refused?.error === 'invalid_session')
await throwForResponse(res);
}
const text = await res.text();
let body = text;
try {
body = text ? JSON.parse(text) : undefined;
}
catch { }
return {
status: res.status,
headers: res.headers,
body,
...(outcome ? { operation: outcome } : {}),
};
}
//# sourceMappingURL=api.js.map