/** * Built-in approval backends for the PraisonAI TypeScript SDK. * * Python parity: praisonaiagents/approval/backends.py (request/decision * shapes from praisonaiagents/approval/protocols.py; the "always" scope * suggestion from praisonaiagents/approval/utils.py `build_permission_target` * and praisonaiagents/permissions/arity.py `derive_pattern`). * * - {@link AutoApproveBackend}: always approves (bots, trusted environments). * - {@link ConsoleBackend}: interactive terminal prompt (CLI default); plain * ANSI colours instead of Rich markup, with injectable readers for tests. * - {@link AgentApproval}: delegates the decision to another AI agent. * - {@link CallbackBackend}: wraps a legacy `(toolName, arguments, riskLevel)` callback. * * Integration with the existing {@link ApprovalManager}: it has no backend * slot, only `onApprovalRequest(handler)`, so {@link setApprovalBackend} * registers one delegating handler per manager and swaps the backend behind it. * * `src/hooks/callbacks.ts` already exports `ApprovalRequest`/`ApprovalDecision` * with a different (action/risk) shape, so the Python-shaped types here are * named `ApprovalBackendRequest`/`ApprovalBackendDecision`. */ import { ApprovalManager, type ApprovalHandler, type ToolApprovalRequest } from '../ai/tool-approval'; /** How long an approval decision should be remembered. */ export type ApprovalScope = 'once' | 'session' | 'always'; /** * Request for tool-execution approval. * Python parity: `ApprovalRequest` (dataclass) in approval/protocols.py. */ export interface ApprovalBackendRequest { /** Name of the tool requesting approval. */ toolName: string; /** Arguments the tool will be called with. */ arguments: Record; /** Risk classification (critical / high / medium / low). */ riskLevel: string; /** Name of the agent that triggered the call. */ agentName?: string | null; /** Session identifier for tracking. */ sessionId?: string | null; /** Arbitrary context for backend-specific data (e.g. a rendered `diff`). */ context?: Record; /** Stable correlation id; auto-generated by {@link approvalRequest}. */ approvalId?: string; /** Reviewer identities allowed to resolve this request (null = anyone). */ authorizedReviewers?: string[] | null; /** Zero-arg predicate returning true while the originating turn is still live. */ liveness?: (() => boolean) | null; } /** * Result of an approval request. * Python parity: `ApprovalDecision` (dataclass) in approval/protocols.py. */ export interface ApprovalBackendDecision { approved: boolean; reason: string; /** Optional replacement arguments (empty = use originals). */ modifiedArgs: Record; /** Who/what approved (user, system, console, agent, ...). */ approver: string | null; metadata: Record; scope: ApprovalScope; /** Reusable target/pattern to persist for session/always scopes. */ scopePattern: string | null; /** Free-text guidance supplied when denying ("deny with guidance"). */ feedback: string | null; } /** Fields accepted by {@link approvalRequest}. */ export interface ApprovalRequestInit { toolName: string; arguments: Record; riskLevel: string; agentName?: string | null; sessionId?: string | null; context?: Record; approvalId?: string; authorizedReviewers?: string[] | null; liveness?: (() => boolean) | null; } /** * Build an {@link ApprovalBackendRequest} with the Python dataclass defaults * (`approvalId` is generated like Python's `uuid4().hex`). */ export declare function approvalRequest(init: ApprovalRequestInit): Required; /** Fields accepted by {@link approvalDecision}; only `approved` is required. */ export interface ApprovalDecisionInit { approved: boolean; reason?: string; modifiedArgs?: Record; approver?: string | null; metadata?: Record; scope?: ApprovalScope; scopePattern?: string | null; feedback?: string | null; } /** Build an {@link ApprovalBackendDecision} with the Python dataclass defaults. */ export declare function approvalDecision(init: ApprovalDecisionInit): ApprovalBackendDecision; /** * Structural contract every approval backend satisfies. * Python parity: `ApprovalProtocol` (request_approval / request_approval_sync). */ export interface ApprovalBackend { requestApproval(request: ApprovalBackendRequest): Promise; requestApprovalSync(request: ApprovalBackendRequest): ApprovalBackendDecision; } /** * Build a permission-store target for a tool call. * Python parity: `build_permission_target(tool_name, arguments=None)`. * Shell tools -> `bash:`, file tools -> `:`, * everything else -> `tool:`. */ export declare function buildPermissionTarget(toolName: string, args?: Record | null): string; /** * Command -> number of leading tokens to keep as the reusable prefix. * Python parity: `ARITY` in permissions/arity.py. */ export declare const ARITY: Readonly>; /** Return the longest meaningful command prefix for `tokens`. Python parity: `prefix(tokens, arity_map=None)`. */ export declare function commandPrefix(tokens: string[], arityMap?: Record | null): string; /** * Derive a reusable glob pattern for a shell approval target. * Python parity: `derive_pattern(target, arity_map=None)`. Only `bash:`/`shell:` * targets are generalised; a bare single-token command, an existing glob, or a * command containing a shell operator is returned unchanged. * * @example derivePattern('bash:git status -s') === 'bash:git status *' */ export declare function derivePattern(target: string, arityMap?: Record | null): string; /** Return a reusable "always" pattern for `request` (best-effort). Python parity: `_suggest_scope_pattern`. */ export declare function suggestScopePattern(request: ApprovalBackendRequest): string; /** * Always approves. Use for bots or trusted unattended environments. * Python parity: `AutoApproveBackend`. */ export declare class AutoApproveBackend implements ApprovalBackend { requestApproval(request: ApprovalBackendRequest): Promise; requestApprovalSync(request: ApprovalBackendRequest): ApprovalBackendDecision; } /** Options for {@link ConsoleBackend} (all optional; Python's class takes none). */ export interface ConsoleBackendOptions { /** Input stream for the default async reader (default: process.stdin). */ input?: NodeJS.ReadableStream; /** Output stream for prompts (default: process.stdout). */ output?: NodeJS.WritableStream; /** Injected async reader: receives the question, resolves the raw answer. */ reader?: (question: string) => Promise; /** Injected sync reader for `requestApprovalSync`. */ syncReader?: (question: string) => string; /** Force ANSI colours on/off (default: on when the output is a TTY and NO_COLOR is unset). */ colors?: boolean; } /** `(approved, scope, scopePattern, feedback)` as returned by Python's `_prompt_user`. */ export type ConsolePromptResult = [boolean, ApprovalScope, string | null, string | null]; /** * Interactive terminal prompt. Default for CLI usage. * * Python parity: `ConsoleBackend`. Renders the request (function, risk level, * agent, diff or arguments) and asks once / this session / always / no / * deny-and-redirect. Plain "y"/"yes" is accepted as "once" and "" defaults to * "no", matching the Python prompt default. * * @example * ```typescript * const backend = new ConsoleBackend({ reader: async () => 'y' }); * const decision = await backend.requestApproval(approvalRequest({ * toolName: 'execute_command', arguments: { command: 'ls' }, riskLevel: 'low', * })); * decision.approved; // true * ``` */ export declare class ConsoleBackend implements ApprovalBackend { private readonly input; private readonly output; private readonly reader?; private readonly syncReader?; private readonly colors; constructor(options?: ConsoleBackendOptions); /** * Render a unified diff with coloured +/- hunks, bounded to `maxLines`. * Python parity: `_render_diff_markup(diff, max_lines=40)` (ANSI instead of Rich markup). */ static renderDiffMarkup(diff: string, maxLines?: number, colors?: boolean): string; /** Build the panel text and the choice question for `request`. */ private buildPrompt; /** Map a raw answer to an outcome; unknown answers fall back to the "n" default. */ private interpret; private write; /** Ask one question with the injected reader or a readline interface. */ private ask; /** Ask one question synchronously with the injected reader or a blocking stdin read. */ private askSync; /** * Show the panel and ask once/session/always/no/deny-with-guidance. * Python parity: `_prompt_user(request)`; resolves * `[approved, scope, scopePattern, feedback]`. */ promptUser(request: ApprovalBackendRequest): Promise; /** Synchronous twin of {@link promptUser}. */ promptUserSync(request: ApprovalBackendRequest): ConsolePromptResult; private static toDecision; /** Synchronous approval via the console prompt. */ requestApprovalSync(request: ApprovalBackendRequest): ApprovalBackendDecision; /** Async approval via the console prompt. */ requestApproval(request: ApprovalBackendRequest): Promise; } /** Duck-typed approver: anything with `achat` or `chat`. */ export interface ApproverAgentLike { name?: string; achat?: (prompt: string) => Promise; chat?: (prompt: string) => unknown | Promise; } /** * Delegates approval decisions to another AI agent. * * Python parity: `AgentApproval(approver_agent=None, llm="gpt-4o-mini")`. The * approver receives a structured prompt and answers APPROVE or DENY. Without * an approver a default reviewer `Agent` is created lazily. * * `requestApprovalSync` cannot block on the event loop in JavaScript; it * returns a denial whose reason says to use `requestApproval` (Python's * error path also resolves to a denial with a reason). */ export declare class AgentApproval implements ApprovalBackend { private approverAgent; private readonly llm; constructor(approverAgent?: ApproverAgentLike | null, llm?: string); toString(): string; /** Lazily create or return the approver agent. Python parity: `_get_approver`. */ protected getApprover(): Promise; /** Build the evaluation prompt for the approver agent. Python parity: `_build_prompt`. */ protected buildPrompt(request: ApprovalBackendRequest): string; /** Ask the approver agent to evaluate the request. */ requestApproval(request: ApprovalBackendRequest): Promise; /** Not supported synchronously in JavaScript; resolves to a denial explaining why. */ requestApprovalSync(request: ApprovalBackendRequest): ApprovalBackendDecision; } /** Legacy `(functionName, arguments, riskLevel)` approval callback. */ export type LegacyApprovalCallback = (functionName: string, args: Record, riskLevel: string) => ApprovalBackendDecision | boolean | unknown | Promise; /** * Wraps a legacy `(functionName, arguments, riskLevel)` callback into an * {@link ApprovalBackend}. Python parity: `CallbackBackend(callback)`. */ export declare class CallbackBackend implements ApprovalBackend { private readonly callback; constructor(callback: LegacyApprovalCallback); requestApprovalSync(request: ApprovalBackendRequest): ApprovalBackendDecision; requestApproval(request: ApprovalBackendRequest): Promise; } /** Options for {@link approvalHandlerFromBackend} / {@link setApprovalBackend}. */ export interface BackendHandlerOptions { /** Risk level stamped on requests coming from `ApprovalManager` (it carries none). Default "medium". */ riskLevel?: string; /** Agent name stamped on requests. */ agentName?: string | null; } /** Convert an `ApprovalManager` request into the Python-shaped backend request. */ export declare function toApprovalBackendRequest(request: ToolApprovalRequest, options?: BackendHandlerOptions): ApprovalBackendRequest; /** Adapt an {@link ApprovalBackend} into an `ApprovalManager` handler. */ export declare function approvalHandlerFromBackend(backend: ApprovalBackend, options?: BackendHandlerOptions): ApprovalHandler; /** * Install `backend` as the approval backend of `manager` (default: the global * `ApprovalManager`). A single delegating handler is registered per manager * the first time; later calls swap the backend behind it. Passing `null` * detaches the backend (the handler then declines, so the manager's other * handlers or its event flow decide). * * @example * ```typescript * setApprovalBackend(new AutoApproveBackend()); * await getApprovalManager().requestApproval({ toolName: 'rm', input: {} }); // true * ``` */ export declare function setApprovalBackend(backend: ApprovalBackend | null, manager?: ApprovalManager, options?: BackendHandlerOptions): void; /** The approval backend installed on `manager` (default: the global one), or null. */ export declare function getApprovalBackend(manager?: ApprovalManager): ApprovalBackend | null;