v2.0.0-beta.1Snapshot bebdcd1Markdown ↗

Core

Core

Core classes for authentication, agents, and providers

Agent class

📍 src/core/Agent.ts:468

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

typescript
static create(config: AgentConfig): Agent

Parameters:

  • config: AgentConfig

Returns: Agent

static resume()

Resume an agent from a saved session

typescript
static async resume(
    sessionId: string,
    config: Omit<AgentConfig, 'session'> & { session: NonNullable<AgentConfig['session']> & { storage: IContextStorage } }
  ): Promise<Agent>

Parameters:

  • sessionId: string
  • config: 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.

typescript
static async fromStorage(
    agentId: string,
    storage?: IAgentDefinitionStorage,
    overrides?: Partial<AgentConfig>
  ): Promise<Agent | null>

Parameters:

  • agentId: string
  • storage: 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.

typescript
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: string
  • options: { 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.

typescript
scopedTo(
    allowedToolNames: string[],
    options?: { instructions?: string },
  ): Agent

Parameters:

  • allowedToolNames: string[]
  • options: { instructions?: string | undefined; } | undefined (optional)

Returns: Agent

getAgentType()

typescript
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.

typescript
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.

typescript
async rolloverContext(
    options: AgentContextRolloverOptions = {},
  ): Promise<ContextRolloverResult>

Parameters:

  • options: AgentContextRolloverOptions (optional) (default: {})

Returns: Promise<ContextRolloverResult>

compactContext()

Explicit bounded reduction through the configured composition policy.

typescript
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.

typescript
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.

typescript
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.

typescript
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().

typescript
async executeExternalToolCall(
    call: ExternalToolCall,
    options: { iteration?: number; signal?: AbortSignal } = {},
  ): Promise<ToolResult>

Parameters:

  • call: ExternalToolCall
  • options: { iteration?: number | undefined; signal?: AbortSignal | undefined; } (optional) (default: {})

Returns: Promise<ToolResult>

recordExternalUsage()

Add provider-reported usage to the active external execution.

typescript
recordExternalUsage(usage: Partial<TokenUsage>): void

Parameters:

  • usage: Partial<TokenUsage>

Returns: void

completeExternalExecution()

Complete the active external execution and run normal lifecycle hooks.

typescript
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.

typescript
getLoopDiagnostics(): AgentLoopDiagnostics | undefined

Returns: AgentLoopDiagnostics | undefined

run()

Run the agent with input

typescript
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

typescript
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.

typescript
async continueWithAsyncResults(results?: ToolResult[]): Promise<AgentResponse>

Parameters:

  • results: ToolResult[] | undefined (optional)

Returns: Promise<LLMResponse>

hasPendingAsyncTools()

Check if there are any pending async tools

typescript
hasPendingAsyncTools(includeQueued = false): boolean

Parameters:

  • includeQueued: boolean (optional) (default: false)

Returns: boolean

getPendingAsyncTools()

Get info about pending async tools

typescript
getPendingAsyncTools(): PendingAsyncTool[]

Returns: PendingAsyncTool[]

cancelAsyncTool()

Cancel a specific async tool by toolCallId

typescript
cancelAsyncTool(toolCallId: string): void

Parameters:

  • toolCallId: string

Returns: void

cancelAllAsyncTools()

Cancel all pending async tools

typescript
cancelAllAsyncTools(): void

Returns: void

pause()

Pause execution

typescript
pause(reason?: string): void

Parameters:

  • reason: string | undefined (optional)

Returns: void

resume()

Resume execution

typescript
resume(): void

Returns: void

cancel()

Cancel execution

typescript
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.

typescript
inject(message: string, role: 'user' | 'developer' = 'user'): void

Parameters:

  • message: string
  • role: "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.

typescript
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.

typescript
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.

typescript
inspectCapabilities(): AgentCapabilityInspection

Returns: AgentCapabilityInspection

getInstructionTemplate()

Return the unrendered instruction template supplied at Agent creation.

typescript
getInstructionTemplate(): string | undefined

Returns: string | undefined

getRenderedInstructionTemplate()

Return the creation-time instruction template after static rendering.

typescript
getRenderedInstructionTemplate(): string | undefined

Returns: string | undefined

approveToolForSession()

typescript
approveToolForSession(toolName: string): void

Parameters:

  • toolName: string

Returns: void

revokeToolApproval()

typescript
revokeToolApproval(toolName: string): void

Parameters:

  • toolName: string

Returns: void

getApprovedTools()

typescript
getApprovedTools(): string[]

Returns: string[]

toolNeedsApproval()

typescript
toolNeedsApproval(toolName: string): boolean

Parameters:

  • toolName: string

Returns: boolean

toolIsBlocked()

typescript
toolIsBlocked(toolName: string): boolean

Parameters:

  • toolName: string

Returns: boolean

allowlistTool()

typescript
allowlistTool(toolName: string): void

Parameters:

  • toolName: string

Returns: void

blocklistTool()

typescript
blocklistTool(toolName: string): void

Parameters:

  • toolName: string

Returns: void

setModel()

typescript
setModel(model: string): void

Parameters:

  • model: string

Returns: void

getTemperature()

typescript
getTemperature(): number | undefined

Returns: number | undefined

setTemperature()

typescript
setTemperature(temperature: number): void

Parameters:

  • temperature: number

Returns: void

saveDefinition()

typescript
async saveDefinition(
    storage?: IAgentDefinitionStorage,
    metadata?: AgentDefinitionMetadata
  ): Promise<void>

Parameters:

  • storage: IAgentDefinitionStorage | undefined (optional)
  • metadata: AgentDefinitionMetadata | undefined (optional)

Returns: Promise<void>

getExecutionContext()

typescript
getExecutionContext(): ExecutionContext | null

Returns: ExecutionContext | null

getContext()

Alias for getExecutionContext() for backward compatibility

typescript
getContext(): ExecutionContext | null

Returns: ExecutionContext | null

getMetrics()

typescript
getMetrics()

Returns: ExecutionMetrics | null

getSummary()

typescript
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()

typescript
getAuditTrail()

Returns: readonly AuditEntry[]

getProviderCircuitBreakerMetrics()

typescript
getProviderCircuitBreakerMetrics()

Returns: unknown

getToolCircuitBreakerStates()

typescript
getToolCircuitBreakerStates()

Returns: Map<string, CircuitState>

getToolCircuitBreakerMetrics()

typescript
getToolCircuitBreakerMetrics(toolName: string)

Parameters:

  • toolName: string

Returns: CircuitBreakerMetrics | undefined

resetToolCircuitBreaker()

typescript
resetToolCircuitBreaker(toolName: string): void

Parameters:

  • toolName: string

Returns: void

isRunning()

typescript
isRunning(): boolean

Returns: boolean

isPaused()

typescript
isPaused(): boolean

Returns: boolean

isCancelled()

typescript
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.

typescript
clearConversation(reason?: string): void

Parameters:

  • reason: string | undefined (optional)

Returns: void

registerHook()

Register a hook on the agent. Can be called after creation.

typescript
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.

typescript
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()

typescript
destroy(): void

Returns: void


AgentRegistry class

📍 src/core/AgentRegistry.ts:185

Static Methods

static register()

Register an agent. Called automatically by Agent constructor.

typescript
static register(agent: IRegistrableAgent): void

Parameters:

  • agent: IRegistrableAgent

Returns: void

static unregister()

Unregister an agent. Called automatically by Agent.destroy().

typescript
static unregister(id: string, reason: 'destroyed' | 'manual' = 'destroyed'): void

Parameters:

  • id: string
  • reason: "destroyed" | "manual" (optional) (default: 'destroyed')

Returns: void

static get()

Get agent by registry ID (unique)

typescript
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)

typescript
static getByName(name: string): IRegistrableAgent[]

Parameters:

  • name: string

Returns: IRegistrableAgent[]

static has()

Check if an agent exists in the registry

typescript
static has(id: string): boolean

Parameters:

  • id: string

Returns: boolean

static list()

List all tracked registry IDs

typescript
static list(): string[]

Returns: string[]

static filter()

Return agents matching all provided filter criteria

typescript
static filter(filter: AgentFilter): IRegistrableAgent[]

Parameters:

  • filter: AgentFilter

Returns: IRegistrableAgent[]

static listInfo()

Lightweight info for all agents

typescript
static listInfo(): AgentInfo[]

Returns: AgentInfo[]

static filterInfo()

Lightweight info for agents matching filter

typescript
static filterInfo(filter: AgentFilter): AgentInfo[]

Parameters:

  • filter: AgentFilter

Returns: AgentInfo[]

static inspect()

Deep inspection of a single agent

typescript
static async inspect(id: string): Promise<AgentInspection | null>

Parameters:

  • id: string

Returns: Promise<AgentInspection | null>

static inspectAll()

Deep inspection of all agents

typescript
static async inspectAll(): Promise<AgentInspection[]>

Returns: Promise<AgentInspection[]>

static inspectMatching()

Deep inspection of agents matching filter

typescript
static async inspectMatching(filter: AgentFilter): Promise<AgentInspection[]>

Parameters:

  • filter: AgentFilter

Returns: Promise<AgentInspection[]>

static getStats()

Aggregate counts by status/model/connector

typescript
static getStats(): AgentRegistryStats

Returns: AgentRegistryStats

static getAggregateMetrics()

Aggregate metrics across all agents (tokens, tool calls, errors)

typescript
static getAggregateMetrics(): AggregateMetrics

Returns: AggregateMetrics

static getChildren()

Get child agents of a parent

typescript
static getChildren(parentId: string): IRegistrableAgent[]

Parameters:

  • parentId: string

Returns: IRegistrableAgent[]

static getParent()

Get parent agent of a child

typescript
static getParent(childId: string): IRegistrableAgent | undefined

Parameters:

  • childId: string

Returns: IRegistrableAgent | undefined

static getTree()

Get recursive tree starting from a root agent

typescript
static getTree(rootId: string): AgentTreeNode | null

Parameters:

  • rootId: string

Returns: AgentTreeNode | null

static on()

Subscribe to registry lifecycle events

typescript
static on<K extends keyof AgentRegistryEvents>(
    event: K,
    listener: (data: AgentRegistryEvents[K]) => void,
  ): void

Parameters:

  • event: K
  • listener: (data: AgentRegistryEvents[K]) => void

Returns: void

static off()

Unsubscribe from registry lifecycle events

typescript
static off<K extends keyof AgentRegistryEvents>(
    event: K,
    listener: (data: AgentRegistryEvents[K]) => void,
  ): void

Parameters:

  • event: K
  • listener: (data: AgentRegistryEvents[K]) => void

Returns: void

static once()

Subscribe once to a registry lifecycle event

typescript
static once<K extends keyof AgentRegistryEvents>(
    event: K,
    listener: (data: AgentRegistryEvents[K]) => void,
  ): void

Parameters:

  • event: K
  • listener: (data: AgentRegistryEvents[K]) => void

Returns: void

static onAgentEvent()

Fan-in: receive ALL events from ALL agents through one listener

typescript
static onAgentEvent(listener: AgentEventListener): void

Parameters:

  • listener: AgentEventListener

Returns: void

static offAgentEvent()

Remove a fan-in listener

typescript
static offAgentEvent(listener: AgentEventListener): void

Parameters:

  • listener: AgentEventListener

Returns: void

static pauseAgent()

Pause a specific agent. Returns true if found and paused.

typescript
static pauseAgent(id: string): boolean

Parameters:

  • id: string

Returns: boolean

static resumeAgent()

Resume a specific agent. Returns true if found and resumed.

typescript
static resumeAgent(id: string): boolean

Parameters:

  • id: string

Returns: boolean

static cancelAgent()

Cancel a specific agent. Returns true if found and cancelled.

typescript
static cancelAgent(id: string, reason?: string): boolean

Parameters:

  • id: string
  • reason: string | undefined (optional)

Returns: boolean

static destroyAgent()

Destroy a specific agent. Returns true if found and destroyed.

typescript
static destroyAgent(id: string): boolean

Parameters:

  • id: string

Returns: boolean

static pauseMatching()

Pause all agents matching filter. Returns count paused.

typescript
static pauseMatching(filter: AgentFilter): number

Parameters:

  • filter: AgentFilter

Returns: number

static cancelMatching()

Cancel all agents matching filter. Returns count cancelled.

typescript
static cancelMatching(filter: AgentFilter, reason?: string): number

Parameters:

  • filter: AgentFilter
  • reason: string | undefined (optional)

Returns: number

static destroyMatching()

Destroy all agents matching filter. Returns count destroyed.

typescript
static destroyMatching(filter: AgentFilter): number

Parameters:

  • filter: AgentFilter

Returns: number

static pauseAll()

Pause all agents. Returns count paused.

typescript
static pauseAll(): number

Returns: number

static cancelAll()

Cancel all agents. Returns count cancelled.

typescript
static cancelAll(reason?: string): number

Parameters:

  • reason: string | undefined (optional)

Returns: number

static destroyAll()

Destroy ALL tracked agents. Returns count destroyed.

typescript
static destroyAll(): number

Returns: number

static clear()

Clear registry without destroying agents (for testing)

typescript
static clear(): void

Returns: void


Connector class

📍 src/core/Connector.ts:62

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.

typescript
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).

typescript
static getRegistry(): IConnectorRegistry | null

Returns: IConnectorRegistry | null

static create()

Create and register a new connector

typescript
static create(config: ConnectorConfig & { name: string }): Connector

Parameters:

  • config: ConnectorConfig & { name: string; }

Returns: Connector

static get()

Get a connector by name

typescript
static get(name: string): Connector

Parameters:

  • name: string

Returns: Connector

static has()

Check if a connector exists

typescript
static has(name: string): boolean

Parameters:

  • name: string

Returns: boolean

static list()

List all registered connector names

typescript
static list(): string[]

Returns: string[]

static remove()

Remove a connector

typescript
static remove(name: string): boolean

Parameters:

  • name: string

Returns: boolean

static clear()

Clear all connectors (useful for testing)

typescript
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).

typescript
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.

typescript
static hasInMap(name: string): boolean

Parameters:

  • name: string

Returns: boolean

static listAllFromMap()

List all connector instances from the internal Map, bypassing the custom registry.

typescript
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.

typescript
static async warmup(): Promise<void>

Returns: Promise<void>

static setDefaultStorage()

Set default token storage for OAuth connectors

typescript
static setDefaultStorage(storage: ITokenStorage): void

Parameters:

  • storage: ITokenStorage

Returns: void

static listAll()

Get all registered connectors

typescript
static listAll(): Connector[]

Returns: Connector[]

static size()

Get number of registered connectors

typescript
static size(): number

Returns: number

static getById()

Get a connector by ID

typescript
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.

typescript
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).

typescript
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().

typescript
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.

typescript
static asRegistry(): IConnectorRegistry

Returns: IConnectorRegistry

static getDescriptionsForTools()

Get connector descriptions formatted for tool parameters Useful for generating dynamic tool descriptions

typescript
static getDescriptionsForTools(): string

Returns: string

static getInfo()

Get connector info (for tools and documentation)

typescript
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).

typescript
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)

typescript
getApiKey(): string

Returns: string

getToken()

Get the current access token (for OAuth, JWT, or API key) Handles automatic refresh if needed

typescript
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

typescript
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 {}.

typescript
async handleCallback(callbackUrl: string, userId?: string, accountId?: string): Promise<OAuthCallbackResult>

Parameters:

  • callbackUrl: string
  • userId: string | undefined (optional)
  • accountId: string | undefined (optional)

Returns: Promise<OAuthCallbackResult>

hasValidToken()

Check if the connector has a valid token

typescript
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.

typescript
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.

typescript
async rekeyAccount(userId: string, oldAccountId: string, newAccountId: string): Promise<boolean>

Parameters:

  • userId: string
  • oldAccountId: string
  • newAccountId: 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.

typescript
async removeAccount(userId: string, accountId: string): Promise<boolean>

Parameters:

  • userId: string
  • accountId: string

Returns: Promise<boolean>

getOptions()

Get vendor-specific options from config

typescript
getOptions(): Record<string, unknown>

Returns: Record<string, unknown>

getMetrics()

Get connector metrics

typescript
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)

typescript
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
typescript
async fetch(
    endpoint: string,
    options?: ConnectorFetchOptions,
    userId?: string,
    accountId?: string
  ): Promise<Response>

Parameters:

  • endpoint: string
  • options: 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

typescript
async fetchJSON<T = unknown>(
    endpoint: string,
    options?: ConnectorFetchOptions,
    userId?: string,
    accountId?: string
  ): Promise<T>

Parameters:

  • endpoint: string
  • options: ConnectorFetchOptions | undefined (optional)
  • userId: string | undefined (optional)
  • accountId: string | undefined (optional)

Returns: Promise<T>

dispose()

Dispose of resources

typescript
dispose(): void

Returns: void

isDisposed()

Check if connector is disposed

typescript
isDisposed(): boolean

Returns: boolean

Properties
Property Type Description
id id: string -
name name: string -
vendor? `vendor: Vendor undefined`
config config: ConnectorConfig -

AgentConfig interface

📍 src/core/Agent.ts:111

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

📍 src/core/Agent.ts:251

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

📍 src/core/Agent.ts:260

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&lt;string, never&gt;; -

AgentRegistryStats interface

📍 src/core/AgentRegistry.ts:70

Aggregate statistics across all tracked agents

Properties
Property Type Description
total total: number; -
byStatus byStatus: Record&lt;AgentStatus, number&gt;; -
byModel byModel: Record&lt;string, number&gt;; -
byConnector byConnector: Record&lt;string, number&gt;; -

ConnectorFetchOptions interface

📍 src/core/Connector.ts:46

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

📍 src/core/Agent.ts:285

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

📍 src/core/Agent.ts:300

Terminal data supplied when an external execution is completed.

Properties
Property Type Description
status? status?: AgentResponse['status']; -
outputText? outputText?: string; -
usage? usage?: Partial&lt;TokenUsage&gt;; -
error? error?: Error; -

ExternalToolCall interface

📍 src/core/Agent.ts:293

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

📍 src/core/Agent.ts:214

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&lt;string, unknown&gt;; 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

typescript
type AgentEventListener = (agentId: string, agentName: string, event: string, data: unknown) =&gt; void

AgentRuntimeConfigSnapshot type

📍 src/core/Agent.ts:193

Agent runtime options exposed by getRuntimeConfigSnapshot().

typescript
type AgentRuntimeConfigSnapshot = Pick&lt;AgentConfig,
  | 'temperature'
  | 'parameterPolicy'
  | 'maxIterations'
  | 'thinking'
  | 'vendorOptions'
  | 'promptCache'
  | 'nativeTools'
  | 'dataHandling'
  | 'toolExecutionTimeout'
  | 'historyMode'
  | 'limits'
  | 'errorHandling'
  | 'asyncTools'
  | 'emptyResponseRetry'
&gt;

AgentSessionConfig type

📍 src/core/Agent.ts:104

Session configuration for Agent (same as BaseSessionConfig)

typescript
type AgentSessionConfig = BaseSessionConfig

AgentStatus type

📍 src/core/AgentRegistry.ts:33

Agent lifecycle status from the registry's perspective

typescript
type AgentStatus = 'idle' | 'running' | 'paused' | 'cancelled' | 'destroyed'

Vendor type

📍 src/core/Vendor.ts:22

typescript
type Vendor = (typeof Vendor)[keyof typeof Vendor]

createProvider function

📍 src/core/createProvider.ts:89

Create a text provider from a connector

typescript
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.

typescript
export function getVendorDefaultBaseURL(vendor: string): string | undefined

isVendor function

📍 src/core/Vendor.ts:32

Check if a string is a valid vendor

typescript
export function isVendor(value: string): value is Vendor

Documentation snapshot · 2026-11-02Suggest a correction ↗

Search documentation

Type to search the v2 documentation.