import type { DbAdapter } from '../db/types'; import type { LLMProvider } from '../llm/providers/types'; import { ApprovalManager } from '../ai/tool-approval'; import { Handoff } from './handoff'; import { type MemoryConfig } from '../memory/memory'; import { KnowledgeBase, type KnowledgeBaseConfig } from '../knowledge/rag'; import { Guardrail, type GuardrailConfig, type GuardrailContext, type GuardrailResult } from '../guardrails'; import { HooksManager, type HookEvent, type HookHandler } from '../hooks/manager'; import { ContextManager, type ContextManagerConfig } from '../context/manager'; import { RulesManager, type Rule, type RulesManagerConfig } from '../memory/rules-manager'; import type { SkillManager, SkillDiscoveryOptions } from '../skills'; import type { PlanningAgentConfig, Plan } from '../planning'; import type { LLMConfig } from '../llm'; import type { Task } from './types'; import { type TaskContext } from './features/chat-options'; import { type ResolvedAgentRuntime } from './features/runtime'; import { type ExecuteCodeOptions, type SandboxConfig as AgentSandboxConfig, type SandboxResult } from './features/sandbox'; import { type MessageSteeringProtocol } from './features/message-steering'; import { type SkillProposal } from './features/self-improve'; import { type AutonomyConfig } from './features/autonomy'; import type { LearnManager } from '../memory/learn'; import { type ReflectionRound } from './features/reflection'; import { type ManagedBackendLike, type ToolPlaceLike } from './features/placement'; /** * The default token sink for `start()` when no `onToken` is supplied. * * Exported so a test can call it rather than re-implementing the guard. A * webview has no `stdout`: unguarded, this threw on the FIRST streamed token, * so streaming died immediately even though the constructor had succeeded. */ export declare function writeTokenToStdout(token: string): void; /** * Agent Configuration * * The Agent class is the primary entry point for PraisonAI. * It supports both simple instruction-based agents and advanced configurations. * * @example Simple usage (3 lines) * ```typescript * import { Agent } from 'praisonai'; * const agent = new Agent({ instructions: "You are helpful" }); * await agent.chat("Hello!"); * ``` * * @example With tools (5 lines) * ```typescript * const getWeather = (city: string) => `Weather in ${city}: 20°C`; * const agent = new Agent({ * instructions: "You provide weather info", * tools: [getWeather] * }); * await agent.chat("Weather in Paris?"); * ``` * * @example With persistence (4 lines) * ```typescript * import { Agent, db } from 'praisonai'; * const agent = new Agent({ * instructions: "You are helpful", * db: db("sqlite:./data.db"), * sessionId: "my-session" * }); * await agent.chat("Hello!"); * ``` */ /** * Terminal reason for the most recent agent run, mirroring Python's * `Agent.last_stop_reason`. Lets callers distinguish a completed run from a * truncated one instead of both looking identical. */ export type StopReason = 'completed' | 'max_steps' | 'cancelled' | 'error'; /** * A single conversation message, as stored on the Agent. * * This is the shape returned by {@link Agent.getHistory} and accepted by * {@link Agent.setHistory}. It carries the tool context (`tool_calls`, * `tool_call_id`) so a saved conversation round-trips without silently * dropping tool calls or their results — persisting `getHistory()` output is * the intended way to save a chat for later restoration. */ export interface AgentMessage { /** The provider role. A restored message with any other value is rejected. */ readonly role: 'system' | 'user' | 'assistant' | 'tool'; /** Text content. `null` on an assistant turn that only called tools. */ readonly content: string | null; /** Present on an assistant turn that called tools. */ readonly tool_calls?: ReadonlyArray<{ id: string; type: string; function: { name: string; arguments: string; }; }>; /** Present on a tool turn; pairs it to the `tool_calls` entry above. */ readonly tool_call_id?: string; /** * The tool's name, present on a `tool` turn. Required so the AI SDK adapter * (`toAISDKPrompt`) can set a non-empty `toolName` on the tool-result part — * without it, a restored tool history sent to a non-OpenAI provider is * rejected. The live tool loop already records this (`processToolCalls`); it * must survive the getHistory/setHistory round-trip too. */ readonly name?: string; } export interface SimpleAgentConfig { /** * Agent instructions/system prompt. Optional: when omitted the prompt is * built from role/goal/backstory, else a default assistant prompt is used. * Python parity: instructions (Optional[str]). */ instructions?: string; /** Agent name (auto-generated if not provided) */ name?: string; /** Enable verbose logging (default: true) */ verbose?: boolean; /** Enable pretty output formatting */ pretty?: boolean; /** * LLM model to use. Accepts: * - Model name: "gpt-4o-mini", "claude-3-sonnet" * - Provider/model: "openai/gpt-4o", "anthropic/claude-3" * Default: "gpt-4o-mini" * Also accepts an LLMConfig object ({ model, temperature, maxTokens, * apiKey, baseURL }). Python parity: llm (Optional[Union[str, Any]]). */ llm?: string | LLMConfig; /** * Canonical model name as documented by the Python SDK. `llm` remains * accepted; when both are given `model` wins. * Python parity: model (Optional[Union[str, Any]]). */ model?: string; /** * API key for the LLM provider. Mirrors Python's per-agent `api_key` * (agent/agent.py). Falls back to OPENAI_API_KEY when omitted. */ apiKey?: string; /** * Base URL for the LLM provider. Mirrors Python's per-agent `base_url` * (agent/agent.py). Useful for OpenAI-compatible endpoints. */ baseURL?: string; /** * Custom fetch implementation. Lets a host route provider egress through * native code (e.g. a Tauri command), keeping the API key out of the JS * heap and avoiding CORS for embedded webviews. Implies browser support. */ fetch?: typeof fetch; /** Enable markdown formatting in responses */ markdown?: boolean; /** Enable streaming responses (default: true) */ stream?: boolean; /** * Tools available to the agent. * Can be plain functions (auto-schema) or OpenAI tool definitions. */ tools?: any[] | Function[]; /** * JSON Schema for structured output (mirrors Python's output_json / * output_pydantic). When set, responses are constrained via OpenAI's * response_format json_schema and the raw JSON string is returned. */ outputSchema?: Record; /** Name for the outputSchema (default: "response") */ outputSchemaName?: string; /** Map of tool function implementations */ toolFunctions?: Record; /** * Human-in-the-loop approval gate for tool calls (mirrors Python's * `approval`). When `true`, every tool is gated behind an interactive CLI * prompt (approve/deny per call); pass an `ApprovalManager` instance to use * custom handlers / auto-approve-deny rules (e.g. a UI responder). Denied * calls are reported back to the model as the tool result rather than * throwing, so it can course-correct. */ approval?: boolean | ApprovalManager; /** * Maximum number of tool-call round-trips before the loop is aborted * (default: 20, matching Python's `ExecutionConfig.max_iter`). When the cap * is reached the run sets `lastStopReason = 'max_steps'` and throws instead * of silently returning an empty string, so exhaustion is observable. */ maxIterations?: number; /** * Maximum number of tool calls executed within a single round-trip * (default: 10, matching Python's `ExecutionConfig.max_tool_calls_per_turn`). * Extra tool calls beyond this cap in one turn are ignored. */ maxToolCallsPerTurn?: number; /** Database adapter for persistence */ db?: DbAdapter; /** Session ID for conversation persistence (auto-generated if not provided) */ sessionId?: string; /** Run ID for tracing (auto-generated if not provided) */ runId?: string; /** Max messages to restore from history (default: 100) */ historyLimit?: number; /** Auto-restore conversation history from db (default: true) */ autoRestore?: boolean; /** Auto-persist messages to db (default: true) */ autoPersist?: boolean; /** Enable caching of responses */ cache?: boolean; /** Cache TTL in seconds (default: 3600) */ cacheTTL?: number; /** Enable telemetry tracking (default: false, opt-in) */ telemetry?: boolean; /** * Default abort signal for cancellation. Aborting it stops the underlying * provider request (a working Stop button). An explicit signal passed to * chat()/start() takes precedence over this. Mirrors Python's * interrupt_controller / cancel_token. */ signal?: AbortSignal; /** Python parity: auth (Optional[str]). Subscription auth provider, e.g. "claude-code". */ auth?: string; /** Python parity: toolsets (Optional[List[str]]). Named toolset groups. */ toolsets?: string[]; /** * Agents (or Handoff objects) this agent may transfer the conversation to. * Each becomes a `transfer_to_` tool and the system prompt lists them. * Python parity: handoffs (Optional[List[Union['Agent', 'Handoff']]]). */ handoffs?: (Agent | Handoff)[]; /** * Conversation memory: `true` for an in-memory store, a MemoryConfig, a * JSONL file path, or any store with `search()`/`add()` (Memory, FileMemory). * Relevant memories are injected into the system prompt on every turn. * Python parity: memory (Optional[Union[bool, str, 'MemoryConfig', Any]]). */ memory?: boolean | string | MemoryConfig | AgentMemoryStore; /** * Retrieval knowledge: `true`, a KnowledgeBaseConfig, a KnowledgeBase, or * file/directory paths that are loaded on first use. Matching documents are * injected into the system prompt. * Python parity: knowledge (Optional[Union[bool, str, List[str], 'KnowledgeConfig', 'Knowledge']]). */ knowledge?: boolean | string | string[] | KnowledgeBaseConfig | KnowledgeBase; /** * Plan-then-execute: a plan is drafted with PlanningAgent before each turn * and appended to the prompt. A string selects the planner model. * Python parity: planning (Optional[Union[bool, str, 'PlanningConfig']]). */ planning?: boolean | string | PlanningAgentConfig; /** Python parity: reflection (Optional[Union[bool, str, 'ReflectionConfig']]). */ reflection?: boolean | string | Record; /** * Output rules: `true` enables the built-in safety rules, or pass Rule[], * a RulesManagerConfig or a RulesManager. Blocking rules throw. * Python parity: rules (Optional[Union[bool, 'RulesConfig']]). */ rules?: boolean | Rule[] | RulesManagerConfig | RulesManager; /** * Output guardrails: a check function, a Guardrail, a GuardrailConfig, a * criteria string (validated by an LLM guardrail), or a list of those. * Python parity: guardrails (Optional[Union[bool, str, Callable, 'GuardrailConfig']]). */ guardrails?: AgentGuardrailInput; /** * How many times a rejected answer may be sent back to the model with the * guardrail's reason appended, within the same run. Python parity: * `GuardrailConfig(max_retries=...)` / `max_guardrail_retries`. * * Defaults to 0, which preserves the previous behaviour exactly: a blocking * guardrail throws immediately. Set it to enable in-conversation correction. */ maxGuardrailRetries?: number; /** * Web search tool: `true` (Tavily), a provider name (tavily, exa, * perplexity, parallel) or `{ provider, ...providerConfig }`. * Python parity: web (Optional[Union[bool, str, 'WebConfig']]). */ web?: boolean | string | AgentWebConfig; /** * Context budgeting: `true`, a ContextManagerConfig or a ContextManager. * Every turn is recorded into it; read it back via getContextManager(). * Python parity: context (Optional[Union[bool, str, Dict[str, Any], 'ContextConfig', 'ContextManager']]). */ context?: boolean | string | ContextManagerConfig | ContextManager; /** Python parity: autonomy (Optional[Union[bool, str, Dict[str, Any], 'AutonomyConfig']]). */ autonomy?: boolean | string | Record; /** Python parity: templates (Optional[Union[Dict[str, Any], 'TemplateConfig']]). */ templates?: Record; /** * Lifecycle hooks: a HooksManager, `{ event: handler }` or a list of * `{ event, handler }`. Fired: agent_start, agent_complete, pre_tool_call, * post_tool_call. A handler returning null blocks the operation. * Python parity: hooks (Optional[Union[List[Any], Dict[str, Any], 'HooksConfig']]). */ hooks?: AgentHooksInput; /** * Skills (SKILL.md): skill names, skill directories, discovery options or * a SkillManager. Loaded on first use and injected into the system prompt. * Python parity: skills (Optional[Union[List[str], str, Dict[str, Any], 'SkillsConfig']]). */ skills?: string | string[] | SkillDiscoveryOptions | SkillManager; /** Python parity: self_improve (Optional[Union[bool, str, 'SkillReviewProtocol']]). */ selfImprove?: boolean | string | Record; /** Python parity: tool_config (Optional[Union[bool, 'ToolConfig']]). */ toolConfig?: boolean | Record; /** Python parity: learn (Optional[Union[bool, str, Dict[str, Any], 'LearnConfig']]). */ learn?: boolean | string | Record; /** Python parity: backend (Optional[Any]). */ backend?: unknown; /** Python parity: run_on (Optional[Union['ManagedRuntime', str]]). */ runOn?: string | Record; /** Python parity: tools_run_on (Optional[Union['ToolPlace', str, Any]]). */ toolsRunOn?: string | Record; /** Python parity: runtime (Optional[Union[bool, str, Dict[str, Any], 'AgentRuntimeConfig', 'RuntimeConfig']]). */ runtime?: boolean | string | Record; /** Python parity: tool_search (Optional[Union[bool, str, Dict[str, Any], 'ToolSearchConfig']]). */ toolSearch?: boolean | string | Record; /** Python parity: message_steering (Optional[Union[bool, 'MessageSteeringProtocol']]). */ messageSteering?: boolean | Record; /** Python parity: sandbox (Optional[Union[bool, 'SandboxConfig']]). */ sandbox?: boolean | Record; /** * Retry transient provider failures (429, 5xx, ECONNRESET, ETIMEDOUT) with * jittered exponential backoff. `true` uses the Python defaults. * Python parity: retry (Optional[Union[bool, Dict[str, Any], 'RetryBackoffConfig']]). */ retry?: boolean | AgentRetryConfig; /** * Reasoning effort forwarded as `reasoning_effort` on OpenAI-compatible * requests: off | minimal | low | medium | high. * Python parity: reasoning_effort (Optional[str]). */ reasoningEffort?: 'off' | 'minimal' | 'low' | 'medium' | 'high' | string; /** Agent role (advanced mode) */ role?: string; /** Agent goal (advanced mode) */ goal?: string; /** Agent backstory (advanced mode) */ backstory?: string; } /** * A store usable for {@link SimpleAgentConfig.memory}. Both `Memory` and * `FileMemory` from src/memory satisfy it. */ export interface AgentMemoryStore { search(query: string, limit?: number): Promise>; add(content: string, role: 'user' | 'assistant' | 'system', metadata?: Record): Promise; } /** * A guardrail check as accepted by {@link SimpleAgentConfig.guardrails}. Besides * a full GuardrailResult it may return a boolean or Python's `(ok, value)` * tuple, where `value` is the replacement content on success or the reason on * failure. */ export type AgentGuardrailFunction = (content: string, context?: GuardrailContext) => GuardrailResult | boolean | [boolean, unknown] | Promise; export type AgentGuardrailEntry = string | AgentGuardrailFunction | Guardrail | GuardrailConfig; export type AgentGuardrailInput = boolean | AgentGuardrailEntry | AgentGuardrailEntry[]; /** Hooks as accepted by {@link SimpleAgentConfig.hooks}. */ export type AgentHooksInput = HooksManager | Array<{ event: HookEvent; handler: HookHandler; }> | Partial>; /** Web search configuration: `provider` plus that provider's own options. */ export interface AgentWebConfig { provider?: 'tavily' | 'exa' | 'perplexity' | 'parallel' | string; [option: string]: unknown; } /** * Retry with jittered exponential backoff. Delays are in seconds and default * to Python's RetryBackoffConfig (baseDelay 5, maxDelay 120, jitterRatio 0.5, * maxRetries 3). */ export interface AgentRetryConfig { maxRetries?: number; baseDelay?: number; maxDelay?: number; jitterRatio?: number; /** Override the retryable-error test (default: 429, 5xx, ECONNRESET, ETIMEDOUT). */ shouldRetry?: (error: unknown) => boolean; } /** * The duck-type Python's `Agent.execute` looks for: `hasattr(task, 'description')` * (praisonaiagents/agent/execution_mixin.py). A {@link Task} satisfies it, and * so does any plain object carrying a `description` string. */ export interface AgentTaskLike { description?: string | null; [key: string]: unknown; } /** * What {@link Agent.execute} accepts as its task. * * {@link Task} is listed alongside {@link AgentTaskLike} because a class * instance gets no implicit index signature in TypeScript, so a real `Task` * would not satisfy `AgentTaskLike` -- and `agent.execute(task)`, the exact * call this method exists to support, would fail to compile. */ export type AgentExecuteTask = string | AgentTaskLike | Task; /** * Per-call options for {@link Agent.chat} (and {@link Agent.stream}), mirroring * the keyword arguments of Python's `Agent.chat`. */ export interface AgentChatOptions { /** Python parity: temperature (Optional[float]). Sampling temperature for this call. */ temperature?: number; /** Python parity: tools (Optional[List[Any]]). Tools for this call only (replaces the agent's). */ tools?: any[]; /** Python parity: output_json (Optional[Any]). JSON Schema for structured output on this call. */ outputJson?: Record; /** * Python parity: output_pydantic (Optional[Any]). A JSON Schema, an object * with `toJSONSchema()`, or a zod schema (converted via zod-to-json-schema). */ outputPydantic?: Record; /** Python parity: reasoning_steps (bool). */ reasoningSteps?: boolean; /** Python parity: stream (Optional[bool]). Overrides the agent's `stream` for this call. */ stream?: boolean; /** Python parity: task_name (Optional[str]). */ taskName?: string; /** Python parity: task_description (Optional[str]). */ taskDescription?: string; /** Python parity: task_id (Optional[str]). */ taskId?: string; /** Python parity: config (Optional[Dict[str, Any]]). */ config?: Record; /** Python parity: force_retrieval (bool). Knowledge/memory retrieval already runs whenever a source is configured. */ forceRetrieval?: boolean; /** Python parity: skip_retrieval (bool). Skip knowledge/memory retrieval for this call. */ skipRetrieval?: boolean; /** Python parity: attachments (Optional[List[str]]). */ attachments?: string[]; /** Python parity: tool_choice (Optional[str]). "auto" | "none" | "required" | a tool name. */ toolChoice?: 'auto' | 'none' | 'required' | string; /** Python parity: seed (Optional[int]). Forwarded on OpenAI-compatible requests. */ seed?: number; } /** * Per-call options for {@link Agent.chat} only. * * `errorsAsNull` lives here rather than on {@link AgentChatOptions} on purpose: * `start()` and `stream()` accept AgentChatOptions and do NOT honour it, and an * option that is accepted and ignored is the defect this package keeps a ledger * for (see `utils/parity-notice.ts`). */ export interface AgentChatCallOptions extends AgentChatOptions { /** * Opt in to Python's error contract: resolve with `null` instead of * rejecting when the turn fails. * * Python's `Agent.chat` catches `Exception` around the LLM call, reports it * through `display_error`, and returns `None` * (praisonaiagents/agent/chat_mixin.py, the two * `except Exception ... return None` arms at the end of `_chat_impl`), so * Python code is written as `result = agent.chat(...)` followed by * `if result is None:`. TypeScript rejects instead, which is the better * default -- a failure that is ignored is a failure that ships -- so this is * opt-in and per call, and the default is unchanged. * * What is NOT swallowed, matching Python's own re-raises: cancellation * (an aborted signal, or an `AbortError`/`InterruptedError`), * `ToolExecutionError`, and `BudgetExceededError`. The swallowed error is * still reported through {@link Logger}, mirroring Python's `display_error`, * so a failed turn is never silent. */ errorsAsNull?: boolean; } /** * Discriminated union emitted by {@link Agent.streamEvents}. * * Mirrors Python's `StreamEvent` channel (praisonaiagents streaming/events.py): * structured information travels here while {@link Agent.stream} yields plain * text tokens. `text` carries an incremental delta; `finish` carries the full * response; `error` carries a thrown error. */ export type AgentEvent = { type: 'text'; delta: string; } /** * A tool is about to run. `callId` is the provider's id for this invocation * and is the ONLY key that may pair a result to its call -- matching by * position holds only while exactly one call is ever in flight, and silently * attributes the wrong output the moment that stops being true. */ | { type: 'tool_call'; callId: string; name: string; args: Record; } /** * A tool finished. `ok` is the only signal of success: never infer it from a * non-empty `output`, because a tool that failed with a message looks * identical to one that succeeded with one. */ | { type: 'tool_result'; callId: string; name: string; ok: boolean; output: string; } | { type: 'finish'; text: string; } | { type: 'error'; error: Error; }; /** * Options for {@link Agent.stream} / {@link Agent.streamEvents}. Accepts every * {@link AgentChatOptions} member as well (`stream: false` makes the run * non-streaming, so only a terminal `finish` event carries the text). */ export interface AgentStreamOptions extends AgentChatOptions { /** Previous result to substitute for the `{{previous}}` placeholder. */ previousResult?: string; /** * Turn-scoped abort signal. Aborting it stops the underlying provider * request so no further tokens are generated or billed. Independent of the * agent-level `SimpleAgentConfig.signal`: cancel one turn while keeping the * agent. Breaking out of the `for await` loop also aborts automatically — * the iterator's `return()` is the language's own cancellation signal. */ signal?: AbortSignal; } export declare class Agent { private instructions; name: string; /** * Python parity: `Agent.role` (`role or "Assistant"`). Python always * materialises role/goal/backstory and exposes them via `to_dict()` and * `__repr__`; TypeScript used to read them once to build `instructions` and * then drop them, so `agent.role` was `undefined` where Python said * `"Assistant"`, and anything deriving text from them (a handoff's tool * description) had nothing to read. */ readonly role: string; /** Python parity: `Agent.goal` (`goal or instructions or "Help the user with their tasks"`). */ readonly goal: string; /** Python parity: `Agent.backstory` (`backstory or instructions or "I am an AI assistant"`). */ readonly backstory: string; private verbose; private pretty; private llm; private markdown; private streamEnabled; private llmService; private tools?; private outputSchema?; private outputSchemaName; private toolFunctions; private approvalManager?; private maxIterations; private maxToolCallsPerTurn; /** * Terminal reason for the most recent run (mirrors Python's * `Agent.last_stop_reason`). `null` until the agent has run at least once. */ lastStopReason: StopReason | null; /** * Text the agent last produced, for {@link Agent.getResult}. `null` until the * agent has completed a turn; set by {@link Agent.runTurn}, which every * public entry point (start, chat, execute, stream, streamEvents) goes * through. */ private _lastResult; private dbAdapter?; private sessionId; private runId; private messages; private dbInitialized; private historyLimit; private autoRestore; private autoPersist; private cache; private cacheTTL; private responseCache; private telemetryEnabled; private signal?; private _backend; private _backendPromise; private _backendSource; private _useAISDKBackend; private _apiKey?; private _baseURL?; private _fetch?; /** True when the outgoing fetch is wrapped so body extras (seed, reasoning_effort) can be injected. */ private _fetchWrapped; /** Whether the caller chose the model explicitly (AgentTeam only overrides an implicit default). */ private _llmExplicit; private defaultTemperature; private defaultMaxTokens?; private _turnSeed?; private _currentPrompt?; /** Python `task_name`/`task_description`/`task_id` of the most recent turn. */ private _taskContext?; /** Resolved from `backend`/`runOn`: the managed runtime the whole agent runs on. */ private _managedBackend?; /** Resolved from `toolsRunOn`: where this agent's tool calls execute. */ private _toolPlace?; /** Resolved from `reflection`: the self-critique loop's settings. */ private _reflectionConfig?; /** Resolved from `templates`: system/prompt/response wrappers. */ private _templates?; /** Resolved from `toolSearch`: progressive tool disclosure settings. */ private _toolSearchConfig?; /** The tool-search decision for the turn in flight (bridge mode + deferred set). */ private _toolSearchTurn?; /** Tool names the configured `toolsets` resolved to (validated in the constructor). */ private _toolsetToolNames; private _toolsetsAttached; /** Resolved from `learn`: continuous-learning settings, or `undefined` when off. */ private _learnConfig?; private _learnManager?; /** Turns since the last learning nudge (Python `_turns_since_nudge`). */ private _turnsSinceNudge; /** Tool calls executed in the most recent turn (Python `_recent_tool_calls_count`). */ private _recentToolCalls; /** Resolved from `toolConfig`: timeout, retry, output budget, global-tool lookup. */ private _toolConfig?; /** Resolved from `autonomy`: how much the agent may do without asking. */ private _autonomyConfig?; /** Spots the model repeating itself, so a loop costs 3 calls rather than the whole budget. */ private _doomLoop?; /** Resolved from `selfImprove`: the post-task skill review. */ private _selfImprove?; /** Guards against a review turn triggering another review. */ private _inSkillReview; /** Tool names used in the turn just finished (the review policy's input). */ private _turnToolsUsed; /** Skills the most recent review turn proposed. */ lastSkillProposals: SkillProposal[]; /** Resolved from `messageSteering`: the live-guidance queue, or `undefined` when off. */ private _messageSteering?; /** Resolved from `sandbox`: where `executeCode()` runs, or `undefined` when unset. */ private _sandboxConfig?; /** Runners cached per sandbox type: a fresh one per call would restart a container each time. */ private _sandboxRunners; /** Resolves once, on the first turn: the subscription credentials `auth` names. */ private _authPromise?; /** Resolved from `runtime`: the runtime each turn is delegated to. */ private _runtime?; /** Every critique made during the most recent turn (Python `display_self_reflection`). */ lastReflections: ReflectionRound[]; /** Python parity: handoffs (Optional[List[Union['Agent', 'Handoff']]]). Registered as transfer tools. */ readonly handoffs: Handoff[]; /** Python parity: planning (Optional[Union[bool, str, 'PlanningConfig']]). */ readonly planning: boolean | string | PlanningAgentConfig; /** The plan produced for the most recent turn when `planning` is enabled. */ lastPlan: Plan | null; /** Python parity: reasoning_effort (Optional[str]). */ readonly reasoningEffort?: string; private memory?; private _memoryFile?; private knowledge?; private _knowledgeSources; private _knowledgeLoaded; private guardrails; private maxGuardrailRetries; private rules?; private hooks?; private contextManager?; private _skillsInput?; private _webInput?; private _webAttached; private _skillsPrompt?; private retryConfig?; /** Python parity: auth (Optional[str]). */ readonly auth?: string; /** Python parity: toolsets (Optional[List[str]]). */ readonly toolsets?: string[]; /** Python parity: reflection (Optional[Union[bool, str, 'ReflectionConfig']]). */ readonly reflection?: boolean | string | Record; /** Python parity: autonomy (Optional[Union[bool, str, Dict[str, Any], 'AutonomyConfig']]). */ readonly autonomy?: boolean | string | Record; /** Python parity: templates (Optional[Union[Dict[str, Any], 'TemplateConfig']]). */ readonly templates?: Record; /** Python parity: self_improve (Optional[Union[bool, str, 'SkillReviewProtocol']]). */ readonly selfImprove: boolean | string | Record; /** Python parity: tool_config (Optional[Union[bool, 'ToolConfig']]). */ readonly toolConfig?: boolean | Record; /** Python parity: learn (Optional[Union[bool, str, Dict[str, Any], 'LearnConfig']]). */ readonly learn?: boolean | string | Record; /** Python parity: backend (Optional[Any]). */ readonly backend?: unknown; /** Python parity: run_on (Optional[Union['ManagedRuntime', str]]). */ readonly runOn?: string | Record; /** Python parity: tools_run_on (Optional[Union['ToolPlace', str, Any]]). */ readonly toolsRunOn?: string | Record; /** Python parity: runtime (Optional[Union[bool, str, Dict[str, Any], 'AgentRuntimeConfig', 'RuntimeConfig']]). */ readonly runtime?: boolean | string | Record; /** Python parity: tool_search (Optional[Union[bool, str, Dict[str, Any], 'ToolSearchConfig']]). */ readonly toolSearch: boolean | string | Record; /** Python parity: message_steering (Optional[Union[bool, 'MessageSteeringProtocol']]). */ readonly messageSteering: boolean | Record; /** Python parity: sandbox (Optional[Union[bool, 'SandboxConfig']]). */ readonly sandbox?: boolean | Record; constructor(config: SimpleAgentConfig); /** * Point the agent at `modelName`: pick the provider path (OpenAI-compatible * vs AI SDK) and rebuild the OpenAI service. Used by the constructor and by * {@link Agent.applyDefaultModel}. */ private configureModel; /** * Adopt `model` when the agent was constructed without an explicit * `llm`/`model` (Python parity: AgentTeam's `llm`/`model` is the default for * member agents). Returns whether the model was applied. */ applyDefaultModel(model: string): boolean; /** * Convert a tools array (plain functions, FunctionTool-like objects with * `execute`, or OpenAI tool definitions) into OpenAI tool definitions pushed * into `sink`, registering the implementations on this agent. Iterates a * SNAPSHOT of the input: an auto-generated definition must never be * re-processed into a duplicate. */ private processToolInputs; private initialiseParityOptions; /** Extra JSON body fields for OpenAI-compatible requests (see wrapFetchWithBodyExtras). */ private requestExtras; private attachHandoffs; private executeHandoff; private attachMemory; private ensureMemory; private recallMemory; private rememberTurn; private attachKnowledge; /** Load file/directory knowledge sources on first use (needs fs, so it is deferred). */ private ensureKnowledgeLoaded; private retrieveKnowledge; private attachGuardrails; private applyOutputGuardrails; private attachRules; private applyRules; private attachHooks; /** Run `event` hooks; null means a hook blocked the operation. */ private runHook; private attachContext; /** * Apply the subscription credentials behind `auth` to the transport * (Python injects them into the LLM client). Resolved once and cached: the * provider may read a keychain or refresh a token, and doing that per turn * would be both slow and rude. */ private ensureAuthCredentials; /** * Attach the tools behind `toolsets` (Python `agent.py` lines 2358-2392). * Idempotent, and lazy so the provider SDKs load only for an agent that * actually asked for them. */ private ensureToolsetTools; /** Resolve `web` into a search tool once (loads a provider module, so it is deferred). */ private ensureWebTool; /** Resolve `skills` into a prompt block once (needs fs, so it is deferred). */ private ensureSkillsPrompt; private applyPlanning; /** The ContextManager attached via `context`, if any. */ getContextManager(): ContextManager | undefined; /** The HooksManager attached via `hooks`, if any. */ getHooks(): HooksManager | undefined; /** The memory store attached via `memory`, if any (a file store is created on first turn). */ getMemory(): AgentMemoryStore | undefined; /** The knowledge base attached via `knowledge`, if any. */ getKnowledge(): KnowledgeBase | undefined; /** The guardrails attached via `guardrails`. */ getGuardrails(): readonly Guardrail[]; /** * The `taskName`/`taskDescription`/`taskId` of the most recent turn, or * `undefined` when the caller named none (Python threads the same triple * into `display_interaction` and the interaction callbacks). */ getTaskContext(): TaskContext | undefined; /** * The continuous-learning store behind `learn`, or `undefined` when the * option was not set. Read it to inspect or approve what was learned. */ getLearnManager(): LearnManager | undefined; /** * Build the learn manager on first use. * * The store imports fs/os/path at its top level, so importing it eagerly * would put Node builtins on the Agent's graph and fail the webview gate. * The specifier is computed so the bundler leaves it as a runtime import; * nothing loads unless an agent actually asked for `learn`. */ private ensureLearnManager; /** * The managed runtime this agent's turns are handed to, resolved from * `backend` or `runOn`. `undefined` means the loop runs here. */ getManagedBackend(): ManagedBackendLike | undefined; /** Where this agent's tool calls run, resolved from `toolsRunOn`. */ getToolPlace(): ToolPlaceLike | undefined; /** * Put this agent's tools somewhere, sharing ONE place with other agents. * * A team-wide `toolsRunOn` means one sandbox for the whole team, not one per * member -- separate instances would multiply the cost and lose any state * tools leave for each other. An agent that declared its OWN toolsRunOn keeps * it: an explicit choice on the member is more specific than the team's * default, and silently overriding it would be the surprising direction. */ adoptToolPlace(place: ToolPlaceLike): boolean; /** * Take a team's autonomy settings, unless this agent declared its own. * * Python's AgentTeam propagates autonomy to members that have none of their * own; this is that. A member's explicit setting wins, because an autonomy * level is a permission boundary -- silently widening one an agent declared * for itself is the direction that causes harm. */ adoptAutonomy(config: AutonomyConfig): boolean; /** * Queue live guidance for the next turn (Python `Agent.steer`). Returns the * message id, or `''` when steering is off or the queue is full. */ steer(message: string, priority?: number): string; /** Whether a sandbox is configured (Python `Agent.has_sandbox`). */ get hasSandbox(): boolean; /** The resolved `sandbox` settings, or `undefined` when the option was not set. */ getSandboxConfig(): AgentSandboxConfig | undefined; /** * Run code in the agent's sandbox (Python `Agent.execute_code`). * * The code is analysed before it runs and the warnings are attached to the * result under `metadata.securityWarnings`, so a caller can act on them * rather than having them logged and lost. * * @param code - The source to run. * @param options.language - `python` (default), `bash`, `javascript`, ... * @param options.checkSecurity - Run the static pre-check (default true). * @param options.runIn - Where to run THIS call: a sandbox type, a config, * or `true` for the default subprocess sandbox. Overrides the agent's. */ executeCode(code: string, options?: ExecuteCodeOptions): Promise; /** The steering queue behind `messageSteering`, or `undefined` when off. */ getMessageSteering(): MessageSteeringProtocol | undefined; /** The runtime each turn is delegated to, resolved from `runtime`. */ getRuntime(): ResolvedAgentRuntime | undefined; /** The resolved `autonomy` settings, or `undefined` when the option was not set. */ getAutonomy(): AutonomyConfig | undefined; /** The rules manager attached via `rules`, if any. */ getRules(): RulesManager | undefined; /** * Extract declared parameter names from a plain function. * Returns [] when parameters can't be parsed reliably (e.g. destructuring), * in which case callers fall back to passing the raw args object. */ private extractParamNames; /** * Register a plain (positional-argument) function as a tool. * The model returns named args ({city: "Paris"}); plain functions like * (city) => ... need them mapped back to positional order — previously the * whole object landed in the first parameter ("Weather in [object Object]"). */ private registerPlainFunction; /** Build the OpenAI response_format payload when outputSchema is set. */ private getResponseFormat; /** * Flatten OpenAI-shape tool definitions ({ type: 'function', function: {...} }) * into the provider-agnostic ToolDefinition shape the AI SDK backend expects. * Tools already in the flat shape pass through unchanged. This mirrors what * litellm does for the Python SDK: format once, translate at the transport — * so tools are never dropped by provider. */ private getFlatToolDefinitions; /** * Generate a unique session ID based on current hour, agent name, and random suffix */ private generateSessionId; /** * Initialize DB session - restore history on first chat (lazy) */ private initDbSession; /** * The cache key for one turn. `previousResult` is part of it because it is * substituted for `{{previous}}` in the prompt before the model sees it, so * the same raw prompt with a different chained context is a DIFFERENT model * input and must not share a cache entry. Omitting it let `execute(task, * contextA)` return the response computed for `execute(task, contextB)`. */ private cacheKeyFor; /** * Get cached response if available and not expired */ private getCachedResponse; /** * Cache a response */ private cacheResponse; /** * The system messages for one turn: exactly one, or none at all when * `templates.useSystemPrompt` is false (Python `use_system_prompt=False` * sends no system message rather than an empty one). */ private systemMessages; private createSystemPrompt; /** * Register a tool function that can be called by the model * @param name Function name * @param fn Function implementation */ registerToolFunction(name: string, fn: Function): void; /** * Check if a tool definition exists for the given function name * @param name Function name * @returns True if a tool definition exists */ private hasToolDefinition; /** * Auto-generate a tool definition based on the function * @param name Function name * @param func Function implementation */ private addAutoGeneratedToolDefinition; /** * Run one registered tool implementation. * * The single place a tool actually executes, so the options that govern * execution have one seam rather than several: `toolsRunOn` decides WHERE * it runs (Python `tools_placement.ensure_tools_placed`). */ private invokeTool; /** * `toolConfig.allowGlobalTools`: resolve a tool the model named but the * agent does not carry from the process-global tool registry, registering * it for the rest of the run. Returns whether one was found. */ private resolveGlobalTool; /** * Process tool calls from the model * @param toolCalls Tool calls from the model * @param signal Optional AbortSignal; if already aborted, no tool is invoked * @returns Array of tool results */ private processToolCalls; /** * Run one turn and return the response. * * @param prompt - The task to run. Optional (Python parity: `start(prompt=None)`): * when omitted, the agent's own `instructions` become the task, so * `new Agent({ instructions: 'Summarise AI news' }).start()` works with no * argument. Falls back to `'Hello'` only if there are no instructions * either. * @param previousResult - Prior agent output to chain into this turn. * @param onToken - Token sink; defaults to stdout. * @param signal - Cancels the run. * @param onEvent - Structured events, for callers that need to SEE tool * activity rather than infer it from prose. Optional and additive: every * existing caller passes four arguments and gets exactly the behaviour it * had before. * @param options - Per-call options (see {@link AgentChatOptions}). AgentTeam * uses this to carry a Task's `tools` and `outputJson` into the run. */ start(prompt?: string, previousResult?: string, onToken?: (token: string) => void, signal?: AbortSignal, onEvent?: (event: AgentEvent) => void, options?: AgentChatOptions): Promise; /** * The task for a `start()` call that named no prompt: the agent's own * instructions, else `'Hello'`. An explicit prompt always wins -- including * an explicit empty string, which is a caller's choice, not an omission. */ private resolveStartPrompt; /** * One complete turn: resolve per-call options and retrieval (prepareTurn), * run the model with retry (runTurnOnce), then apply rules, guardrails, * hooks, context and memory (finishTurn). Every public entry point -- * start(), chat(), stream(), streamEvents() -- goes through here. */ private runTurn; /** {@link Agent.runTurn} without the `getResult()` bookkeeping. */ private runTurnUnrecorded; /** * One non-streaming completion, used by the features that need to ask the * model something outside the main turn (reflection's critique, the * self-improvement review). * * `model` overrides the agent's own for this call (Python's `reflect_llm` / * per-feature `llm`), routed the same way the constructor routes the agent's * model so a `claude-*` critique model does not get sent to OpenAI. */ private completeOnce; /** * Python parity: the reflection loop in `agent/chat_mixin.py`. The model is * asked to critique its own answer and to say whether it is satisfactory; * an unsatisfactory answer is regenerated from the critique, up to * `maxIterations` rounds, and a "yes" only counts once `minIterations` * reflections have run. */ private applyReflection; /** * Hand the turn to the managed runtime named by `backend`/`runOn` * (Python `execution_mixin.py::_delegate_to_backend`). Every per-call * option the caller passed -- `config` included -- is forwarded verbatim, * because the runtime, not this process, decides what to do with them. */ private delegateTurnToBackend; /** * Hand the turn to the runtime named by `runtime` (Python * `_chat_via_runtime`). The runtime runs the whole loop -- model calls and * tools -- so the local turn machinery is skipped, exactly as for a managed * backend. */ private delegateTurnToRuntime; private withRetry; private prepareTurn; /** * Python `_maybe_emit_nudge`: every `nudgeInterval` turns, and only once the * agent has actually done some work (`nudgeMinToolIters` tool calls), remind * it to persist anything reusable it discovered. */ private maybeEmitNudge; /** * Python `_process_auto_learning`: after the answer, `agentic` mode extracts * and stores learnings from the turn, `propose` mode extracts them into the * pending queue for a human to approve. Failures are swallowed -- a learning * pass must never break the turn that produced it. */ private captureLearnings; private finishTurn; /** * Python parity: `agent/skill_review.py` `SkillReviewMixin`. After a task * finishes, an opt-in guarded review turn runs an isolated model call * restricted to the single `skill_manage` tool and asks whether the session * revealed a reusable technique worth persisting. * * The guarantees are Python's and each is deliberate: off by default; never * run with the agent's full toolset; a review cannot trigger another * review; and any failure is swallowed, because a bookkeeping pass must * never break the task that produced it. */ private runSkillReview; /** * One isolated model call offering exactly one tool, and nothing else. * Used by the skill review, whose whole guarantee is that it never runs * with the agent's own toolset. */ private askWithSingleTool; private runTurnOnce; /** * Stream the agent's response token-by-token as an async iterable of plain * strings — mirrors Python's `Agent.iter_stream()`, which yields bare `str`. * This lets any host (browser, webview, React Native, server) render an * answer as it arrives, instead of only receiving the final string. * * Backpressure is free (the loop pulls) and cancellation is a single path: * breaking out of the `for await` runs the iterator's `return()`, which * detaches the token sink so no further tokens are queued. * * When the underlying execution path does not stream (e.g. `stream: false`, * tools, or a structured `outputSchema`), no text deltas are produced; in * that case the full response from the terminal `finish` event is yielded as * a single token so callers always receive the answer. * * @param prompt - The user prompt to send to the agent. * @param opts - Optional {@link AgentStreamOptions} (e.g. `previousResult`). * @returns An async iterable of plain text tokens. * @example * ```typescript * for await (const token of agent.stream("Tell me a story")) { * process.stdout.write(token); * } * ``` */ stream(prompt: string, opts?: AgentStreamOptions): AsyncIterable; /** * Stream structured {@link AgentEvent}s (text deltas, finish, error) — the * TypeScript analogue of Python's `stream_emitter` channel. Prefer * {@link Agent.stream} when you only need the text tokens. * * @param prompt - The user prompt to send to the agent. * @param opts - Optional {@link AgentStreamOptions} (e.g. `previousResult`). * @returns An async iterable of {@link AgentEvent}s: zero or more `text` * deltas followed by a single terminal `finish` (or `error`) event. * @example * ```typescript * for await (const event of agent.streamEvents("Hi")) { * if (event.type === 'text') process.stdout.write(event.delta); * else if (event.type === 'finish') console.log('\n', event.text); * } * ``` */ streamEvents(prompt: string, opts?: AgentStreamOptions): AsyncIterable; /** * Send one message and return the reply, keeping conversation history. * * Rejects if the turn fails. Python's `Agent.chat` instead reports the error * and returns `None`; pass `{ errorsAsNull: true }` in `options` for that * contract, which changes the return type to `string | null` and nothing * else. See {@link AgentChatCallOptions.errorsAsNull} for what stays fatal. * * @param prompt - The user message. * @param previousResult - Substituted for `{{previous}}` in the prompt. * @param signal - Turn-scoped abort signal (Python parity: cancel_token). * @param options - Per-call options mirroring Python's `Agent.chat` keyword * arguments (temperature, tools, outputJson, stream, toolChoice, seed, ...), * plus the chat-only `errorsAsNull`. */ chat(prompt: string, previousResult?: string, signal?: AbortSignal, options?: AgentChatOptions): Promise; chat(prompt: string, previousResult: string | undefined, signal: AbortSignal | undefined, options: AgentChatCallOptions & { errorsAsNull: false; }): Promise; chat(prompt: string, previousResult: string | undefined, signal: AbortSignal | undefined, options: AgentChatCallOptions & { errorsAsNull: true; }): Promise; /** {@link Agent.chat}'s body: always rejects on failure. */ private chatOrThrow; /** * Run a task on this agent. * * Python parity: `praisonaiagents/agent/execution_mixin.py` (`Agent.execute`) * takes a TASK -- `task.description` if the argument has one, else * `str(task)` -- and runs it through `chat()`. This method does the same, so * a port of `agent.execute(task)` behaves the way the Python it came from * behaves. * * The forms, precisely: * * - `execute()` -- no task named: runs the agent's own `instructions`, the * same fallback {@link Agent.start} uses for `start()`. Unchanged. * - `execute(task)` where `task` is a string: runs that string as the task. * - `execute(task)` where `task` is task-like (anything with a string * `description`, e.g. a {@link Task}): runs `task.description`. * - `execute(task)` with any other value: runs `String(task)`, matching * Python's `str(task)` fallback. * - `context` (second argument) is prior output to chain in: it is * substituted for the `{{previous}}` placeholder in the resolved prompt, * exactly as {@link Agent.chat}'s `previousResult` is. An array is joined * with blank lines. Python accepts `context` on `execute()` and ignores * it; honouring it here is additive, and no Python program can tell. * * BREAKING (v2): before this, the single argument was the previous result * and the agent always ran its own `instructions`, so `execute(taskText)` * discarded `taskText` unless the instructions contained `{{previous}}`. * That chaining call is now written `execute(undefined, previousResult)`, * which reproduces the old behaviour exactly. * * @param task - The task to run, or omitted to run the agent's instructions. * @param context - Prior output, substituted for `{{previous}}`. * @returns The agent's response. Rejects on failure (see {@link Agent.chat} * for the `errorsAsNull` opt-in to Python's return-null contract). */ execute(task?: AgentExecuteTask | null, context?: string | string[] | null): Promise; /** * Persist a message to the database */ private persistMessage; /** * Get the session ID for this agent */ getSessionId(): string; /** * Get the run ID for this agent */ getRunId(): string; /** * The text this agent produced on its most recent completed turn. * * `null` until the agent has run. A turn that throws (or is cancelled) * leaves the previous value in place -- the field records the last result * there WAS, not the last attempt. Streaming runs are included: the value is * the full assembled response, recorded when the run completes. * * There is no Python counterpart -- Python callers keep the return value of * `chat()`/`start()`. This exists for hosts that hand an `Agent` to one * component and read its output from another; before this it was hard-coded * to `null` and so could never do that. * * @returns The last response text, or `null` if the agent has not produced one. */ getResult(): string | null; getInstructions(): string; /** * Get the full conversation history, including tool context. * * The returned messages carry `tool_calls` and `tool_call_id`, so persisting * this output is a lossless way to save a chat — a tool-calling conversation * survives the round-trip through {@link Agent.setHistory}. The array and its * messages are copied on read: mutating the result does not change the * agent's state. * * @returns A copy of the conversation history. */ getHistory(): AgentMessage[]; /** * Restore a previously saved conversation so the model regains its memory of * it. Without this, reopening a saved chat renders the transcript on screen * while the model behaves as though the conversation never happened. * * Input is validated because it comes from disk, and disk contents outlive * the code that wrote them. A malformed history accepted here would fail on * the *next* model call, far from the code that loaded it, so it is refused * loudly and immediately: * * - a non-array input, or a message that is not an object, is rejected * - an unknown `role` is rejected * - a `tool` message whose `tool_call_id` matches no preceding `tool_calls` * entry is rejected (an orphaned tool result is a 400 from every provider) * * `system` messages: a leading `system` message is accepted and stripped. * `start()` prepends the agent's own instructions as the system prompt on * every run, so keeping a restored one would double it. Any non-leading * `system` message is rejected as malformed. * * The input is copied on write, mirroring {@link Agent.getHistory}'s copy on * read: mutating the array you pass in does not change the agent's state. * * @param messages The conversation to restore, e.g. from `getHistory()`. * @throws {Error} If the history is malformed (see rules above). */ setHistory(messages: readonly AgentMessage[]): void; /** * Deep-copy a single message so neither getHistory() nor setHistory() shares * the caller's mutable references (tool_calls is an array of objects). */ private copyMessage; /** * Clear conversation history (in memory and optionally in DB) */ clearHistory(clearDb?: boolean): Promise; /** * Clear response cache */ clearCache(): void; /** * Get the resolved backend (AI SDK preferred, native fallback) * Lazy initialization - backend is only resolved on first use */ getBackend(): Promise; /** * Get the backend source (ai-sdk, native, custom, or legacy) */ getBackendSource(): 'ai-sdk' | 'native' | 'custom' | 'legacy'; /** * Embed text using AI SDK (preferred) or native provider * * @param text - Text to embed (string or array of strings) * @param options - Embedding options * @returns Embedding vector(s) * * @example Single text * ```typescript * const embedding = await agent.embed("Hello world"); * ``` * * @example Multiple texts * ```typescript * const embeddings = await agent.embed(["Hello", "World"]); * ``` */ embed(text: string | string[], options?: { model?: string; }): Promise; /** * Get the model string for this agent */ getModel(): string; } export type { AgentTeamProcess, AgentTeamConfig, AgentTeamStartOptions, AgentTeamStartDictOptions, AgentTeamStartOptionsInput, PraisonAIAgentsConfig, AgentsConfig, } from './team';