@adonis-agora/agent
Version:
Governed, durable-backed AI agent (chat + tool-calling + governance) for AdonisJS — part of the Agora ecosystem.
192 lines • 7.98 kB
JavaScript
/** The container binding the registry lives at. */
export const AGORA_CONSOLES_BINDING = 'agora.consoles';
const CONSOLE_ID = /^[a-z][a-z0-9-]*$/;
const ICONS = [
'workflow',
'telescope',
'media',
'payments',
'agent',
'identity',
'flags',
'cms',
'generic',
];
/** Default time each console's `authorize` (and `search`) gets before it counts as hidden. */
export const CONSOLE_PROBE_TIMEOUT_MS = 300;
/** Hits returned per console by the global search. */
export const CONSOLE_SEARCH_LIMIT = 5;
/** A same-origin absolute path: starts with `/`, not `//`, no backslash, no control characters. */
export function isSameOriginPath(value) {
return (typeof value === 'string' &&
value.startsWith('/') &&
!value.startsWith('//') &&
!value.includes('\\') &&
// biome-ignore lint/suspicious/noControlCharactersInRegex: rejecting control characters is the point
!/[\u0000-\u001f\u007f]/.test(value));
}
/**
* Add a console to the shared `'agora.consoles'` registry, creating it when absent. Skips (never
* throws) a registry of another version; warns and skips a duplicate id. Throws on an invalid `id`
* or `path`: that is a programming error. Apps can call it to register a console they mount by hand.
*
* ```ts
* await registerAgoraConsole(app, { id: 'reports', title: 'Reports', icon: 'generic', path: '/reports',
* order: 100, authorize: async (ctx) => ({ allowed: await isStaff(ctx) }) })
* ```
*/
export async function registerAgoraConsole(app, entry, logger) {
if (typeof entry?.id !== 'string' || !CONSOLE_ID.test(entry.id)) {
throw new Error(`registerAgoraConsole: console id ${JSON.stringify(entry?.id)} must match /^[a-z][a-z0-9-]*$/`);
}
if (!isSameOriginPath(entry.path)) {
throw new Error(`registerAgoraConsole: console "${entry.id}" path ${JSON.stringify(entry.path)} must be a same-origin absolute path`);
}
if (typeof entry.authorize !== 'function') {
throw new Error(`registerAgoraConsole: console "${entry.id}" needs an authorize(ctx)`);
}
const container = app.container;
if (!container.hasBinding(AGORA_CONSOLES_BINDING)) {
container.bindValue(AGORA_CONSOLES_BINDING, { version: 1, entries: [] });
}
const registry = (await container.make(AGORA_CONSOLES_BINDING));
if (registry?.version !== 1 || !Array.isArray(registry.entries))
return false;
if (registry.entries.some((e) => e.id === entry.id)) {
logger?.warn(`[@adonis-agora/agent] console id "${entry.id}" already registered`);
return false;
}
registry.entries.push(entry);
return true;
}
/** The registry, when one is bound and is version 1. */
export async function readAgoraConsoles(app) {
if (!app.container.hasBinding(AGORA_CONSOLES_BINDING))
return null;
const registry = (await app.container.make(AGORA_CONSOLES_BINDING));
if (registry?.version !== 1 || !Array.isArray(registry.entries))
return null;
return registry;
}
/** How many consoles besides `selfId` are registered (the shell's `switcher.others`). */
export function countOtherConsoles(registry, selfId) {
return registry ? registry.entries.filter((e) => e.id !== selfId).length : 0;
}
function sortEntries(entries) {
return [...entries].sort((a, b) => a.order - b.order || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
}
function iconOf(icon) {
return ICONS.includes(icon) ? icon : 'generic';
}
const TIMED_OUT = Symbol('timed out');
/** Resolves to `TIMED_OUT` when `promise` takes longer than `ms`, or `undefined` when it rejects. */
async function race(promise, ms) {
let timer;
try {
return await Promise.race([
Promise.resolve().then(promise),
new Promise((resolve) => {
timer = setTimeout(() => resolve(TIMED_OUT), ms);
}),
]);
}
catch {
return undefined;
}
finally {
if (timer)
clearTimeout(timer);
}
}
/** Runs `fn` with `ctx.agoraProbe = true`, restoring the previous value afterwards. */
async function probing(ctx, fn) {
const holder = ctx;
const previous = holder.agoraProbe;
holder.agoraProbe = true;
try {
return await fn();
}
finally {
if (previous === undefined)
delete holder.agoraProbe;
else
holder.agoraProbe = previous;
}
}
/** Runs every other console's gate in parallel (each raced against `timeoutMs`); keeps the allowed. */
async function allowedEntries(entries, ctx, timeoutMs, logger) {
return probing(ctx, async () => {
const decisions = await Promise.all(entries.map(async (entry) => {
const decision = await race(() => entry.authorize(ctx), timeoutMs);
if (decision === TIMED_OUT || decision === undefined) {
logger?.debug?.(`[@adonis-agora/agent] console "${entry.id}" hidden: authorize ${decision === TIMED_OUT ? 'timed out' : 'failed'}`);
return false;
}
return decision?.allowed === true;
}));
return entries.filter((_, i) => decisions[i]);
});
}
/**
* The consoles (other than `selfId`) the viewer may open: every `authorize` runs in parallel, each
* raced against 300 ms; a timeout, a rejection or anything but `allowed: true` hides the console.
*/
export async function listVisibleConsoles(registry, selfId, ctx, options = {}) {
const others = sortEntries((registry?.entries ?? []).filter((e) => e.id !== selfId));
const allowed = await allowedEntries(others, ctx, options.timeoutMs ?? CONSOLE_PROBE_TIMEOUT_MS, options.logger);
return {
version: 1,
current: selfId,
consoles: allowed
.filter((e) => isSameOriginPath(e.path))
.map((e) => ({
id: e.id,
title: e.title,
...(typeof e.package === 'string' ? { package: e.package } : {}),
icon: iconOf(e.icon),
href: e.path,
})),
};
}
/**
* Global search across the consoles the viewer may open. The current console (`selfId`, already
* authorized by its own route guard) is searched without re-running its gate; the others only after
* their `authorize` allowed. Each `search` gets `timeoutMs` and returns at most `limit` hits; a hit
* whose `href` is not a same-origin path is dropped.
*/
export async function searchConsoles(registry, selfId, ctx, query, options = {}) {
const q = query.trim().slice(0, 200);
const result = { version: 1, query: q, groups: [] };
if (q.length === 0 || !registry)
return result;
const timeoutMs = options.timeoutMs ?? CONSOLE_PROBE_TIMEOUT_MS;
const limit = options.limit ?? CONSOLE_SEARCH_LIMIT;
const searchable = sortEntries(registry.entries.filter((e) => typeof e.search === 'function'));
const self = searchable.filter((e) => e.id === selfId);
const others = await allowedEntries(searchable.filter((e) => e.id !== selfId), ctx, timeoutMs, options.logger);
const targets = sortEntries([...self, ...others]);
const hits = await probing(ctx, () => Promise.all(targets.map((entry) => race(() => entry.search(ctx, q, limit), timeoutMs))));
targets.forEach((entry, i) => {
const found = hits[i];
if (!Array.isArray(found))
return;
const safe = found
.filter((h) => h && typeof h.title === 'string' && isSameOriginPath(h.href))
.slice(0, limit)
.map((h) => ({
title: h.title,
...(typeof h.subtitle === 'string' ? { subtitle: h.subtitle } : {}),
href: h.href,
}));
if (safe.length > 0) {
result.groups.push({
id: entry.id,
title: entry.title,
icon: iconOf(entry.icon),
hits: safe,
});
}
});
return result;
}
//# sourceMappingURL=console-switcher.js.map