UNPKG

@adonis-agora/agent

Version:

Governed, durable-backed AI agent (chat + tool-calling + governance) for AdonisJS — part of the Agora ecosystem.

74 lines • 2.94 kB
import { consoleAuthorizeFor } from '../console-authorize.js'; /** * One request's view of `devTools.actions`: each distinct `authorize` of the map runs at most once, * however many tools point at it. */ export class DevToolsActionsGate { #actions; #ctx; #caller; #decisions = new Map(); constructor(actions, ctx, caller) { this.#actions = actions; this.#ctx = ctx; this.#caller = caller; } /** Whether `actions` decides per caller (map or function), rather than statically. */ get dynamic() { return isDynamicActions(this.#actions); } /** `true` when the action tool is served to this request, else why not. */ async decide(action) { const actions = this.#actions; if (actions === 'execute') return true; // `null` / `undefined` from an untyped config: the default, refuse. if (actions === 'refuse' || actions === null || actions === undefined) { return { reason: 'not-configured' }; } if (Array.isArray(actions)) { return actions.includes(action.lib) || actions.includes(action.tool) ? true : { reason: 'not-configured' }; } if (typeof actions === 'function') { try { const allowed = await actions(this.#ctx, { ...action, caller: this.#caller }); return allowed === true ? true : { reason: 'denied' }; } catch (error) { return { reason: 'threw', error }; } } const authorize = own(actions, action.tool) ?? own(actions, action.lib); if (authorize === undefined) return { reason: 'not-configured' }; let decision = this.#decisions.get(authorize); if (decision === undefined) { decision = this.#run(authorize); this.#decisions.set(authorize, decision); } return decision; } async #run(authorize) { // An action tool changes something: a grant limited to reading (`access: 'read'`) is a denial. const decision = await consoleAuthorizeFor(authorize)(this.#ctx, undefined, { action: 'write', }); if (decision.allowed) return decision.access === 'read' ? { reason: 'denied' } : true; // `{ redirectTo }` and `401` are denials too: there is no page to send an MCP client to. return decision.error !== undefined ? { reason: 'threw', error: decision.error } : { reason: 'denied' }; } } /** Whether `actions` is the map or function form. */ export function isDynamicActions(actions) { return (typeof actions === 'function' || (actions !== null && typeof actions === 'object' && !Array.isArray(actions))); } function own(map, key) { return Object.hasOwn(map, key) ? map[key] : undefined; } //# sourceMappingURL=actions.js.map