Core
Core
Core classes for authentication, agents, and providers
Agent class
Agent class - represents an AI assistant with tool calling capabilities
Extends BaseAgent to inherit:
- Connector resolution
- Provider initialization
- Tool manager initialization
- Permission manager initialization
- Session management
- Lifecycle/cleanup
Static Methods
static create()
Create a new agent
static create(config: AgentConfig): Agent
Parameters:
config:AgentConfig
Returns: Agent
static resume()
Resume an agent from a saved session
static async resume(
sessionId: string,
config: Omit<AgentConfig, 'session'> & { session: NonNullable<AgentConfig['session']> & { storage: IContextStorage } }
): Promise<Agent>
Parameters:
sessionId:stringconfig:Omit<AgentConfig, "session"> & { session: BaseSessionConfig & { storage: IContextStorage; }; }
Returns: Promise<Agent>
static fromStorage()
Create an agent from a stored definition
Loads agent configuration from storage and creates a new Agent instance. The connector must be registered at runtime before calling this method.
static async fromStorage(
agentId: string,
storage?: IAgentDefinitionStorage,
overrides?: Partial<AgentConfig>
): Promise<Agent | null>
Parameters:
agentId:stringstorage:IAgentDefinitionStorage | undefined(optional)overrides:Partial<AgentConfig> | undefined(optional)
Returns: Promise<Agent | null>
static hydrate()
Hydrate an agent from stored definition + saved session.
Returns a fully reconstructed Agent with conversation history and plugin
states restored. The caller can customize the agent (add tools, hooks, etc.)
before calling run() to continue execution.
This is the primary API for resuming suspended sessions.
static async hydrate(
sessionId: string,
options: {
/** Agent ID to load definition for */
agentId: string;
/** Optional definition storage override */
definitionStorage?: IAgentDefinitionStorage;
/** Optional config overrides (e.g., connector, model) */
overrides?: Partial<AgentConfig>;
}
): Promise<Agent>
Parameters:
sessionId:stringoptions:{ agentId: string; definitionStorage?: IAgentDefinitionStorage | undefined; overrides?: Partial<AgentConfig> | undefined; }
Returns: Promise<Agent>
Methods
scopedTo()
Build a fresh agent restricted to the named tools, reusing this agent's connector, model, and userId.
This is the "filtered superagent" pattern: keep one agent carrying every
possible tool, and at routine-execution time hand the runner an agent
restricted to exactly the tools the routine declared in requiredTools.
The returned agent is independent — its own AgentContextNextGen, own
ToolManager (with fresh circuit breakers), own hooks. Caller owns its
lifecycle and must destroy() it.
Tool functions are shared by reference, so connector tools resolve the
same way they would on the parent — no re-instantiation. identities is
not propagated to avoid auto-regenerating a full connector tool surface
(which would defeat the scope).
Plugins are NOT inherited. The scoped agent runs with default context
features only (working memory, in-context memory). Memory plugins,
SharedWorkspace, custom plugins on the parent are not carried over.
Routines that need them must declare requiredPlugins so the runner's
missing-plugin check fails loudly. Matches Mode 1 (connector + model)
behavior in the routine runner.
Permissions ARE inherited. The parent's permissions config
(autoApproveAll, allowlist, denylist, policies, etc.) is propagated
verbatim so the scoped sub-agent runs with the same trust posture as
the parent. Routine execution is autonomous — there is no interactive
approval surface — so an autoApproveAll superagent must produce
autoApproveAll scoped children.
Throws if any name is not registered on this agent.
scopedTo(
allowedToolNames: string[],
options?: { instructions?: string },
): Agent
Parameters:
allowedToolNames:string[]options:{ instructions?: string | undefined; } | undefined(optional)
Returns: Agent
getAgentType()
protected getAgentType(): 'agent' | 'task-agent' | 'universal-agent'
Returns: "agent" | "task-agent" | "universal-agent"
hasContext()
Check if context management is enabled. Always returns true since AgentContext is always created by BaseAgent.
hasContext(): boolean
Returns: boolean
rolloverContext()
Force a semantic rollover between provider sessions.
This method owns the Agent's execution slot, so it cannot race run(), stream(), async continuation, or an active Realtime/external execution. By default it summarizes through the Agent's configured connector/model, keeps the eight most-recent user turns exact, preserves plugin state and the full history journal, and checkpoints when session storage is present.
async rolloverContext(
options: AgentContextRolloverOptions = {},
): Promise<ContextRolloverResult>
Parameters:
options:AgentContextRolloverOptions(optional) (default:{})
Returns: Promise<ContextRolloverResult>
compactContext()
Explicit bounded reduction through the configured composition policy.
async compactContext(options: AgentContextCompactionOptions = {}): Promise<ContextCompactionReport>
Parameters:
options:AgentContextCompactionOptions(optional) (default:{})
Returns: Promise<ContextCompactionReport>
getRoutingDiagnostics()
Read the latest routed execution's detached, secret-free decision.
getRoutingDiagnostics(): ModelRoutingDiagnostics | undefined
Returns: ModelRoutingDiagnostics | undefined
beginExternalExecution()
Start a long-lived execution driven by an external model transport.
Realtime voice sessions use this to share the Agent's normal tool hooks, permission pipeline, limits, events, and metrics without running a second text-model loop.
async beginExternalExecution(options: ExternalExecutionOptions = {}): Promise<string>
Parameters:
options:ExternalExecutionOptions(optional) (default:{})
Returns: Promise<string>
recordExternalUserInput()
Add user input owned by the active external transport and retain the exact input sequence for lifecycle hooks.
recordExternalUserInput(content: string | Content[]): string
Parameters:
content:string | Content[]
Returns: string
executeExternalToolCall()
Execute a function call received from an external model transport. The call follows the same approval, hook, permission, timeout, connector, event, and metrics path as a tool selected by Agent.run().
async executeExternalToolCall(
call: ExternalToolCall,
options: { iteration?: number; signal?: AbortSignal } = {},
): Promise<ToolResult>
Parameters:
call:ExternalToolCalloptions:{ iteration?: number | undefined; signal?: AbortSignal | undefined; }(optional) (default:{})
Returns: Promise<ToolResult>
recordExternalUsage()
Add provider-reported usage to the active external execution.
recordExternalUsage(usage: Partial<TokenUsage>): void
Parameters:
usage:Partial<TokenUsage>
Returns: void
completeExternalExecution()
Complete the active external execution and run normal lifecycle hooks.
async completeExternalExecution(result: ExternalExecutionResult = {}): Promise<AgentResponse>
Parameters:
result:ExternalExecutionResult(optional) (default:{})
Returns: Promise<LLMResponse>
getLoopDiagnostics()
Detached diagnostics for the active/latest opt-in managed execution.
getLoopDiagnostics(): AgentLoopDiagnostics | undefined
Returns: AgentLoopDiagnostics | undefined
run()
Run the agent with input
async run(input: string | InputItem[], options?: RunOptions): Promise<AgentResponse>
Parameters:
input:string | InputItem[]options:RunOptions | undefined(optional)
Returns: Promise<LLMResponse>
stream()
Stream response from the agent
async *stream(input: string | InputItem[], options?: RunOptions): AsyncIterableIterator<StreamEvent>
Parameters:
input:string | InputItem[]options:RunOptions | undefined(optional)
Returns: AsyncIterableIterator<StreamEvent>
continueWithAsyncResults()
Continue the agentic loop with async tool results. Can be called automatically (autoContinue) or manually by the caller.
Injects results as a user message and re-enters the agentic loop.
async continueWithAsyncResults(results?: ToolResult[]): Promise<AgentResponse>
Parameters:
results:ToolResult[] | undefined(optional)
Returns: Promise<LLMResponse>
hasPendingAsyncTools()
Check if there are any pending async tools
hasPendingAsyncTools(includeQueued = false): boolean
Parameters:
includeQueued:boolean(optional) (default:false)
Returns: boolean
getPendingAsyncTools()
Get info about pending async tools
getPendingAsyncTools(): PendingAsyncTool[]
Returns: PendingAsyncTool[]
cancelAsyncTool()
Cancel a specific async tool by toolCallId
cancelAsyncTool(toolCallId: string): void
Parameters:
toolCallId:string
Returns: void
cancelAllAsyncTools()
Cancel all pending async tools
cancelAllAsyncTools(): void
Returns: void
pause()
Pause execution
pause(reason?: string): void
Parameters:
reason:string | undefined(optional)
Returns: void
resume()
Resume execution
resume(): void
Returns: void
cancel()
Cancel execution
cancel(reason?: string): void
Parameters:
reason:string | undefined(optional)
Returns: void
inject()
Inject a message into this agent's context, to be processed on the next agentic loop iteration. Safe to call while the agent is running.
Used by orchestrator tools (send_message) to communicate with workers during or between turns.
inject(message: string, role: 'user' | 'developer' = 'user'): void
Parameters:
message:stringrole:"user" | "developer"(optional) (default:'user')
Returns: void
getToolDefinitions()
Return the enabled, identity-filtered tool definitions exactly as they would be sent by the normal Agent loop. External model transports should use this instead of reading ToolManager registrations directly.
getToolDefinitions(): import('../domain/entities/Tool.js').FunctionToolDefinition[]
Returns: FunctionToolDefinition[]
getRuntimeConfigSnapshot()
Return a runtime-options snapshot. Arrays and plain records are deeply isolated. Callable or opaque host-local values are retained by reference.
Set includeHostLocal to false when constructing a portable projection.
This excludes provider options, native tools, and data-governance policy
before cloning, so host callbacks and credentials are never traversed.
getRuntimeConfigSnapshot(
options: { includeHostLocal?: boolean } = {},
): AgentRuntimeConfigSnapshot
Parameters:
options:{ includeHostLocal?: boolean | undefined; }(optional) (default:{})
Returns: AgentRuntimeConfigSnapshot
inspectCapabilities()
Inspect resolved managed-Agent settings and provider support without model or storage IO.
inspectCapabilities(): AgentCapabilityInspection
Returns: AgentCapabilityInspection
getInstructionTemplate()
Return the unrendered instruction template supplied at Agent creation.
getInstructionTemplate(): string | undefined
Returns: string | undefined
getRenderedInstructionTemplate()
Return the creation-time instruction template after static rendering.
getRenderedInstructionTemplate(): string | undefined
Returns: string | undefined
approveToolForSession()
approveToolForSession(toolName: string): void
Parameters:
toolName:string
Returns: void
revokeToolApproval()
revokeToolApproval(toolName: string): void
Parameters:
toolName:string
Returns: void
getApprovedTools()
getApprovedTools(): string[]
Returns: string[]
toolNeedsApproval()
toolNeedsApproval(toolName: string): boolean
Parameters:
toolName:string
Returns: boolean
toolIsBlocked()
toolIsBlocked(toolName: string): boolean
Parameters:
toolName:string
Returns: boolean
allowlistTool()
allowlistTool(toolName: string): void
Parameters:
toolName:string
Returns: void
blocklistTool()
blocklistTool(toolName: string): void
Parameters:
toolName:string
Returns: void
setModel()
setModel(model: string): void
Parameters:
model:string
Returns: void
getTemperature()
getTemperature(): number | undefined
Returns: number | undefined
setTemperature()
setTemperature(temperature: number): void
Parameters:
temperature:number
Returns: void
saveDefinition()
async saveDefinition(
storage?: IAgentDefinitionStorage,
metadata?: AgentDefinitionMetadata
): Promise<void>
Parameters:
storage:IAgentDefinitionStorage | undefined(optional)metadata:AgentDefinitionMetadata | undefined(optional)
Returns: Promise<void>
getExecutionContext()
getExecutionContext(): ExecutionContext | null
Returns: ExecutionContext | null
getContext()
Alias for getExecutionContext() for backward compatibility
getContext(): ExecutionContext | null
Returns: ExecutionContext | null
getMetrics()
getMetrics()
Returns: ExecutionMetrics | null
getSummary()
getSummary()
Returns: { executionId: string; startTime: Date; currentIteration: number; paused: boolean; cancelled: boolean; metrics: { totalDuration: number; llmDuration: number; toolDuration: number; hookDuration: number; iterationCount: number; toolCallCount: number; toolSuccessCount: number; toolFailureCount: number; toolTimeoutCount: number; inputTokens: number; outputTokens: number; totalTokens: number; cachedInputTokens?: number | undefined; cacheCreationInputTokens?: number | undefined; reasoningTokens?: number | undefined; nativeToolCalls?: Record<string, number> | undefined; errors: { type: string; message: string; timestamp: Date; }[]; }; totalDuration: number; } | null
getAuditTrail()
getAuditTrail()
Returns: readonly AuditEntry[]
getProviderCircuitBreakerMetrics()
getProviderCircuitBreakerMetrics()
Returns: unknown
getToolCircuitBreakerStates()
getToolCircuitBreakerStates()
Returns: Map<string, CircuitState>
getToolCircuitBreakerMetrics()
getToolCircuitBreakerMetrics(toolName: string)
Parameters:
toolName:string
Returns: CircuitBreakerMetrics | undefined
resetToolCircuitBreaker()
resetToolCircuitBreaker(toolName: string): void
Parameters:
toolName:string
Returns: void
isRunning()
isRunning(): boolean
Returns: boolean
isPaused()
isPaused(): boolean
Returns: boolean
isCancelled()
isCancelled(): boolean
Returns: boolean
clearConversation()
Clear conversation history, resetting the context for a fresh interaction. Plugins (working memory, in-context memory, etc.) are NOT affected.
clearConversation(reason?: string): void
Parameters:
reason:string | undefined(optional)
Returns: void
registerHook()
Register a hook on the agent. Can be called after creation.
registerHook(name: HookName, hook: Function): void
Parameters:
name:"before:execution" | "after:execution" | "before:llm" | "after:llm" | "before:tool" | "after:tool" | "approve:tool" | "pause:check"hook:Function
Returns: void
unregisterHook()
Unregister a previously registered hook by reference.
unregisterHook(name: HookName, hook: Function): boolean
Parameters:
name:"before:execution" | "after:execution" | "before:llm" | "after:llm" | "before:tool" | "after:tool" | "approve:tool" | "pause:check"hook:Function
Returns: boolean
destroy()
destroy(): void
Returns: void
AgentRegistry class
📍 src/core/AgentRegistry.ts:185
Static Methods
static register()
Register an agent. Called automatically by Agent constructor.
static register(agent: IRegistrableAgent): void
Parameters:
agent:IRegistrableAgent
Returns: void
static unregister()
Unregister an agent. Called automatically by Agent.destroy().
static unregister(id: string, reason: 'destroyed' | 'manual' = 'destroyed'): void
Parameters:
id:stringreason:"destroyed" | "manual"(optional) (default:'destroyed')
Returns: void
static get()
Get agent by registry ID (unique)
static get(id: string): IRegistrableAgent | undefined
Parameters:
id:string
Returns: IRegistrableAgent | undefined
static getByName()
Get all agents with a given name (names are NOT unique)
static getByName(name: string): IRegistrableAgent[]
Parameters:
name:string
Returns: IRegistrableAgent[]
static has()
Check if an agent exists in the registry
static has(id: string): boolean
Parameters:
id:string
Returns: boolean
static list()
List all tracked registry IDs
static list(): string[]
Returns: string[]
static filter()
Return agents matching all provided filter criteria
static filter(filter: AgentFilter): IRegistrableAgent[]
Parameters:
filter:AgentFilter
Returns: IRegistrableAgent[]
static listInfo()
Lightweight info for all agents
static listInfo(): AgentInfo[]
Returns: AgentInfo[]
static filterInfo()
Lightweight info for agents matching filter
static filterInfo(filter: AgentFilter): AgentInfo[]
Parameters:
filter:AgentFilter
Returns: AgentInfo[]
static inspect()
Deep inspection of a single agent
static async inspect(id: string): Promise<AgentInspection | null>
Parameters:
id:string
Returns: Promise<AgentInspection | null>
static inspectAll()
Deep inspection of all agents
static async inspectAll(): Promise<AgentInspection[]>
Returns: Promise<AgentInspection[]>
static inspectMatching()
Deep inspection of agents matching filter
static async inspectMatching(filter: AgentFilter): Promise<AgentInspection[]>
Parameters:
filter:AgentFilter
Returns: Promise<AgentInspection[]>
static getStats()
Aggregate counts by status/model/connector
static getStats(): AgentRegistryStats
Returns: AgentRegistryStats
static getAggregateMetrics()
Aggregate metrics across all agents (tokens, tool calls, errors)
static getAggregateMetrics(): AggregateMetrics
Returns: AggregateMetrics
static getChildren()
Get child agents of a parent
static getChildren(parentId: string): IRegistrableAgent[]
Parameters:
parentId:string
Returns: IRegistrableAgent[]
static getParent()
Get parent agent of a child
static getParent(childId: string): IRegistrableAgent | undefined
Parameters:
childId:string
Returns: IRegistrableAgent | undefined
static getTree()
Get recursive tree starting from a root agent
static getTree(rootId: string): AgentTreeNode | null
Parameters:
rootId:string
Returns: AgentTreeNode | null
static on()
Subscribe to registry lifecycle events
static on<K extends keyof AgentRegistryEvents>(
event: K,
listener: (data: AgentRegistryEvents[K]) => void,
): void
Parameters:
event:Klistener:(data: AgentRegistryEvents[K]) => void
Returns: void
static off()
Unsubscribe from registry lifecycle events
static off<K extends keyof AgentRegistryEvents>(
event: K,
listener: (data: AgentRegistryEvents[K]) => void,
): void
Parameters:
event:Klistener:(data: AgentRegistryEvents[K]) => void
Returns: void
static once()
Subscribe once to a registry lifecycle event
static once<K extends keyof AgentRegistryEvents>(
event: K,
listener: (data: AgentRegistryEvents[K]) => void,
): void
Parameters:
event:Klistener:(data: AgentRegistryEvents[K]) => void
Returns: void
static onAgentEvent()
Fan-in: receive ALL events from ALL agents through one listener
static onAgentEvent(listener: AgentEventListener): void
Parameters:
listener:AgentEventListener
Returns: void
static offAgentEvent()
Remove a fan-in listener
static offAgentEvent(listener: AgentEventListener): void
Parameters:
listener:AgentEventListener
Returns: void
static pauseAgent()
Pause a specific agent. Returns true if found and paused.
static pauseAgent(id: string): boolean
Parameters:
id:string
Returns: boolean
static resumeAgent()
Resume a specific agent. Returns true if found and resumed.
static resumeAgent(id: string): boolean
Parameters:
id:string
Returns: boolean
static cancelAgent()
Cancel a specific agent. Returns true if found and cancelled.
static cancelAgent(id: string, reason?: string): boolean
Parameters:
id:stringreason:string | undefined(optional)
Returns: boolean
static destroyAgent()
Destroy a specific agent. Returns true if found and destroyed.
static destroyAgent(id: string): boolean
Parameters:
id:string
Returns: boolean
static pauseMatching()
Pause all agents matching filter. Returns count paused.
static pauseMatching(filter: AgentFilter): number
Parameters:
filter:AgentFilter
Returns: number
static cancelMatching()
Cancel all agents matching filter. Returns count cancelled.
static cancelMatching(filter: AgentFilter, reason?: string): number
Parameters:
filter:AgentFilterreason:string | undefined(optional)
Returns: number
static destroyMatching()
Destroy all agents matching filter. Returns count destroyed.
static destroyMatching(filter: AgentFilter): number
Parameters:
filter:AgentFilter
Returns: number
static pauseAll()
Pause all agents. Returns count paused.
static pauseAll(): number
Returns: number
static cancelAll()
Cancel all agents. Returns count cancelled.
static cancelAll(reason?: string): number
Parameters:
reason:string | undefined(optional)
Returns: number
static destroyAll()
Destroy ALL tracked agents. Returns count destroyed.
static destroyAll(): number
Returns: number
static clear()
Clear registry without destroying agents (for testing)
static clear(): void
Returns: void
Connector class
Connector class - represents a single authenticated connection
Static Methods
static setRegistry()
Set a custom connector registry implementation. When set, all static read methods (get, has, list, listAll, size, etc.) delegate to this registry instead of the internal Map.
Use this to plug in multi-tenant, lazy-loading, or any custom connector resolution strategy. Pass null to revert to the built-in Map-based registry.
static setRegistry(registry: IConnectorRegistry | null): void
Parameters:
registry:IConnectorRegistry | null
Returns: void
static getRegistry()
Get the current custom registry (or null if using the built-in registry).
static getRegistry(): IConnectorRegistry | null
Returns: IConnectorRegistry | null
static create()
Create and register a new connector
static create(config: ConnectorConfig & { name: string }): Connector
Parameters:
config:ConnectorConfig & { name: string; }
Returns: Connector
static get()
Get a connector by name
static get(name: string): Connector
Parameters:
name:string
Returns: Connector
static has()
Check if a connector exists
static has(name: string): boolean
Parameters:
name:string
Returns: boolean
static list()
List all registered connector names
static list(): string[]
Returns: string[]
static remove()
Remove a connector
static remove(name: string): boolean
Parameters:
name:string
Returns: boolean
static clear()
Clear all connectors (useful for testing)
static clear(): void
Returns: void
static getFromMap()
Get a connector from the internal Map, bypassing the custom registry. Returns undefined if not found (does not throw).
static getFromMap(name: string): Connector | undefined
Parameters:
name:string
Returns: Connector | undefined
static hasInMap()
Check if a connector exists in the internal Map, bypassing the custom registry.
static hasInMap(name: string): boolean
Parameters:
name:string
Returns: boolean
static listAllFromMap()
List all connector instances from the internal Map, bypassing the custom registry.
static listAllFromMap(): Connector[]
Returns: Connector[]
static warmup()
Call the custom registry's warmup() if available. Entry points (middleware, request handlers) should call this before using sync read methods to ensure connectors are loaded for the current context (e.g., tenant/group).
No-op if no custom registry or no warmup method.
static async warmup(): Promise<void>
Returns: Promise<void>
static setDefaultStorage()
Set default token storage for OAuth connectors
static setDefaultStorage(storage: ITokenStorage): void
Parameters:
storage:ITokenStorage
Returns: void
static listAll()
Get all registered connectors
static listAll(): Connector[]
Returns: Connector[]
static size()
Get number of registered connectors
static size(): number
Returns: number
static getById()
Get a connector by ID
static getById(id: string): Connector
Parameters:
id:string
Returns: Connector
static setAccessPolicy()
Set a global access policy for connector scoping. Pass null to clear the policy.
static setAccessPolicy(policy: IConnectorAccessPolicy | null): void
Parameters:
policy:IConnectorAccessPolicy | null
Returns: void
static getAccessPolicy()
Get the current global access policy (or null if none set).
static getAccessPolicy(): IConnectorAccessPolicy | null
Returns: IConnectorAccessPolicy | null
static scoped()
Create a scoped (filtered) view of the connector registry. Requires a global access policy to be set via setAccessPolicy().
static scoped(context: ConnectorAccessContext): IConnectorRegistry
Parameters:
context:ConnectorAccessContext
Returns: IConnectorRegistry
static asRegistry()
Return the static Connector methods as an IConnectorRegistry object (unfiltered). Useful when code accepts the interface but you want the full admin view.
static asRegistry(): IConnectorRegistry
Returns: IConnectorRegistry
static getDescriptionsForTools()
Get connector descriptions formatted for tool parameters Useful for generating dynamic tool descriptions
static getDescriptionsForTools(): string
Returns: string
static getInfo()
Get connector info (for tools and documentation)
static getInfo(): Record<string, { displayName: string; description: string; baseURL: string }>
Returns: Record<string, { displayName: string; description: string; baseURL: string; }>
static setRefreshStrategyBackfill()
Register the refresh-strategy backfill resolver. Called by
vendors/index.ts once at boot. Idempotent (a second call replaces).
static setRefreshStrategyBackfill(
fn: NonNullable<typeof Connector.refreshStrategyBackfill>,
): void
Parameters:
fn:(serviceType: string | undefined, auth: OAuthConnectorAuth & { type: "oauth"; }) => { requiredScope?: string | undefined; scope?: string | undefined; authorizationParams?: Record<string, string> | undefined; } | undefined
Returns: void
Methods
getApiKey()
Get the API key (for api_key auth type)
getApiKey(): string
Returns: string
getToken()
Get the current access token (for OAuth, JWT, or API key) Handles automatic refresh if needed
async getToken(userId?: string, accountId?: string): Promise<string>
Parameters:
userId:string | undefined(optional)accountId:string | undefined(optional)
Returns: Promise<string>
startAuth()
Start OAuth authorization flow Returns the URL to redirect the user to
async startAuth(userId?: string, accountId?: string): Promise<string>
Parameters:
userId:string | undefined(optional)accountId:string | undefined(optional)
Returns: Promise<string>
handleCallback()
Handle OAuth callback Call this after user is redirected back from OAuth provider
Returns an optional raw ID token for caller-side OIDC verification. The ID token is not verified or persisted by the library; non-OIDC flows return {}.
async handleCallback(callbackUrl: string, userId?: string, accountId?: string): Promise<OAuthCallbackResult>
Parameters:
callbackUrl:stringuserId:string | undefined(optional)accountId:string | undefined(optional)
Returns: Promise<OAuthCallbackResult>
hasValidToken()
Check if the connector has a valid token
async hasValidToken(userId?: string, accountId?: string): Promise<boolean>
Parameters:
userId:string | undefined(optional)accountId:string | undefined(optional)
Returns: Promise<boolean>
listAccounts()
List account aliases for a user on this connector. Only applicable for OAuth connectors with multi-account support.
async listAccounts(userId?: string): Promise<string[]>
Parameters:
userId:string | undefined(optional)
Returns: Promise<string[]>
rekeyAccount()
Re-key a token from one accountId to another. Used to stabilize account IDs after OAuth — e.g., replacing a temporary random ID with the actual email address discovered post-authorization.
async rekeyAccount(userId: string, oldAccountId: string, newAccountId: string): Promise<boolean>
Parameters:
userId:stringoldAccountId:stringnewAccountId:string
Returns: Promise<boolean>
removeAccount()
Remove a specific account's stored token. Used when a user unlinks/disconnects one of their accounts. Only applicable for OAuth connectors with multi-account support.
async removeAccount(userId: string, accountId: string): Promise<boolean>
Parameters:
userId:stringaccountId:string
Returns: Promise<boolean>
getOptions()
Get vendor-specific options from config
getOptions(): Record<string, unknown>
Returns: Record<string, unknown>
getMetrics()
Get connector metrics
getMetrics(): {
requestCount: number;
successCount: number;
failureCount: number;
avgLatencyMs: number;
circuitBreakerState?: string;
}
Returns: { requestCount: number; successCount: number; failureCount: number; avgLatencyMs: number; circuitBreakerState?: string | undefined; }
resetCircuitBreaker()
Reset circuit breaker (force close)
resetCircuitBreaker(): void
Returns: void
fetch()
Make an authenticated fetch request using this connector This is the foundation for all vendor-dependent tools
Features:
- Timeout with AbortController
- Circuit breaker protection
- Retry with exponential backoff
- Request/response logging
async fetch(
endpoint: string,
options?: ConnectorFetchOptions,
userId?: string,
accountId?: string
): Promise<Response>
Parameters:
endpoint:stringoptions:ConnectorFetchOptions | undefined(optional)userId:string | undefined(optional)accountId:string | undefined(optional)
Returns: Promise<Response>
fetchJSON()
Make an authenticated fetch request and parse JSON response Throws on non-OK responses
async fetchJSON<T = unknown>(
endpoint: string,
options?: ConnectorFetchOptions,
userId?: string,
accountId?: string
): Promise<T>
Parameters:
endpoint:stringoptions:ConnectorFetchOptions | undefined(optional)userId:string | undefined(optional)accountId:string | undefined(optional)
Returns: Promise<T>
dispose()
Dispose of resources
dispose(): void
Returns: void
isDisposed()
Check if connector is disposed
isDisposed(): boolean
Returns: boolean
Properties
| Property | Type | Description |
|---|---|---|
id |
id: string |
- |
name |
name: string |
- |
vendor? |
`vendor: Vendor | undefined` |
config |
config: ConnectorConfig |
- |
AgentConfig interface
Agent configuration - extends BaseAgentConfig with Agent-specific options
Properties
| Property | Type | Description |
|---|---|---|
loopPolicy? |
`loopPolicy?: AgentLoopPolicy | null;` |
instructions? |
instructions?: string; |
System instructions for the agent |
temperature? |
temperature?: number; |
Temperature for generation |
maxIterations? |
maxIterations?: number; |
Maximum iterations for tool calling loop |
thinking? |
thinking?: ThinkingConfig; |
Vendor-agnostic thinking/reasoning configuration |
vendorOptions? |
vendorOptions?: Record<string, unknown>; |
Vendor-specific options (e.g., Google's thinkingLevel: 'low' |
promptCache? |
promptCache?: PromptCachePolicy; |
Provider-neutral prompt caching policy. |
nativeTools? |
nativeTools?: NativeToolRequest[]; |
Provider-hosted tools, separate from client-executed ToolFunctions. |
dataHandling? |
dataHandling?: DataHandlingPolicy; |
- |
context? |
`context?: AgentContextNextGen | AgentContextNextGenConfig;` |
| When provided (as AgentContextNextGen instance or config), Agent will: |
- Track conversation history
- Provide unified memory access
- Support session persistence via context
Pass an AgentContextNextGen instance or AgentContextNextGenConfig to enable. |
| toolExecutionTimeout? | toolExecutionTimeout?: number; | Hard timeout in milliseconds for any single tool execution.
Acts as a safety net: if a tool's own timeout mechanism fails
(e.g. a spawned child process doesn't exit), this will force-resolve
with an error. Default: 0 (disabled - relies on each tool's own timeout).
Example: toolExecutionTimeout: 300000 (5 minutes hard cap per tool call) |
| toolTimeout? | toolTimeout?: number; | - |
| hooks? | hooks?: HookConfig; | - |
| historyMode? | historyMode?: HistoryMode; | - |
| limits? | limits?: { maxExecutionTime?: number; maxToolCalls?: number; maxContextSize?: number; maxInputMessages?: number; }; | - |
| errorHandling? | errorHandling?: { hookFailureMode?: 'fail' | 'warn' | 'ignore'; toolFailureMode?: 'fail' | 'continue'; maxConsecutiveErrors?: number; }; | - |
| asyncTools? | asyncTools?: AsyncToolConfig; | Configuration for async (non-blocking) tool execution |
| emptyResponseRetry? | emptyResponseRetry?: { /** Enable retry for empty responses (default: true) */ enabled?: boolean; /** Max retry attempts (default: 2) */ maxRetries?: number; /** Initial backoff delay ms (default: 1000) */ initialDelayMs?: number; /** Max backoff delay ms (default: 5000) */ maxDelayMs?: number; }; | Configuration for retrying empty/incomplete LLM responses |
AgentContextCompactionOptions interface
Options for {@link Agent.rolloverContext}.
Properties
| Property | Type | Description |
|---|---|---|
target? |
target?: ContextCompactionTarget; |
Default all. Manual history compaction may run below the pressure threshold. |
signal? |
signal?: AbortSignal; |
- |
modelTask? |
modelTask?: ModelTask; |
- |
checkpoint? |
checkpoint?: boolean; |
Defaults to true when session storage is configured. |
AgentContextRolloverOptions interface
Properties
| Property | Type | Description |
|---|---|---|
modelTask? |
modelTask?: ModelTask; |
- |
preserveRecentTurns? |
preserveRecentTurns?: number; |
Number of most-recent user turns to retain verbatim. Default: 8. |
summarize? |
summarize?: ContextRolloverSummarizer; |
Optional trusted summarizer. When omitted, the Agent makes a tool-free |
| direct call through its configured connector and model. | ||
maxSummaryTokens? |
maxSummaryTokens?: number; |
Maximum output tokens for the built-in summarizer. Default: 2048. |
checkpoint? |
checkpoint?: boolean; |
Persist the rolled-over context immediately. Defaults to true when the |
| Agent has session storage and false otherwise. | ||
reason? |
reason?: string; |
Optional reason included in observability data. |
AgentFilter interface
📍 src/core/AgentRegistry.ts:56
Filter criteria for querying agents (all fields optional, AND logic)
Properties
| Property | Type | Description |
|---|---|---|
name? |
name?: string; |
Exact match on agent name |
model? |
model?: string; |
Exact match on model |
connector? |
connector?: string; |
Exact match on connector name |
status? |
`status?: AgentStatus | AgentStatus[];` |
parentAgentId? |
parentAgentId?: string; |
Filter by parent agent ID |
AgentInfo interface
📍 src/core/AgentRegistry.ts:36
Lightweight snapshot of an agent's state
Properties
| Property | Type | Description |
|---|---|---|
id |
id: string; |
Registry ID (UUID, unique) |
name |
name: string; |
Agent name (NOT unique — user-provided or auto-generated) |
model |
model: string; |
Model identifier |
connector |
connector: string; |
Connector name |
status |
status: AgentStatus; |
Current status |
createdAt |
createdAt: Date; |
When the agent was registered |
parentAgentId |
`parentAgentId: string | undefined;` |
childAgentIds |
childAgentIds: string[]; |
IDs of child agents spawned by this agent (live lookup) |
AgentInspection interface
📍 src/core/AgentRegistry.ts:95
Deep inspection of a single agent
Properties
| Property | Type | Description |
|---|---|---|
context |
context: IContextSnapshot; |
Full context snapshot (plugins, tools, budget, features, systemPrompt) |
conversation |
conversation: ReadonlyArray<InputItem>; |
Full conversation history |
currentInput |
currentInput: ReadonlyArray<InputItem>; |
Pending input (about to go to LLM) |
execution |
`execution: { |
id: string | null;
iteration: number;
metrics: ExecutionMetrics | null;
auditTrail: readonly AuditEntry[];
};| Current execution state | |toolStats|toolStats: ToolManagerStats;| Tool manager statistics | |circuitBreakers|circuitBreakers: Map<string, CircuitState>;| Circuit breaker states per tool | |children|children: AgentInfo[];` | Child agent info snapshots |
AgentRegistryEvents interface
📍 src/core/AgentRegistry.ts:118
Events emitted by the registry
Properties
| Property | Type | Description |
|---|---|---|
'agent:registered' |
'agent:registered': { agent: IRegistrableAgent; info: AgentInfo }; |
- |
'agent:unregistered' |
`'agent:unregistered': { id: string; name: string; reason: 'destroyed' | 'manual' };` |
'agent:statusChanged' |
'agent:statusChanged': { id: string; name: string; previous: AgentStatus; current: AgentStatus }; |
- |
'registry:empty' |
'registry:empty': Record<string, never>; |
- |
AgentRegistryStats interface
📍 src/core/AgentRegistry.ts:70
Aggregate statistics across all tracked agents
Properties
| Property | Type | Description |
|---|---|---|
total |
total: number; |
- |
byStatus |
byStatus: Record<AgentStatus, number>; |
- |
byModel |
byModel: Record<string, number>; |
- |
byConnector |
byConnector: Record<string, number>; |
- |
ConnectorFetchOptions interface
Fetch options with additional connector-specific settings
Properties
| Property | Type | Description |
|---|---|---|
timeout? |
timeout?: number; |
Override timeout for this request |
timeoutScope? |
`timeoutScope?: 'headers' | 'operation';` |
retryPolicy? |
`retryPolicy?: 'legacy' | 'safe';` |
skipRetry? |
skipRetry?: boolean; |
Skip retry for this request |
skipCircuitBreaker? |
skipCircuitBreaker?: boolean; |
Skip circuit breaker for this request |
ExternalExecutionOptions interface
Options for a non-LLM execution owned by an external transport.
Properties
| Property | Type | Description |
|---|---|---|
modelTask? |
modelTask?: ModelTask; |
Observation only: external transports retain responsibility for admission. |
source? |
source?: string; |
Stable label recorded in the execution context for observability. |
ExternalExecutionResult interface
Terminal data supplied when an external execution is completed.
Properties
| Property | Type | Description |
|---|---|---|
status? |
status?: AgentResponse['status']; |
- |
outputText? |
outputText?: string; |
- |
usage? |
usage?: Partial<TokenUsage>; |
- |
error? |
error?: Error; |
- |
ExternalToolCall interface
A function call received from an external model transport.
Properties
| Property | Type | Description |
|---|---|---|
id |
id: string; |
- |
name |
name: string; |
- |
arguments |
`arguments: string | Record<string, unknown>;` |
RunOptions interface
Per-call options for run() and stream(). These override the agent-level config for this single invocation.
Properties
| Property | Type | Description |
|---|---|---|
routing? |
`routing?: ModelRoutingRunOptions | null;` |
loopPolicy? |
`loopPolicy?: AgentLoopPolicy | null;` |
modelTask? |
modelTask?: ModelTask; |
Explicit process-local budget/usage shared with helper or other agent calls. |
thinking? |
thinking?: ThinkingConfig; |
Vendor-agnostic thinking/reasoning configuration |
temperature? |
temperature?: number; |
Temperature for generation |
parameterPolicy? |
parameterPolicy?: TextGenerateOptions['parameterPolicy']; |
- |
vendorOptions? |
vendorOptions?: Record<string, unknown>; |
Vendor-specific options |
promptCache? |
promptCache?: PromptCachePolicy; |
Per-run override for provider prompt caching. |
nativeTools? |
nativeTools?: NativeToolRequest[]; |
Per-run override for provider-hosted tools. |
dataHandling? |
dataHandling?: DataHandlingPolicy; |
- |
continuationToken? |
continuationToken?: string; |
Resume an incomplete provider decode using the token returned by the prior response. |
responseFormat? |
responseFormat?: ResponseFormat; |
Vendor-agnostic structured (JSON) output. When set, the final answer is |
| constrained to JSON — via the vendor's native mechanism where supported, | ||
| otherwise a strict prompt instruction — and parsed into | ||
response.output_parsed. See src/core/StructuredOutput.ts. |
AgentEventListener type
📍 src/core/AgentRegistry.ts:126
Callback type for agent event fan-in
type AgentEventListener = (agentId: string, agentName: string, event: string, data: unknown) => void
AgentRuntimeConfigSnapshot type
Agent runtime options exposed by getRuntimeConfigSnapshot().
type AgentRuntimeConfigSnapshot = Pick<AgentConfig,
| 'temperature'
| 'parameterPolicy'
| 'maxIterations'
| 'thinking'
| 'vendorOptions'
| 'promptCache'
| 'nativeTools'
| 'dataHandling'
| 'toolExecutionTimeout'
| 'historyMode'
| 'limits'
| 'errorHandling'
| 'asyncTools'
| 'emptyResponseRetry'
>
AgentSessionConfig type
Session configuration for Agent (same as BaseSessionConfig)
type AgentSessionConfig = BaseSessionConfig
AgentStatus type
📍 src/core/AgentRegistry.ts:33
Agent lifecycle status from the registry's perspective
type AgentStatus = 'idle' | 'running' | 'paused' | 'cancelled' | 'destroyed'
Vendor type
type Vendor = (typeof Vendor)[keyof typeof Vendor]
createProvider function
📍 src/core/createProvider.ts:89
Create a text provider from a connector
export function createProvider(connector: Connector): ITextProvider
getVendorDefaultBaseURL function
📍 src/core/createProvider.ts:57
Get the default API base URL for a vendor. For OpenAI/Anthropic reads from the installed SDK at runtime. Returns undefined for Custom or unknown vendors.
export function getVendorDefaultBaseURL(vendor: string): string | undefined
isVendor function
Check if a string is a valid vendor
export function isVendor(value: string): value is Vendor