/** * Tool Decorator and Registry - Type-safe tool creation and management * * Python parity with praisonaiagents/tools/decorator.py `tool()`. */ import { type ToolGuardrailChain, type ToolGuardrailSpec } from '../guardrails/tool-guardrails'; export interface ToolParameters { type: 'object'; properties: Record; required?: string[]; } /** Risk levels accepted by `approval` / `requiresApproval`, mirroring Python's `_VALID_RISK_LEVELS`. */ export declare const VALID_RISK_LEVELS: readonly ["critical", "high", "medium", "low"]; export type RiskLevel = typeof VALID_RISK_LEVELS[number]; /** Default retryable error classes, mirroring Python `RetryPolicy.retry_on`. */ export declare const DEFAULT_RETRY_ON: readonly ["timeout", "rate_limit", "connection_error"]; /** * Retry configuration for tool execution with exponential backoff. * Python parity with praisonaiagents/tools/retry.py `RetryPolicy`. */ export interface RetryPolicy { /** Total attempts including the first (default 3). */ maxAttempts?: number; /** Multiplier applied per attempt (default 2.0). */ backoffFactor?: number; /** Delay before the first retry in ms (default 1000). */ initialDelayMs?: number; /** Upper bound on any delay in ms (default 30000). */ maxDelayMs?: number; /** Error classes that trigger a retry (default timeout, rate_limit, connection_error). */ retryOn?: string[]; /** Randomise each delay by +/- jitterFactor (default false). */ jitter?: boolean; /** Jitter amplitude as a fraction of the delay (default 0.25). */ jitterFactor?: number; } export interface ToolConfig { name: string; description?: string; parameters?: ToolParameters | any; category?: string; execute: (params: TParams, context?: ToolContext) => Promise | TResult; /** Python parity: version (str, default "1.0.0"). */ version?: string; /** Python parity: availability (Optional[Callable[[], tuple[bool, str]]], default None). Returns [isAvailable, reason]; unavailable tools are left out of registry definitions. */ availability?: () => [boolean, string]; /** Python parity: dynamic_schema_overrides (Optional[Callable[[Dict[str, Any]], Dict[str, Any]]], default None). Applied to the parameters schema whenever a definition is produced. */ dynamicSchemaOverrides?: (schema: ToolParameters) => ToolParameters; /** Python parity: retry_policy (Optional[Any], default None). Exponential-backoff retries around execute(). */ retryPolicy?: RetryPolicy; /** Python parity: approval (Optional[Union[bool, str]], default None). `true` = "high" risk; a risk level string sets it explicitly. Gated through the global ApprovalManager. */ approval?: boolean | RiskLevel | string; /** Python parity: requires_approval (Union[bool, str], default _UNSET). Deprecated alias for `approval`; `approval` wins when both are set. */ requiresApproval?: boolean | RiskLevel | string; /** Python parity: to_model_output (Optional[Callable[[Any], Any]], default None). Shapes the value execute() hands to the model; executeRaw() keeps the full result. */ toModelOutput?: (result: TResult) => unknown; /** * Python parity: restart_safe (Optional[bool], default None). Replay * contract for durable resume. `true` marks a read-only/idempotent tool * that may be re-run after a crash; `false` marks an effectful tool that * must never be silently re-executed on resume; `undefined` falls back to * the read-only name heuristic ({@link isReadOnlyToolName}). Enforced by * `execute()` when the context carries `resumed: true`. */ restartSafe?: boolean; /** * Python parity: input_guardrails (Optional[Any], default None). Guardrails * that gate THIS tool's arguments before it runs. A single guardrail or an * array; each entry is a function taking the arguments, or an object * exposing `validateToolCall()`. A blocked call returns the reason to the * model instead of throwing. */ inputGuardrails?: ToolGuardrailSpec | ToolGuardrailSpec[]; /** * Python parity: output_guardrails (Optional[Any], default None). Guardrails * that gate THIS tool's raw result before it re-enters the LLM context. */ outputGuardrails?: ToolGuardrailSpec | ToolGuardrailSpec[]; } export interface ToolContext { agentName?: string; sessionId?: string; runId?: string; signal?: AbortSignal; /** * Set by a durable-resume caller when this call was in flight at the time * of a crash and is being replayed. Tools that are not restart-safe refuse * to run in that case (Python `DurableRunState.wrap_sync` gate). */ resumed?: boolean; } /** * Python parity: `ToolExecutionMixin._is_read_only_tool`. Tools whose names * imply mutation (write/edit/delete/create/run/exec/...) are not read-only. */ export declare function isReadOnlyToolName(name: string | undefined | null): boolean; /** * Thrown when a tool that is not restart-safe is asked to re-run a call * that was in flight when a durable run crashed. Mirrors Python's * `NotSafelyResumable` result. */ export declare class ToolNotRestartSafeError extends Error { readonly toolName: string; readonly errorType = "NotSafelyResumable"; readonly notSafelyResumable = true; readonly restartSafe = false; constructor(toolName: string); } export interface ToolDefinition { name: string; description: string; parameters: ToolParameters; category?: string; } /** * Map an execution error onto Python's retry error classes * ("timeout" | "rate_limit" | "connection_error" | "unknown"). */ export declare function classifyToolError(error: unknown): string; /** Delay for `attempt` (0-based) under `policy`, mirroring Python `RetryPolicy.get_delay_ms`. */ export declare function retryDelayMs(policy: RetryPolicy, attempt: number): number; /** * Tool class - Represents an executable tool */ export declare class FunctionTool { readonly name: string; readonly description: string; /** Base parameters schema (before dynamicSchemaOverrides). */ readonly parameters: ToolParameters; readonly category?: string; /** Python parity: version (str, default "1.0.0"). */ readonly version: string; /** Python parity: retry_policy. */ readonly retryPolicy?: RetryPolicy; /** Resolved approval requirement: `undefined`/`false` = none, `true` = "high", or an explicit risk level. */ readonly approval?: boolean | string; /** Python parity: restart_safe. */ readonly restartSafe?: boolean; private readonly executeFn; private readonly availabilityFn?; private readonly schemaOverride?; private readonly toModelOutputFn?; /** Python parity: coerced at definition time, like `@tool(...)` does. */ readonly inputGuardrails?: ToolGuardrailChain; readonly outputGuardrails?: ToolGuardrailChain; constructor(config: ToolConfig); /** * Python parity: `durable._is_restart_safe`. An explicit boolean * declaration wins; a malformed (non-boolean) declaration fails closed; * an undeclared tool falls back to the read-only name heuristic. */ get isRestartSafe(): boolean; private normalizeParameters; private zodToJsonSchema; private zodFieldToJsonSchema; /** * Python parity: `FunctionTool.check_availability()`. Returns * `[isAvailable, reason]`; a throwing check reports unavailable. */ checkAvailability(): [boolean, string]; /** `true` when the tool can currently be offered to a model. */ isAvailable(): boolean; /** * The parameters schema after `dynamicSchemaOverrides`. Re-evaluated on * every call so the override can react to runtime state; a throwing * override falls back to the base schema. */ getParameters(): ToolParameters; /** Whether a human must approve each call (AI SDK `needsApproval` shape). */ get needsApproval(): boolean; /** The risk level to report when approval is required (`true` maps to "high"). */ get riskLevel(): RiskLevel | undefined; private gateApproval; private runWithRetry; /** * Execute and return the full result: approval gate, then the function * under the retry policy. `toModelOutput` is not applied here. */ executeRaw(params: TParams, context?: ToolContext): Promise; /** * Python parity: `FunctionTool.to_model_output(result)`. The compact, * model-facing view of a result; the full result when no shaper is set or * the shaper throws. */ toModelOutput(result: TResult): unknown; /** * Execute the tool and return the model-facing result (after * `toModelOutput`). Use {@link executeRaw} for the full value. */ execute(params: TParams, context?: ToolContext): Promise; /** * Python parity: `FunctionTool.run(**kwargs)` — the name ported code calls. * * Returns the FULL result, as Python's `run()` does (the compact, * model-facing view is {@link toModelOutput}, applied by {@link execute}), * so this is the {@link executeRaw} value under a Python-shaped name. * * It deliberately runs the SAME gates as `executeRaw` — restart safety, the * approval gate, the retry policy — instead of calling the wrapped function * directly. Python can afford a raw `run()` because `@tool(approval=...)` * also records the requirement in the process-wide ApprovalRegistry, which * the agent consults by tool NAME; TypeScript holds the requirement only on * this instance, so a raw `run()` here would be an ungated second door onto * the same tool. */ run(params: TParams, context?: ToolContext): Promise; /** * Python parity: `BaseTool.validate()`. Throws {@link ToolValidationError} * listing every problem found; returns `true` when the tool is well formed. */ validate(): boolean; /** * Get the tool definition for LLM */ getDefinition(): ToolDefinition; /** * Get OpenAI-compatible tool format */ toOpenAITool(): { type: 'function'; function: { name: string; description: string; parameters: any; }; }; } /** * Create a tool from a configuration object */ export declare function tool(config: ToolConfig): FunctionTool; /** Trust levels a registered tool may declare (Python `ToolTrustLevel`). */ export declare const TOOL_TRUST_LEVELS: readonly ["trusted", "external"]; export type ToolTrustLevel = typeof TOOL_TRUST_LEVELS[number]; /** * Everything {@link ToolRegistry.register} accepts, mirroring Python's * `Union[BaseTool, Callable]`: a {@link FunctionTool}, a BaseTool-like object * with `run()`/`execute()`, or a plain function. */ export type RegisterableTool = FunctionTool | { name?: string; description?: string; parameters?: any; run?: Function; execute?: Function; } | ((...args: any[]) => any); /** * Options for {@link ToolRegistry.register} / {@link registerTool}. * * Python parity: `ToolRegistry.register(tool, name=None, overwrite=False, * trust_level=None, dynamic_schema_overrides=None)`. */ export interface RegisterToolOptions { /** Register under this name instead of the tool's own (Python `name`). */ name?: string; /** Replace an existing registration under the same name (Python `overwrite`). */ overwrite?: boolean; /** Trust level recorded for the entry (Python `trust_level`); read back with {@link ToolRegistry.getTrustLevel}. */ trustLevel?: ToolTrustLevel | string; /** Per-entry schema shaper applied on top of the tool's own (Python `dynamic_schema_overrides`). */ dynamicSchemaOverrides?: (schema: ToolParameters) => ToolParameters; } /** * Wrap a plain function as a {@link FunctionTool}, so * `register_tool(myFunction)` works the way it does in Python. * * The model returns NAMED arguments (`{ city: "Paris" }`) while a plain * function takes positional ones, so the wrapper maps the object back onto the * declared parameter order — the same mapping `Agent` applies to plain tool * functions. A schema is derived from those parameter names when the caller * supplies none. */ export declare function functionToTool(fn: (...args: any[]) => any, options?: { name?: string; description?: string; parameters?: ToolParameters; }): FunctionTool; /** * Coerce anything Python's registry would accept into a {@link FunctionTool}. * A `FunctionTool` passes through untouched, so its approval gate, retry * policy and restart-safety declaration are preserved. */ export declare function coerceToFunctionTool(tool: RegisterableTool, name?: string): FunctionTool; /** * Tool Registry — the Python-equivalent registry (`praisonaiagents/tools/registry.py`). * * Holds ready-to-run tools looked up BY NAME. This is the registry the * snake_case parity names ({@link get_registry}, {@link register_tool}, * {@link get_tool}) resolve to. The separate `tools/registry/` module is a * registry of tool FACTORIES with a different contract; see * `getToolsRegistry()` there. */ export declare class ToolRegistry { private tools; /** * Register a tool. Accepts a {@link FunctionTool}, a BaseTool-like object, * or a plain function (Python `register(tool, name, overwrite, trust_level, * dynamic_schema_overrides)`); anything that is not already a `FunctionTool` * is wrapped in one. * * Throws when the name is taken and `overwrite` is not set — the global * {@link registerTool} helper follows Python and skips instead. */ register(tool: RegisterableTool, options?: RegisterToolOptions): this; get(name: string): FunctionTool | undefined; has(name: string): boolean; /** Remove a tool; `true` if one was removed (Python `unregister`). */ unregister(name: string): boolean; /** The names under which tools are registered (Python `list_tools`). */ listTools(): string[]; /** Every registered tool keyed by its registration name (Python `get_all`). */ getAll(): Record; /** The trust level recorded for a registration, if any (Python `get_trust_level`). */ getTrustLevel(name: string): string | undefined; /** Every registered tool, available or not. */ list(): FunctionTool[]; /** Registered tools whose availability check passes. */ listAvailable(): FunctionTool[]; /** Registered tools that are currently unavailable, with the reason each gave. */ listUnavailable(): Array<{ tool: FunctionTool; reason: string; }>; getByCategory(category: string): FunctionTool[]; /** Registered tools that may be re-run after a durable-resume crash ({@link FunctionTool.isRestartSafe}). */ listRestartSafe(): FunctionTool[]; /** The entry's parameters schema, with the entry-level override applied last. */ private entryParameters; /** * Available entries paired with the NAME they are registered under. * * A tool registered with `{ name: 'renamed' }` is keyed as `'renamed'` even * though its own `.name` is unchanged. Model definitions must advertise the * registration key, because that is the name the agent dispatches on — see * {@link get}, which looks up by key. Advertising `entry.tool.name` would * offer a name the registry cannot resolve. */ private availableNamedEntries; /** Definitions offered to a model: unavailable tools are excluded. */ getDefinitions(): ToolDefinition[]; /** OpenAI tool payloads offered to a model: unavailable tools are excluded. */ toOpenAITools(): Array<{ type: 'function'; function: any; }>; delete(name: string): boolean; clear(): void; get size(): number; } /** * The process-wide tool registry (Python `get_registry`). */ export declare function getRegistry(): ToolRegistry; /** * Register a tool with the global registry (Python `register_tool`). * * Accepts what Python accepts — a {@link FunctionTool}, a BaseTool-like * object, or a plain function — and, like Python, SKIPS a name that is * already taken unless `overwrite` is set, rather than throwing. */ export declare function registerTool(tool: RegisterableTool, options?: RegisterToolOptions): void; /** Look a tool up by name in the global registry (Python `get_tool`). */ export declare function getTool(name: string): FunctionTool | undefined; /** Whether a name is registered globally (Python `has_tool`). */ export declare function hasTool(name: string): boolean; /** Remove a tool from the global registry (Python `remove_tool`). */ export declare function removeTool(name: string): boolean; /** Names of every globally registered tool (Python `list_tools`). */ export declare function listTools(): string[]; /** OpenAI tool definitions for every available global tool (Python `get_tool_definitions`). */ export declare function getToolDefinitions(): ToolDefinition[]; /** Python `get_registry()`. */ export declare const get_registry: typeof getRegistry; /** Python `register_tool(tool, name=None, trust_level=None, dynamic_schema_overrides=None)`. */ export declare const register_tool: typeof registerTool; /** Python `get_tool(name)`. */ export declare const get_tool: typeof getTool; /** Python `has_tool(name)`. */ export declare const has_tool: typeof hasTool; /** Python `remove_tool(name)`. */ export declare const remove_tool: typeof removeTool; /** Python `list_tools()`. */ export declare const list_tools: typeof listTools; /** Python `get_tool_definitions()`. */ export declare const get_tool_definitions: typeof getToolDefinitions; /** Python `add_tool(...)` — the simplified alias for `register_tool`. */ export declare const add_tool: typeof registerTool;