@agentium/core. Read the agents and execution guide for setup and behavior, or return to the package reference.
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
Sourceexport 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;
}
AgentConfig, AgentiumSchema, ApprovalManager, CheckpointManager, DeserializeRegistry, EventBus, MemoryManager, MessageContent, ModelProvider, RunContext, RunOpts, RunOutput.
AgentConfig
Sourceexport 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;
}
AgentFileSystemConfig, AgentHooks, AgentiumSchema, ApprovalConfig, ApprovalManager, CompressionManager, ContextCompactorConfig, CostTracker, EventBus, ExecutionPolicy, FileMemoryConfig, HandoffConfig.
AgentFactory
Source/**
* 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;
}
Agent, AgentConfig, FactoryContext.
AgentHooks
Sourceexport 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>;
}
RunContext, RunOutput.
buildAgentConfigFromSerialized
Sourceexport 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;
};
DeserializeRegistry, ModelProvider, SerializedAgent, ToolDef.
ComputerAction
Source/**
* 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
Sourceexport 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
Sourceexport 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>;
}
ComputerAction, ComputerActionResult.
ComputerUseAgent
Sourceexport 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>;
}
ComputerUseAgentConfig, ComputerUseRunOutput.
ComputerUseAgentConfig
Sourceexport 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;
}
ComputerExecutor.
ComputerUseRunOutput
Sourceexport interface ComputerUseRunOutput {
/** Final assistant text. */
text: string;
/** All actions taken during the run. */
actions: ComputerAction[];
/** Number of LLM iterations consumed. */
iterations: number;
}
ComputerAction.
ContextCompactorConfig
Sourceexport interface ContextCompactorConfig {
maxContextTokens: number;
reserveTokens?: number;
strategy: "trim" | "summarize" | "hybrid";
summarizeModel?: ModelProvider;
priorityOrder?: ("system" | "recentHistory" | "memory" | "tools")[];
}
ModelProvider.
createTaskTool
Sourceexport declare function createTaskTool(parent: Agent, config?: {
maxDepth?: number;
}): ToolDef;
Agent, ToolDef.
CritiqueResult
Sourceexport interface CritiqueResult {
pass: boolean;
score: number;
feedback: string;
suggestedRevision?: string;
}
defineExternalAgent
Source/**
* 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;
ExternalAgentConfig, ServableAgent.
DeserializeRegistry
Sourceexport interface DeserializeRegistry {
models: Record<string, ModelProvider>;
tools?: Record<string, ToolDef>;
storage?: StorageDriver;
}
ModelProvider, StorageDriver, ToolDef.
DrainController
Source/**
* 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
Sourceexport declare function estimateProgress(roundtrip: number, maxRoundtrips: number, phase: "llm" | "tools"): number;
ExecutionServices
Source/** 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;
}
ApprovalManager, ChatMessage, ExecutionPolicy, ModelConfig, ModelProvider, ModelResponse, RunContext, StreamChunk, ToolCall, ToolCallResult, ToolDef, ToolDefinition.
ExternalAgentConfig
Sourceexport 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;
}
EventBus, MessageContent, RunOpts, RunOutput, StreamChunk.
FactoryContext
Sourceexport type FactoryContext = StorageScope;
StorageScope.
GuardrailResult
Sourceexport type GuardrailResult = {
pass: true;
} | {
pass: false;
reason: string;
};
InputGuardrail
Sourceexport interface InputGuardrail {
name: string;
validate: (input: MessageContent, ctx: RunContext) => Promise<GuardrailResult>;
}
GuardrailResult, MessageContent, RunContext.
LLMLoop
Sourceexport 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>;
}
AgentiumSchema, ChatMessage, CheckpointManager, Logger, LoopHooks, ModelProvider, ReasoningConfig, RetryConfig, RunContext, RunOutput, StreamChunk, ToolCallResult.
LoopEscapeResult
Sourceexport interface LoopEscapeResult {
detected: boolean;
repeatedTool: string;
repeatCount: number;
escapePrompt: string;
}
LoopHooks
Source/** 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>;
}
ChatMessage, TokenUsage.
OutputGuardrail
Sourceexport interface OutputGuardrail {
name: string;
validate: (output: RunOutput, ctx: RunContext) => Promise<GuardrailResult>;
}
GuardrailResult, RunContext, RunOutput.
PlanCritiqueResult
Sourceexport interface PlanCritiqueResult {
approved: boolean;
concerns: string[];
suggestion?: string;
}
ProgressEvent
Sourceexport 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
Sourceexport interface ReflectionConfig {
enabled: boolean;
maxReflections?: number;
critic?: ModelProvider;
preExecutionReview?: boolean;
loopEscapeDetection?: boolean;
postMortemLearning?: boolean;
customCriteria?: string;
}
ModelProvider.
ReflectionManager
Sourceexport 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;
}
ChatMessage, CritiqueResult, LoopEscapeResult, ModelProvider, PlanCritiqueResult, ReflectionConfig, RunOutput, ToolCall.
RunCancelledError
Sourceexport declare class RunCancelledError extends Error {
constructor(message?: string);
}
RunContext
Sourceexport 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;
}
ChatMessage, EventBus, ExecutionPolicy, ExecutionServices, RunMode.
RunDrainedError
Source/**
* 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
Sourceexport 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
Sourceexport 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>;
}
ChatMessage, ExecutionPolicy, ExecutionServices, RunMode.
RunOutput
Sourceexport 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;
};
}
ChatMessage, RunMetrics, TokenUsage, ToolCallResult.
SandboxAgent
Source/** 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>;
}
SandboxAgentConfig, SandboxRunOptions, SandboxRunResult, WorkspaceSnapshot.
SandboxAgentConfig
Sourceexport 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;
}
CloudSandbox, SandboxBackend, WorkspaceManifest.
SandboxBackend
Sourceexport type SandboxBackend = "unix-local" | "remote";
serializeAgentConfig
Sourceexport declare function serializeAgentConfig(config: any): SerializedAgent;
SerializedAgent.
SerializedAgent
Sourceexport 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>;
}
ReasoningConfig.
spawnSubagent
Source/**
* 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>;
SpawnSubagentOptions.
SpawnSubagentOptions
Sourceexport 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;
}
Agent, RunOpts, SubagentSpec.
SubagentSpec
Sourceexport interface SubagentSpec {
name?: string;
instructions?: string;
tools?: ToolDef[];
maxToolRoundtrips?: number;
}
ToolDef.
TeamFactory
Sourceexport declare class TeamFactory {
constructor(base: TeamConfig);
create(scope?: FactoryContext): Team;
}
FactoryContext, Team, TeamConfig.
ToolResultLimitConfig
Sourceexport 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;
}
ModelProvider.
toolResultPreview
Sourceexport declare function toolResultPreview(result: string, maxLength?: number): string;
WorkflowFactory
Sourceexport declare class WorkflowFactory<TState extends Record<string, unknown> = Record<string, unknown>> {
constructor(base: WorkflowConfig<TState>);
create(_scope?: FactoryContext): Workflow<TState>;
}
FactoryContext, Workflow, WorkflowConfig.
WorkspaceFile
Sourceexport interface WorkspaceFile {
path: string;
contents: string;
encoding?: "utf8" | "base64";
}
WorkspaceManifest
Sourceexport interface WorkspaceManifest {
files?: WorkspaceFile[];
gitClones?: Array<{
repo: string;
path: string;
ref?: string;
}>;
env?: Record<string, string>;
}
WorkspaceFile.
WorkspaceSnapshot
Sourceexport interface WorkspaceSnapshot {
takenAt: number;
files: WorkspaceFile[];
env: Record<string, string>;
}
WorkspaceFile.
Supporting types
These local shapes appear in public signatures but are not named exports of this entrypoint.ProviderOptions
/** 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
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;
}