> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentium.in/llms.txt
> Use this file to discover all available pages before exploring further.

# Agents and execution

> Public agents and execution signatures and configuration in @agentium/core 4.0.0.

Import these **52 exports** from `@agentium/core`. Read the [agents and execution guide](/agents/overview) for setup and behavior, or return to the [package reference](/api-reference/core).

A `?` marks an optional field. These are declarations for lookup; run the examples in the linked guide. Follow related-type links for Agentium types and source links for imported dependency types.

## Agent

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/agent.ts)

```typescript theme={null}
export declare class Agent {
    readonly kind: "agent";
    readonly name: string;
    readonly eventBus: EventBus;
    readonly instructions?: string | ((ctx: RunContext) => string);
    get tools(): ToolDef[];
    /** Replace the agent's tool set at runtime (e.g. after MCP servers connect/disconnect). */
    setTools(tools: ToolDef[]): void;
    /** Add a single tool at runtime. */
    addTool(tool: ToolDef): void;
    /** Remove a tool by name at runtime. Returns true if the tool was found and removed. */
    removeTool(name: string): boolean;
    /** List the names of all currently registered tools. */
    listTools(): string[];
    get model(): ModelProvider;
    /** Alias for `eventBus`. */
    get events(): EventBus;
    get modelId(): string;
    get providerId(): string;
    get hasStructuredOutput(): boolean;
    get approvalManager(): ApprovalManager | null;
    get structuredOutputSchema(): AgentiumSchema | undefined;
    /** Access the MemoryManager (if memory is configured). */
    get memory(): MemoryManager | null;
    /** Access the CheckpointManager (if checkpointing is configured). */
    get checkpointManager(): CheckpointManager | null;
    constructor(config: AgentConfig);
    toJSON(): SerializedAgent;
    static fromJSON(data: SerializedAgent, registry: DeserializeRegistry): Agent;
    close(options?: {
        closeStorage?: boolean;
    }): Promise<void>;
    run(input: MessageContent, opts?: RunOpts): Promise<RunOutput>;
    stream(input: MessageContent, opts?: RunOpts): AsyncGenerator<StreamChunk>;
    /** Run a child agent with a fresh message list. Returns the child's final text. */
    spawnSubagent(task: string, spec?: SubagentSpec, runOpts?: RunOpts): Promise<string>;
    /** Internal child recipe: fresh state and borrowed host policy/services; no copied parent tools or stores. */
    getSubagentConfig(spec?: SubagentSpec): AgentConfig;
}
```

Related: [`AgentConfig`](/api-reference/core/agent#agentconfig), [`AgentiumSchema`](/api-reference/core/tools#agentiumschema), [`ApprovalManager`](/api-reference/core/tools#approvalmanager), [`CheckpointManager`](/api-reference/core/checkpoint#checkpointmanager), [`DeserializeRegistry`](/api-reference/core/agent#deserializeregistry), [`EventBus`](/api-reference/core/events#eventbus), [`MemoryManager`](/api-reference/core/memory#memorymanager), [`MessageContent`](/api-reference/core/models#messagecontent), [`ModelProvider`](/api-reference/core/models#modelprovider), [`RunContext`](/api-reference/core/agent#runcontext), [`RunOpts`](/api-reference/core/agent#runopts), [`RunOutput`](/api-reference/core/agent#runoutput).

## AgentConfig

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/types.ts)

```typescript theme={null}
export interface AgentConfig {
    name: string;
    model: ModelProvider;
    tools?: ToolDef[];
    instructions?: string | ((ctx: RunContext) => string);
    /** Auto-register this agent in the global registry. Default: true. Set false to opt out. */
    register?: boolean;
    /**
     * Unified memory config — sessions, summaries, user facts, user profile,
     * entities, decisions, and learnings. Pass an object with a `storage` field
     * to enable persistent memory. All subsystems share this single storage.
     * `fileMemory` and `filesystem` reuse this storage when they do not set their own.
     */
    memory?: UnifiedMemoryConfig;
    /**
     * Host workspace with an explicit access mode.
     * Use `{ path, mode: "read" }` for read-only tools. Canonical paths are confined
     * to this folder; OS isolation is still needed against concurrent path replacement.
     */
    workspace?: false | {
        path: string;
        mode: "read" | "write";
    };
    /**
     * Folders to scan for Agent Skills (`SKILL.md`). The prompt only sees a short
     * name + description until the agent calls `get_skill_instructions`.
     */
    skillDirs?: string[] | false;
    /**
     * Load project instruction files (`AGENTS.md`, `CLAUDE.md`, `.agentium.md`,
     * `.cursorrules`) and add them to the system prompt. Default: false.
     */
    contextFiles?: boolean | LoadContextFilesOptions;
    /**
     * Durable notes the agent writes for its future self (not the host disk).
     * Tools: `agent_fs_write`, `agent_fs_read`, `agent_fs_list`, `agent_fs_search`.
     */
    filesystem?: boolean | AgentFileSystemConfig;
    /**
     * Isolated child agents via the `task` tool. The child gets a fresh chat and
     * returns one final report. Default: false.
     */
    subagents?: boolean | {
        maxDepth?: number;
    };
    /**
     * Tiny standing memory files (MEMORY.md / USER.md) with a hard character cap.
     * Default: false.
     */
    fileMemory?: boolean | FileMemoryConfig;
    /**
     * Vector-backed learnings. Requires a real vector store — pass
     * `{ vectorStore }` here or set `memory.learnings`.
     */
    learning?: LearningsConfig;
    /**
     * Give the agent a `search_past_sessions` tool to look up older chats by keyword.
     */
    searchPastSessions?: boolean;
    /**
     * Use the process-wide `EventBus.shared` so one tracer can see every agent.
     */
    sharedEventBus?: boolean;
    /** Alias for `eventBus`. */
    events?: EventBus;
    sessionId?: string;
    userId?: string;
    maxToolRoundtrips?: number;
    temperature?: number;
    /** Maximum output tokens per LLM call. */
    maxTokens?: number;
    structuredOutput?: AgentiumSchema;
    hooks?: AgentHooks;
    guardrails?: {
        input?: InputGuardrail[];
        output?: OutputGuardrail[];
    };
    /**
     * Custom event bus. Default: a private bus for this agent.
     * Pass `EventBus.shared` (or `sharedEventBus: true`) so one tracer sees everything.
     */
    eventBus?: EventBus;
    /** Logging level. Set to "debug" for tool call details, "info" for summaries, "silent" to disable. Default: "silent". */
    logLevel?: LogLevel;
    /** Enable extended thinking / reasoning for the model. */
    reasoning?: ReasoningConfig;
    /** Cache, compaction, and Gemini grounding options for this agent. */
    providerOptions?: ProviderOptions;
    /** Retry configuration for transient LLM API failures (429, 5xx, network errors). */
    retry?: Partial<RetryConfig>;
    /** Default sandbox config applied to ALL tools unless the tool explicitly sets sandbox: false. Off by default. */
    sandbox?: boolean | SandboxConfig;
    /** Human-in-the-loop approval configuration for tool calls. */
    approval?: ApprovalConfig;
    /** Borrow a host dispatcher (for example across child agents); Agent.close will not close it. */
    approvalManager?: ApprovalManager;
    /** Mandatory host policy; per-tool approval exemptions cannot override it. */
    executionPolicy?: ExecutionPolicy;
    /**
     * Skills — pre-packaged or learned tool bundles.
     * Accepts loaded Skill objects or source strings (paths, npm packages, URLs).
     */
    skills?: Array<Skill | string>;
    /** Agent handoff — transfer conversations to specialist agents. */
    handoff?: HandoffConfig;
    /** Cost tracker — track token usage and enforce budgets. */
    costTracker?: CostTracker;
    /** Semantic cache — cache LLM responses by semantic similarity. */
    semanticCache?: SemanticCacheConfig;
    /** Webhooks — push events to external destinations (HTTP, Slack, Email). */
    webhooks?: WebhookConfig;
    /**
     * Tool router — use a cheap model to pre-select relevant tools per query.
     * Dramatically reduces prompt tokens when the agent has many tools (e.g. 50+ MCP tools).
     */
    toolRouter?: ToolRouterConfig;
    /**
     * Limit large tool results to prevent prompt token explosion.
     * When a tool returns more than `maxChars`, the result is either smart-truncated
     * (JSON arrays are sliced, objects trimmed) or summarized via a cheap model.
     *
     * Default: off (no limit). Recommended: `{ maxChars: 20000 }` for MCP-heavy agents.
     */
    toolResultLimit?: ToolResultLimitConfig;
    /** Per-roundtrip hooks for fine-grained LLM loop control (cost auto-stop, checkpointing, context compaction). */
    loopHooks?: LoopHooks;
    /** Dynamic tool resolver — called at the start of each run to provide context-dependent tools. */
    toolResolver?: (ctx: RunContext) => Promise<ToolDef[]>;
    /** Token-aware context compaction to prevent context window overflow. */
    contextCompactor?: ContextCompactorConfig;
    /** Save a transcript/state snapshot after each tool roundtrip. Snapshot rollback does not undo effects or resume execution. */
    checkpointing?: boolean | {
        storage: StorageDriver;
    };
    /** Context compression — auto-compress verbose tool results. Set `true` for defaults or provide a CompressionManager. */
    compressToolResults?: boolean;
    compressionManager?: CompressionManager;
    /** Runtime dependency injection — inject variables into instructions/messages via {key} templates. */
    dependencies?: Record<string, unknown | (() => unknown) | (() => Promise<unknown>)>;
    /** Agent reflection and self-correction. */
    reflection?: ReflectionConfig;
    /**
     * Memory Pointer Pattern: auto-inject `storeArtifact` / `getArtifact` / `listArtifacts`
     * tools and automatically convert large tool outputs into pointers.
     * Off by default.
     */
    artifacts?: ArtifactsConfig;
}
```

Related: [`AgentFileSystemConfig`](/api-reference/core/fs#agentfilesystemconfig), [`AgentHooks`](/api-reference/core/agent#agenthooks), [`AgentiumSchema`](/api-reference/core/tools#agentiumschema), [`ApprovalConfig`](/api-reference/core/tools#approvalconfig), [`ApprovalManager`](/api-reference/core/tools#approvalmanager), [`CompressionManager`](/api-reference/core/compression#compressionmanager), [`ContextCompactorConfig`](/api-reference/core/agent#contextcompactorconfig), [`CostTracker`](/api-reference/core/cost#costtracker), [`EventBus`](/api-reference/core/events#eventbus), [`ExecutionPolicy`](/api-reference/core/tools#executionpolicy), [`FileMemoryConfig`](/api-reference/core/memory#filememoryconfig), [`HandoffConfig`](/api-reference/core/handoff#handoffconfig).

## AgentFactory

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/factory.ts)

````typescript theme={null}
/**
 * Factory for creating per-request `Agent` instances scoped to a tenant / user.
 *
 * @example
 * ```ts
 * const factory = new AgentFactory({
 *   name: "assistant",
 *   model: openai("gpt-4o"),
 *   memory: { storage: new SqliteStorage("data.db") },
 * });
 *
 * app.post("/chat", (req, res) => {
 *   const agent = factory.create({ tenantId: req.user.tenant, userId: req.user.id });
 *   return agent.run(req.body.input);
 * });
 * ```
 */
export declare class AgentFactory {
    constructor(base: AgentConfig);
    create(scope?: FactoryContext): Agent;
}
````

Related: [`Agent`](/api-reference/core/agent#agent), [`AgentConfig`](/api-reference/core/agent#agentconfig), [`FactoryContext`](/api-reference/core/agent#factorycontext).

## AgentHooks

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/types.ts)

```typescript theme={null}
export interface AgentHooks {
    beforeRun?: (ctx: RunContext) => Promise<void>;
    afterRun?: (ctx: RunContext, output: RunOutput) => Promise<void>;
    onToolCall?: (ctx: RunContext, toolName: string, args: unknown) => Promise<void>;
    onError?: (ctx: RunContext, error: Error) => Promise<void>;
}
```

Related: [`RunContext`](/api-reference/core/agent#runcontext), [`RunOutput`](/api-reference/core/agent#runoutput).

## buildAgentConfigFromSerialized

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/serialization.ts)

```typescript theme={null}
export declare function buildAgentConfigFromSerialized(data: SerializedAgent, registry: DeserializeRegistry): {
    name: string;
    model: ModelProvider;
    instructions: string | undefined;
    tools: ToolDef[] | undefined;
    temperature: number | undefined;
    maxTokens: number | undefined;
    maxToolRoundtrips: number | undefined;
    sessionId: string | undefined;
    userId: string | undefined;
    logLevel: any;
    reasoning: {
        enabled: boolean;
        effort?: "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
        budgetTokens?: number;
        summary?: "auto" | "concise" | "detailed";
        mode?: "standard" | "pro";
        context?: "auto" | "current_turn" | "all_turns";
    } | undefined;
    providerOptions: ProviderOptions | undefined;
    register: boolean;
};
```

Related: [`DeserializeRegistry`](/api-reference/core/agent#deserializeregistry), [`ModelProvider`](/api-reference/core/models#modelprovider), [`SerializedAgent`](/api-reference/core/agent#serializedagent), [`ToolDef`](/api-reference/core/tools#tooldef).

## ComputerAction

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/computer-use-agent.ts)

```typescript theme={null}
/**
 * Wrapper around Anthropic's Computer Use API (`computer_20251124`).
 *
 * Implements the agent loop where Claude returns desktop actions (mouse/keyboard
 * /screenshot/zoom), the caller-supplied `executor` performs them, and the
 * loop continues until the model returns a final non-tool message.
 *
 * The executor is pluggable so the same Agent can run against:
 *   - local OS desktops (via `xdotool` + screenshot)
 *   - remote VNC sessions
 *   - sandboxed Linux containers (e.g. an `E2BSandbox` from Phase 4.1)
 *
 * Spec: https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/computer-use-tool
 */
export type ComputerAction = {
    action: "screenshot";
} | {
    action: "mouse_move";
    coordinate: [
        number,
        number
    ];
} | {
    action: "left_click";
    coordinate?: [
        number,
        number
    ];
} | {
    action: "right_click";
    coordinate?: [
        number,
        number
    ];
} | {
    action: "double_click";
    coordinate?: [
        number,
        number
    ];
} | {
    action: "left_click_drag";
    coordinate: [
        number,
        number
    ];
} | {
    action: "type";
    text: string;
} | {
    action: "key";
    text: string;
} | {
    action: "scroll";
    coordinate: [
        number,
        number
    ];
    scroll_direction: "up" | "down" | "left" | "right";
    scroll_amount: number;
} | {
    action: "zoom";
    region: [
        number,
        number,
        number,
        number
    ];
};
```

## ComputerActionResult

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/computer-use-agent.ts)

```typescript theme={null}
export interface ComputerActionResult {
    /** Optional human-readable output (e.g. an error message). */
    output?: string;
    /** Base64-encoded PNG of the screen after the action. */
    screenshotBase64?: string;
}
```

## ComputerExecutor

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/computer-use-agent.ts)

```typescript theme={null}
export interface ComputerExecutor {
    /** Display width in pixels. */
    readonly displayWidth: number;
    /** Display height in pixels. */
    readonly displayHeight: number;
    /** X11 display number, if applicable. Optional. */
    readonly displayNumber?: number;
    /** Execute a single action and return the result. */
    execute(action: ComputerAction): Promise<ComputerActionResult>;
}
```

Related: [`ComputerAction`](/api-reference/core/agent#computeraction), [`ComputerActionResult`](/api-reference/core/agent#computeractionresult).

## ComputerUseAgent

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/computer-use-agent.ts)

```typescript theme={null}
export declare class ComputerUseAgent {
    readonly kind: "computer-use-agent";
    constructor(config: ComputerUseAgentConfig);
    /** Run the computer-use loop until the model returns a final assistant turn. */
    run(input: string): Promise<ComputerUseRunOutput>;
}
```

Related: [`ComputerUseAgentConfig`](/api-reference/core/agent#computeruseagentconfig), [`ComputerUseRunOutput`](/api-reference/core/agent#computeruserunoutput).

## ComputerUseAgentConfig

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/computer-use-agent.ts)

```typescript theme={null}
export interface ComputerUseAgentConfig {
    /** Anthropic API key. Falls back to `ANTHROPIC_API_KEY`. */
    apiKey?: string;
    /** Claude model id. Defaults to a known computer-use-compatible model. */
    model?: string;
    /** Maximum response tokens. Default 4096. */
    maxTokens?: number;
    /** Executor that performs OS-level actions and returns screenshots. */
    executor: ComputerExecutor;
    /** Maximum agent loop iterations (one LLM call per iteration). Default 50. */
    maxIterations?: number;
    /** System prompt prepended to the conversation. */
    systemPrompt?: string;
    /** Enable zoom action (only on `computer_20251124`). Default true. */
    enableZoom?: boolean;
}
```

Related: [`ComputerExecutor`](/api-reference/core/agent#computerexecutor).

## ComputerUseRunOutput

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/computer-use-agent.ts)

```typescript theme={null}
export interface ComputerUseRunOutput {
    /** Final assistant text. */
    text: string;
    /** All actions taken during the run. */
    actions: ComputerAction[];
    /** Number of LLM iterations consumed. */
    iterations: number;
}
```

Related: [`ComputerAction`](/api-reference/core/agent#computeraction).

## ContextCompactorConfig

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/types.ts)

```typescript theme={null}
export interface ContextCompactorConfig {
    maxContextTokens: number;
    reserveTokens?: number;
    strategy: "trim" | "summarize" | "hybrid";
    summarizeModel?: ModelProvider;
    priorityOrder?: ("system" | "recentHistory" | "memory" | "tools")[];
}
```

Related: [`ModelProvider`](/api-reference/core/models#modelprovider).

## createTaskTool

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/subagent.ts)

```typescript theme={null}
export declare function createTaskTool(parent: Agent, config?: {
    maxDepth?: number;
}): ToolDef;
```

Related: [`Agent`](/api-reference/core/agent#agent), [`ToolDef`](/api-reference/core/tools#tooldef).

## CritiqueResult

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/reflection.ts)

```typescript theme={null}
export interface CritiqueResult {
    pass: boolean;
    score: number;
    feedback: string;
    suggestedRevision?: string;
}
```

## defineExternalAgent

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/external-agent.ts)

````typescript theme={null}
/**
 * Wrap framework-external agent logic (LangGraph, Claude Agent SDK, plain
 * functions) into a `ServableAgent` so it gets Agentium's production surface:
 * registry, HTTP/Socket.IO gateways, queue workers, and observability —
 * without adopting the Agentium `Agent` class.
 *
 * @example
 * ```ts
 * const langGraphAgent = defineExternalAgent({
 *   name: "researcher",
 *   run: async (input) => {
 *     const result = await graph.invoke({ messages: [String(input)] });
 *     return result.messages.at(-1).content;
 *   },
 * });
 * // immediately servable: POST /agents/researcher/run
 * ```
 */
export declare function defineExternalAgent(config: ExternalAgentConfig): ServableAgent;
````

Related: [`ExternalAgentConfig`](/api-reference/core/agent#externalagentconfig), [`ServableAgent`](/api-reference/core/serve#servableagent).

## DeserializeRegistry

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/serialization.ts)

```typescript theme={null}
export interface DeserializeRegistry {
    models: Record<string, ModelProvider>;
    tools?: Record<string, ToolDef>;
    storage?: StorageDriver;
}
```

Related: [`ModelProvider`](/api-reference/core/models#modelprovider), [`StorageDriver`](/api-reference/core/storage#storagedriver), [`ToolDef`](/api-reference/core/tools#tooldef).

## DrainController

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/errors.ts)

```typescript theme={null}
/**
 * A coordinator the application can call to request a graceful drain of an
 * in-flight run. Pass into `agent.run(input, { signal, drain })` (or its
 * factory equivalent) and call `requestDrain()` from any thread/handler.
 */
export declare class DrainController {
    /** Returns true once `requestDrain()` has been invoked. */
    get drained(): boolean;
    /** Request a graceful stop. Idempotent. */
    requestDrain(): void;
    /** Resolves once drain is requested. */
    waitForDrain(): Promise<void>;
}
```

## estimateProgress

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/progress-protocol.ts)

```typescript theme={null}
export declare function estimateProgress(roundtrip: number, maxRoundtrips: number, phase: "llm" | "tools"): number;
```

## ExecutionServices

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/execution-services.ts)

```typescript theme={null}
/** Host-supplied execution boundary. Core consumes these operations; it does not
 * construct or own the host's orchestration, configuration, or resource lifecycle.
 */
export interface ExecutionServices {
    readonly ctx: RunContext;
    readonly signal: AbortSignal;
    readonly tools: readonly ToolDef[];
    readonly history: readonly ChatMessage[];
    readonly executionPolicy: ExecutionPolicy;
    readonly approvalManager?: ApprovalManager;
    readonly state: Record<string, unknown>;
    readonly sessionKey: string;
    model(provider: ModelProvider, messages: ChatMessage[], options?: ModelConfig & {
        tools?: ToolDefinition[];
    }, context?: RunContext): Promise<ModelResponse>;
    streamModel(provider: ModelProvider, messages: ChatMessage[], options?: ModelConfig & {
        tools?: ToolDefinition[];
    }, context?: RunContext): AsyncGenerator<StreamChunk>;
    runOwned<T>(operation: () => Promise<T>): Promise<T>;
    observeTool(result: ToolCallResult, context?: RunContext): Promise<void>;
    dispatchEffect<T>(name: string, args: Record<string, unknown>, execute: (args: Record<string, unknown>, ctx: RunContext) => Promise<T>): Promise<T>;
    dispatch(call: ToolCall): Promise<ToolCallResult>;
    recordConversation(executionId: string, messages: readonly ChatMessage[]): void;
}
```

Related: [`ApprovalManager`](/api-reference/core/tools#approvalmanager), [`ChatMessage`](/api-reference/core/models#chatmessage), [`ExecutionPolicy`](/api-reference/core/tools#executionpolicy), [`ModelConfig`](/api-reference/core/models#modelconfig), [`ModelProvider`](/api-reference/core/models#modelprovider), [`ModelResponse`](/api-reference/core/models#modelresponse), [`RunContext`](/api-reference/core/agent#runcontext), [`StreamChunk`](/api-reference/core/models#streamchunk), [`ToolCall`](/api-reference/core/models#toolcall), [`ToolCallResult`](/api-reference/core/tools#toolcallresult), [`ToolDef`](/api-reference/core/tools#tooldef), [`ToolDefinition`](/api-reference/core/models#tooldefinition).

## ExternalAgentConfig

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/external-agent.ts)

```typescript theme={null}
export interface ExternalAgentConfig {
    name: string;
    /**
     * The agent's run logic — wrap a LangGraph graph invocation, a Claude Agent
     * SDK call, or any custom code. Return a plain string or a partial
     * RunOutput; missing fields are filled with sensible defaults.
     */
    run: (input: MessageContent, opts?: RunOpts) => Promise<string | Partial<RunOutput>>;
    /**
     * Optional native streaming. When omitted, `stream()` falls back to
     * running `run()` and yielding the full text as a single chunk.
     */
    stream?: (input: MessageContent, opts?: RunOpts) => AsyncIterable<StreamChunk>;
    /** Shown in registry descriptions and swagger docs. */
    instructions?: string;
    modelId?: string;
    providerId?: string;
    /** Auto-register in the global registry (default: true). */
    register?: boolean;
    /** Bring your own event bus; a fresh one is created otherwise. */
    eventBus?: EventBus;
}
```

Related: [`EventBus`](/api-reference/core/events#eventbus), [`MessageContent`](/api-reference/core/models#messagecontent), [`RunOpts`](/api-reference/core/agent#runopts), [`RunOutput`](/api-reference/core/agent#runoutput), [`StreamChunk`](/api-reference/core/models#streamchunk).

## FactoryContext

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/factory.ts)

```typescript theme={null}
export type FactoryContext = StorageScope;
```

Related: [`StorageScope`](/api-reference/core/storage#storagescope).

## GuardrailResult

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/types.ts)

```typescript theme={null}
export type GuardrailResult = {
    pass: true;
} | {
    pass: false;
    reason: string;
};
```

## InputGuardrail

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/types.ts)

```typescript theme={null}
export interface InputGuardrail {
    name: string;
    validate: (input: MessageContent, ctx: RunContext) => Promise<GuardrailResult>;
}
```

Related: [`GuardrailResult`](/api-reference/core/agent#guardrailresult), [`MessageContent`](/api-reference/core/models#messagecontent), [`RunContext`](/api-reference/core/agent#runcontext).

## LLMLoop

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/llm-loop.ts)

```typescript theme={null}
export declare class LLMLoop {
    constructor(provider: ModelProvider, toolExecutor: ToolExecutor | null, options: {
        maxToolRoundtrips: number;
        temperature?: number;
        maxTokens?: number;
        structuredOutput?: AgentiumSchema;
        logger?: Logger;
        reasoning?: ReasoningConfig;
        providerOptions?: ProviderOptions;
        retry?: Partial<RetryConfig>;
        toolResultLimit?: ToolResultLimitConfig;
        loopHooks?: LoopHooks;
        checkpointManager?: CheckpointManager;
        controlledExecution?: boolean;
    });
    run(messages: ChatMessage[], ctx: RunContext, apiKey?: string, transcript?: ChatMessage[]): Promise<RunOutput>;
    stream(messages: ChatMessage[], ctx: RunContext, apiKey?: string, transcript?: ChatMessage[], collectedTools?: ToolCallResult[], outcome?: {
        status: "completed" | "stopped";
    }): AsyncGenerator<StreamChunk>;
}
```

Related: [`AgentiumSchema`](/api-reference/core/tools#agentiumschema), [`ChatMessage`](/api-reference/core/models#chatmessage), [`CheckpointManager`](/api-reference/core/checkpoint#checkpointmanager), [`Logger`](/api-reference/core/logger#logger), [`LoopHooks`](/api-reference/core/agent#loophooks), [`ModelProvider`](/api-reference/core/models#modelprovider), [`ReasoningConfig`](/api-reference/core/models#reasoningconfig), [`RetryConfig`](/api-reference/core/utils#retryconfig), [`RunContext`](/api-reference/core/agent#runcontext), [`RunOutput`](/api-reference/core/agent#runoutput), [`StreamChunk`](/api-reference/core/models#streamchunk), [`ToolCallResult`](/api-reference/core/tools#toolcallresult).

## LoopEscapeResult

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/reflection.ts)

```typescript theme={null}
export interface LoopEscapeResult {
    detected: boolean;
    repeatedTool: string;
    repeatCount: number;
    escapePrompt: string;
}
```

## LoopHooks

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/types.ts)

```typescript theme={null}
/** Per-roundtrip hooks injected into the LLM loop for fine-grained control. */
export interface LoopHooks {
    /** Called before each LLM API call. Return modified messages to override, or void to pass through. */
    beforeLLMCall?: (messages: ChatMessage[], roundtrip: number) => Promise<ChatMessage[] | void>;
    /** Called after each LLM API response. */
    afterLLMCall?: (response: {
        finishReason: string;
        usage: TokenUsage;
    }, roundtrip: number) => Promise<void>;
    /** Called before each individual tool execution. Return `{ skip: true, result }` to skip execution. */
    beforeToolExec?: (toolName: string, args: unknown) => Promise<{
        skip?: boolean;
        result?: string;
    } | void>;
    /** Called after each individual tool execution. Return a string to replace the result. */
    afterToolExec?: (toolName: string, result: string) => Promise<string | void>;
    /** Called after all tools in a roundtrip complete. Return `{ stop: true }` to break the loop early. */
    onRoundtripComplete?: (roundtrip: number, tokensSoFar: TokenUsage) => Promise<{
        stop?: boolean;
    } | void>;
}
```

Related: [`ChatMessage`](/api-reference/core/models#chatmessage), [`TokenUsage`](/api-reference/core/models#tokenusage).

## OutputGuardrail

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/types.ts)

```typescript theme={null}
export interface OutputGuardrail {
    name: string;
    validate: (output: RunOutput, ctx: RunContext) => Promise<GuardrailResult>;
}
```

Related: [`GuardrailResult`](/api-reference/core/agent#guardrailresult), [`RunContext`](/api-reference/core/agent#runcontext), [`RunOutput`](/api-reference/core/agent#runoutput).

## PlanCritiqueResult

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/reflection.ts)

```typescript theme={null}
export interface PlanCritiqueResult {
    approved: boolean;
    concerns: string[];
    suggestion?: string;
}
```

## ProgressEvent

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/progress-protocol.ts)

```typescript theme={null}
export type ProgressEvent = {
    type: "run.started";
    runId: string;
    agentName: string;
} | {
    type: "step.started";
    step: string;
    description?: string;
} | {
    type: "step.finished";
    step: string;
    durationMs: number;
} | {
    type: "thinking";
    content: string;
} | {
    type: "tool.executing";
    toolName: string;
    args?: unknown;
} | {
    type: "tool.completed";
    toolName: string;
    durationMs: number;
    preview?: string;
} | {
    type: "text.delta";
    text: string;
} | {
    type: "progress";
    percent: number;
    message?: string;
} | {
    type: "intermediate.result";
    content: string;
} | {
    type: "run.finished";
    runId: string;
    durationMs: number;
    tokenCount?: number;
} | {
    type: "run.error";
    runId: string;
    error: string;
} | {
    type: "run.cancelled";
    runId: string;
};
```

## ReflectionConfig

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/reflection.ts)

```typescript theme={null}
export interface ReflectionConfig {
    enabled: boolean;
    maxReflections?: number;
    critic?: ModelProvider;
    preExecutionReview?: boolean;
    loopEscapeDetection?: boolean;
    postMortemLearning?: boolean;
    customCriteria?: string;
}
```

Related: [`ModelProvider`](/api-reference/core/models#modelprovider).

## ReflectionManager

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/reflection.ts)

```typescript theme={null}
export declare class ReflectionManager {
    constructor(config: ReflectionConfig, defaultModel: ModelProvider);
    critiqueOutput(output: RunOutput, input: string, _messages: ChatMessage[]): Promise<CritiqueResult>;
    critiquePlan(toolCalls: ToolCall[], context: string): Promise<PlanCritiqueResult>;
    detectLoopEscape(toolCalls: ToolCall[]): LoopEscapeResult | null;
    generatePostMortem(runId: string, error: Error, toolHistory: ToolCall[]): Promise<{
        lesson: string;
        category: string;
    }>;
    resetHistory(): void;
}
```

Related: [`ChatMessage`](/api-reference/core/models#chatmessage), [`CritiqueResult`](/api-reference/core/agent#critiqueresult), [`LoopEscapeResult`](/api-reference/core/agent#loopescaperesult), [`ModelProvider`](/api-reference/core/models#modelprovider), [`PlanCritiqueResult`](/api-reference/core/agent#plancritiqueresult), [`ReflectionConfig`](/api-reference/core/agent#reflectionconfig), [`RunOutput`](/api-reference/core/agent#runoutput), [`ToolCall`](/api-reference/core/models#toolcall).

## RunCancelledError

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/errors.ts)

```typescript theme={null}
export declare class RunCancelledError extends Error {
    constructor(message?: string);
}
```

## RunContext

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/run-context.ts)

```typescript theme={null}
export declare class RunContext {
    readonly executionServices?: ExecutionServices;
    readonly ephemeral: boolean;
    readonly externalHistory?: readonly ChatMessage[];
    readonly runMode: RunMode;
    readonly executionPolicy?: ExecutionPolicy;
    readonly runId: string;
    readonly sessionId: string;
    readonly userId?: string;
    readonly tenantId?: string;
    readonly metadata: Record<string, unknown>;
    readonly eventBus: EventBus;
    sessionState: Record<string, unknown>;
    /** AbortSignal for cancelling the run mid-execution. */
    readonly signal?: AbortSignal;
    /** Resolved runtime dependencies available to tools and hooks. */
    readonly dependencies: Record<string, string>;
    /** Per-run Jev questions, when `agent.run(input, { questions })` is used. */
    readonly questions?: Record<string, unknown>;
    constructor(opts: {
        sessionId: string;
        userId?: string;
        tenantId?: string;
        metadata?: Record<string, unknown>;
        eventBus: EventBus;
        sessionState?: Record<string, unknown>;
        runId?: string;
        executionServices?: ExecutionServices;
        ephemeral?: boolean;
        externalHistory?: readonly ChatMessage[];
        runMode?: RunMode;
        executionPolicy?: ExecutionPolicy;
        signal?: AbortSignal;
        dependencies?: Record<string, string>;
        questions?: Record<string, unknown>;
    });
    getState<T>(key: string): T | undefined;
    setState(key: string, value: unknown): void;
}
```

Related: [`ChatMessage`](/api-reference/core/models#chatmessage), [`EventBus`](/api-reference/core/events#eventbus), [`ExecutionPolicy`](/api-reference/core/tools#executionpolicy), [`ExecutionServices`](/api-reference/core/agent#executionservices), [`RunMode`](/api-reference/core/tools#runmode).

## RunDrainedError

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/errors.ts)

```typescript theme={null}
/**
 * Thrown to signal a cooperative graceful drain: an in-flight run is asked to
 * stop after the current step and persist a resumable checkpoint. Callers can
 * resume the run later with the same `runId`.
 */
export declare class RunDrainedError extends Error {
    readonly runId: string;
    constructor(runId: string, message?: string);
}
```

## RunMetrics

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/types.ts)

```typescript theme={null}
export interface RunMetrics {
    inputTokens: number;
    outputTokens: number;
    totalTokens: number;
    reasoningTokens?: number;
    cachedTokens?: number;
    audioInputTokens?: number;
    audioOutputTokens?: number;
    /** Time from request start to first LLM response (ms). */
    timeToFirstTokenMs?: number;
    /** Total wall-clock duration (ms). */
    durationMs?: number;
}
```

## RunOpts

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/types.ts)

```typescript theme={null}
export interface RunOpts {
    /** Runtime-owned execution services; trusted hosts only. */
    executionServices?: ExecutionServices;
    /** Additional mandatory host policy for delegated runs; cannot relax Agent policy. */
    executionPolicy?: ExecutionPolicy;
    /** Canonical external history; used by execution-driver adapters. */
    history?: readonly ChatMessage[];
    /** Read supplied history without loading or persisting an Agent-owned session. */
    ephemeral?: boolean;
    /** Caller-assigned run identity for a lifecycle-owning driver. */
    runId?: string;
    /** Immutable execution mode for this run. Plan mode denies declared effects and reviews unknowns. */
    runMode?: RunMode;
    /** Continue this conversation. Same id = the agent remembers prior turns. */
    sessionId?: string;
    /** Who is talking. Used by memory, fileMemory (USER.md), and isolation. */
    userId?: string;
    /** Which customer/org this run belongs to (multi-tenant apps). */
    tenantId?: string;
    /** Extra facts your tools and instruction functions can read via `ctx.metadata`. */
    metadata?: Record<string, unknown>;
    /** Per-request API key override passed to the model provider. */
    apiKey?: string;
    /** AbortSignal to cancel the run mid-execution. */
    signal?: AbortSignal;
    /** Per-run dependency overrides (merged with agent-level dependencies). */
    dependencies?: Record<string, unknown | (() => unknown) | (() => Promise<unknown>)>;
    /**
     * Jev questions for this run (`choice` / `noul` / `score`).
     * Wins over `jev(model, { questions })`. Ignored by chat providers.
     */
    questions?: Record<string, unknown>;
}
```

Related: [`ChatMessage`](/api-reference/core/models#chatmessage), [`ExecutionPolicy`](/api-reference/core/tools#executionpolicy), [`ExecutionServices`](/api-reference/core/agent#executionservices), [`RunMode`](/api-reference/core/tools#runmode).

## RunOutput

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/types.ts)

```typescript theme={null}
export interface RunOutput {
    text: string;
    toolCalls: ToolCallResult[];
    usage: TokenUsage;
    /** Parsed structured output if structuredOutput schema is set. */
    structured?: unknown;
    /** Model's internal reasoning / thinking content (when reasoning is enabled). */
    thinking?: string;
    durationMs?: number;
    /** Unique run identifier. */
    runId?: string;
    /** Name of the agent that produced this output. */
    agentName?: string;
    /** Session identifier for multi-turn conversations. */
    sessionId?: string;
    /** User identifier (when provided). */
    userId?: string;
    /** Model ID used for this run (e.g. "gpt-4o", "gemini-2.5-flash"). */
    model?: string;
    /** Provider ID (e.g. "openai", "vertex", "anthropic"). */
    modelProvider?: string;
    /** Run completion status. */
    status?: "completed" | "error" | "stopped" | "cancelled";
    /** Unix timestamp (ms) when the run was created. */
    createdAt?: number;
    /** Enhanced metrics with timing and token breakdown. */
    metrics?: RunMetrics;
    /** Newly produced canonical user/model/tool exchange, before request projection. */
    newMessages?: ChatMessage[];
    /** Full conversation messages sent to the LLM (system + history + user input). */
    messages?: ChatMessage[];
    /** Provider-specific response identifier (e.g. OpenAI's chatcmpl-xxx). */
    responseId?: string;
    /**
     * Self-critique result when reflection is enabled. Low scores indicate the
     * output may need human review — use for confidence-gated escalation.
     */
    critique?: {
        pass: boolean;
        score: number;
        feedback: string;
        revisions: number;
    };
}
```

Related: [`ChatMessage`](/api-reference/core/models#chatmessage), [`RunMetrics`](/api-reference/core/agent#runmetrics), [`TokenUsage`](/api-reference/core/models#tokenusage), [`ToolCallResult`](/api-reference/core/tools#toolcallresult).

## SandboxAgent

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/sandbox-agent.ts)

```typescript theme={null}
/** Owned workspace lifecycle. Local helpers check paths; local programs retain host privileges. */
export declare class SandboxAgent {
    readonly kind: "sandbox-agent";
    constructor(config: SandboxAgentConfig);
    get ready(): boolean;
    start(): Promise<void>;
    writeFile(path: string, contents: string, encoding?: "utf8" | "base64"): Promise<void>;
    readFile(path: string, encoding?: "utf8" | "base64"): Promise<string | null>;
    shell(command: string, options?: SandboxRunOptions): Promise<SandboxRunResult>;
    run(code: string, options?: SandboxRunOptions): Promise<SandboxRunResult>;
    snapshot(): Promise<WorkspaceSnapshot>;
    resume(snapshot: WorkspaceSnapshot): Promise<void>;
    close(): Promise<void>;
}
```

Related: [`SandboxAgentConfig`](/api-reference/core/agent#sandboxagentconfig), [`SandboxRunOptions`](/api-reference/core/sandbox#sandboxrunoptions), [`SandboxRunResult`](/api-reference/core/sandbox#sandboxrunresult), [`WorkspaceSnapshot`](/api-reference/core/agent#workspacesnapshot).

## SandboxAgentConfig

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/sandbox-agent.ts)

```typescript theme={null}
export interface SandboxAgentConfig {
    /** unix-local executes trusted code on the host; it is not a security sandbox. */
    backend: SandboxBackend;
    remote?: CloudSandbox;
    workspace?: WorkspaceManifest;
    /** Explicit host environment names to forward, in addition to PATH. */
    inheritEnv?: string[];
    /** Combined captured output bound; exceeding it terminates the local process group. Default 1 MiB. */
    maxOutputBytes?: number;
}
```

Related: [`CloudSandbox`](/api-reference/core/sandbox#cloudsandbox), [`SandboxBackend`](/api-reference/core/agent#sandboxbackend), [`WorkspaceManifest`](/api-reference/core/agent#workspacemanifest).

## SandboxBackend

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/sandbox-agent.ts)

```typescript theme={null}
export type SandboxBackend = "unix-local" | "remote";
```

## serializeAgentConfig

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/serialization.ts)

```typescript theme={null}
export declare function serializeAgentConfig(config: any): SerializedAgent;
```

Related: [`SerializedAgent`](/api-reference/core/agent#serializedagent).

## SerializedAgent

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/serialization.ts)

```typescript theme={null}
export interface SerializedAgent {
    name: string;
    modelId: string;
    providerId: string;
    instructions?: string;
    toolNames: string[];
    temperature?: number;
    maxTokens?: number;
    maxToolRoundtrips?: number;
    sessionId?: string;
    userId?: string;
    logLevel?: string;
    reasoning?: ReasoningConfig;
    providerOptions?: ProviderOptions;
    metadata?: Record<string, unknown>;
}
```

Related: [`ReasoningConfig`](/api-reference/core/models#reasoningconfig).

## spawnSubagent

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/subagent.ts)

```typescript theme={null}
/**
 * Run a child agent with a fresh message list.
 * The parent only sees the child's final text — not its tool chatter.
 */
export declare function spawnSubagent(opts: SpawnSubagentOptions): Promise<string>;
```

Related: [`SpawnSubagentOptions`](/api-reference/core/agent#spawnsubagentoptions).

## SpawnSubagentOptions

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/subagent.ts)

```typescript theme={null}
export interface SpawnSubagentOptions {
    parent: Agent;
    task: string;
    spec?: SubagentSpec;
    runOpts?: RunOpts;
    depth?: number;
    maxDepth?: number;
    /** Actual parent run identity, when delegation originates from a tool call. */
    parentRunId?: string;
}
```

Related: [`Agent`](/api-reference/core/agent#agent), [`RunOpts`](/api-reference/core/agent#runopts), [`SubagentSpec`](/api-reference/core/agent#subagentspec).

## SubagentSpec

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/subagent.ts)

```typescript theme={null}
export interface SubagentSpec {
    name?: string;
    instructions?: string;
    tools?: ToolDef[];
    maxToolRoundtrips?: number;
}
```

Related: [`ToolDef`](/api-reference/core/tools#tooldef).

## TeamFactory

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/factory.ts)

```typescript theme={null}
export declare class TeamFactory {
    constructor(base: TeamConfig);
    create(scope?: FactoryContext): Team;
}
```

Related: [`FactoryContext`](/api-reference/core/agent#factorycontext), [`Team`](/api-reference/core/team#team), [`TeamConfig`](/api-reference/core/team#teamconfig).

## ToolResultLimitConfig

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/types.ts)

```typescript theme={null}
export interface ToolResultLimitConfig {
    /** Max characters before the strategy kicks in. Default: 20000 (~5K tokens). */
    maxChars?: number;
    /**
     * `"truncate"` — smart JSON truncation: arrays are sliced, remainder noted.
     * `"summarize"` — sends the full result to a cheap model for summarization.
     * Default: `"truncate"`.
     */
    strategy?: "truncate" | "summarize";
    /** Model used for summarization. Required when strategy is `"summarize"`. */
    model?: ModelProvider;
}
```

Related: [`ModelProvider`](/api-reference/core/models#modelprovider).

## toolResultPreview

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/progress-protocol.ts)

```typescript theme={null}
export declare function toolResultPreview(result: string, maxLength?: number): string;
```

## WorkflowFactory

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/factory.ts)

```typescript theme={null}
export declare class WorkflowFactory<TState extends Record<string, unknown> = Record<string, unknown>> {
    constructor(base: WorkflowConfig<TState>);
    create(_scope?: FactoryContext): Workflow<TState>;
}
```

Related: [`FactoryContext`](/api-reference/core/agent#factorycontext), [`Workflow`](/api-reference/core/workflow#workflow), [`WorkflowConfig`](/api-reference/core/workflow#workflowconfig).

## WorkspaceFile

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/sandbox-agent.ts)

```typescript theme={null}
export interface WorkspaceFile {
    path: string;
    contents: string;
    encoding?: "utf8" | "base64";
}
```

## WorkspaceManifest

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/sandbox-agent.ts)

```typescript theme={null}
export interface WorkspaceManifest {
    files?: WorkspaceFile[];
    gitClones?: Array<{
        repo: string;
        path: string;
        ref?: string;
    }>;
    env?: Record<string, string>;
}
```

Related: [`WorkspaceFile`](/api-reference/core/agent#workspacefile).

## WorkspaceSnapshot

[Source](https://github.com/agentiumOS/agentium/blob/v4.0.0/packages/core/src/agent/sandbox-agent.ts)

```typescript theme={null}
export interface WorkspaceSnapshot {
    takenAt: number;
    files: WorkspaceFile[];
    env: Record<string, string>;
}
```

Related: [`WorkspaceFile`](/api-reference/core/agent#workspacefile).

## Supporting types

These local shapes appear in public signatures but are not named exports of this entrypoint.

### ProviderOptions

```typescript theme={null}
/** Provider request options that are not shared sampling knobs. */
export interface ProviderOptions {
    /** Anthropic: cache the system prompt (`cache_control: ephemeral`). */
    promptCache?: boolean;
    /** OpenAI Responses `prompt_cache_retention`. */
    promptCacheRetention?: "in_memory" | "24h";
    /**
     * Anthropic server compaction once input exceeds this many tokens.
     * Values under 50000 are raised to 50000. Requires the compaction beta.
     */
    compactionTokens?: number;
    /** Anthropic: clear old tool results server-side. Requires the context-management beta. */
    clearToolResults?: boolean;
    /** Gemini media token budget. */
    mediaResolution?: "low" | "medium" | "high" | "ultra_high";
    /** Gemini explicit cache resource name (`cachedContents/...`). */
    cachedContent?: string;
    /** Gemini Google Search grounding tool. */
    googleSearch?: boolean;
}
```

### ArtifactsConfig

```typescript theme={null}
export interface ArtifactsConfig {
    enabled?: boolean;
    /**
     * Maximum byte size of a tool result before it auto-converts to an `art:` pointer.
     * Default: 51200 (50KB).
     */
    maxToolOutputBytes?: number;
    /** Characters kept in the preview surfaced to the LLM. Default: 200. */
    previewChars?: number;
}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.