Skip to content

Abstract Class: AIAgent<TBus, TConnector>

Makaio Framework


Makaio Framework / ai-adapters-core / AIAgent

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:112

Abstract base class for AI agents.

Bridges adapter/agent bus subjects to connector sessions.

TBus extends ScopedBus<string> = ScopedBus<string>

The scoped bus type for this adapter

TConnector extends AIAgentConnector<TBus> = AIAgentConnector<TBus>

The connector type this agent wraps

new AIAgent<TBus, TConnector>(config): AIAgent<TBus, TConnector>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:158

Create an AIAgent instance.

Note: Does NOT create the connector yet - call init() after construction.

AIAgentConfig<TBus, TConnector>

Agent configuration

AIAgent<TBus, TConnector>

protected readonly optional availableModels?: object[]

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:151

Available models for context window lookup

contextWindowSize: number

Maximum context window size in tokens.

optional family?: string

Model family name (e.g., ‘opus’, ‘sonnet’, ‘gpt-4o’). Used for alias resolution and UI grouping.

optional friendlyName?: string

Human-readable display name (e.g., ‘Sonnet 4.5’, ‘GPT-4o’).

labId: string

Lab that created this model (e.g., ‘anthropic’, ‘openai’, ‘google’).

optional metadata?: object

Supplementary metadata from rich provider APIs (pricing, capabilities, etc.). Not used for routing or adapter logic — purely informational.

optional capabilities?: object

Provider-scoped capabilities for this model offering.

optional parallelToolCalls?: boolean

Whether multiple tool calls can be issued in a single turn.

optional pdfUpload?: boolean

Whether the provider accepts PDF file uploads.

optional speechToText?: object

Speech-to-text capability descriptor.

modes: (… | …)[]

Supported transcription modes.

metadata.capabilities.speechToText.vocabularyBiasing?
Section titled “metadata.capabilities.speechToText.vocabularyBiasing?”

optional vocabularyBiasing?: boolean

Whether the model supports vocabulary/terminology biasing. Optional by design because model metadata can be partial, unlike provider runtime capabilities.

optional structuredOutput?: boolean

Whether the provider supports structured (JSON schema) output.

optional textToSpeech?: object

Text-to-speech capability descriptor.

modes: (… | …)[]

Supported synthesis modes.

metadata.capabilities.textToSpeech.outputFormats?
Section titled “metadata.capabilities.textToSpeech.outputFormats?”

optional outputFormats?: …[]

Supported output audio formats. Optional because metadata may omit it.

metadata.capabilities.textToSpeech.voiceInstructions?
Section titled “metadata.capabilities.textToSpeech.voiceInstructions?”

optional voiceInstructions?: boolean

Whether the model supports style/tone instructions (e.g., gpt-4o-mini-tts). Optional because metadata may omit it.

metadata.capabilities.textToSpeech.voiceSelection?
Section titled “metadata.capabilities.textToSpeech.voiceSelection?”

optional voiceSelection?: boolean

Whether the user can select a voice preset. Optional because model metadata may omit it.

optional toolCalling?: boolean

Whether the provider’s API supports tool/function calling.

optional vision?: boolean

Whether the model accepts image inputs.

optional description?: string

Optional description of the model *

optional includedInSubscription?: boolean

Whether this model is included in the provider’s subscription plan.

optional maxOutputTokens?: number

Maximum output tokens the provider allows for this model.

optional pricing?: object

Token pricing for this model offering.

optional request?: object

Per-request pricing (GitHub Copilot premium requests, etc.).

multiplier: number

Cost per request in provider billing units (0 = free).

optional token?: object

Per-token pricing (Anthropic direct, OpenAI direct, etc.).

metadata.pricing.token.cacheWritePerMillion?
Section titled “metadata.pricing.token.cacheWritePerMillion?”

optional cacheWritePerMillion?: number

Cost per million cache-write input tokens (USD).

metadata.pricing.token.inputCachedPerMillion?
Section titled “metadata.pricing.token.inputCachedPerMillion?”

optional inputCachedPerMillion?: number

Cost per million cache-read input tokens (USD).

inputPerMillion: number

Cost per million input tokens (USD).

outputPerMillion: number

Cost per million output tokens (USD).

name: string

Model identifier used by the provider (e.g., ‘claude-sonnet-4-6’, ‘gpt-4o’, ‘gemini-2.5-pro’).

optional supportedReasoningLevels?: object

Maps supported reasoning levels to provider-native values. When omitted, the model does not support extended thinking / reasoning.

optional extra-high?: string | number = reasoningLevelValue

optional high?: string | number = reasoningLevelValue

optional low?: string | number = reasoningLevelValue

optional medium?: string | number = reasoningLevelValue

optional none?: string | number = reasoningLevelValue


protected readonly config: object

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:149

Normalized config with defaults applied

adapterBus: TBus

Scoped bus for adapter-specific events

adapterId: string

Adapter instance identifier

adapterName: string

Adapter type name (e.g., ‘claude-code’, ‘gemini-sdk’)

optional adapterSessionId?: string

Adapter-specific session identifier for multi-turn conversations

agentId: string

Unique agent identifier

optional allowedDirectories?: string[]

Directory restrictions for file-system tool execution.

optional allowedTools?: string[]

Allowed tool names (adapter-specific). Empty array = disable all tools.

optional availableModels?: object[]

Available models for this adapter (used for context window lookup)

capabilities: string[]

Adapter capabilities (e.g., [‘streaming’, ‘tools’, ‘vision’])

optional clientId?: string

Client identifier for the application this adapter belongs to (e.g., ‘claude-code’, ‘gemini’).

configFactory: (input) => Promise<BaseAgentConnectorConfig<TBus, object> & object>

Config factory - transforms partial input into full adapter-specific config. This is the seam where adapters inject their defaults (especially model).

ConfigFactoryInput<TBus>

Promise<BaseAgentConnectorConfig<TBus, object> & object>

connectorFactory: (config) => TConnector | Promise<TConnector>

Connector factory - creates connector from full config. Called AFTER configFactory returns the complete configuration. Config includes adapterId (passed through from input by config factory).

BaseAgentConnectorConfig<TBus, object> & object

TConnector | Promise<TConnector>

optional cwd?: string

Working directory for agent execution (optional - platform provides default)

optional disallowedTools?: string[]

Disallowed tool names (adapter-specific). Takes precedence over allowedTools.

optional env?: Record<string, string>

Environment variables to pass to agent execution

optional ephemeral?: boolean

When true, PreUserMessage hooks are skipped for this agent. Use for ephemeral ping agents where session enrichment and context injection are not needed and would be actively harmful.

globalBus: IMakaioBus

Global bus instance (defaults to MakaioBus singleton)

optional harnessId?: string

Resolved harness ID for tool policy lookup.

optional mcpSessionContext?: LedgerSessionContext

MCP session context resolved by the orchestrator. Passed through to the connector config so adapters can inject direct tools.

optional model?: string

Model to use (optional - adapter provides default)

nativeTools: string[]

Native tools built into the adapter (e.g., [‘shell_command’, ‘apply_patch’])

optional providerContext?: object

Unresolved provider context (credential refs, not plaintext). Set by the orchestrator before forwarding the startAgent request. Connectors resolve credentials locally via resolveConnectorCredentials().

optional credentialEnvVars?: Record<string, string>

Maps credential keys to environment variable names for subprocess adapters. E.g., { apiKey: 'ANTHROPIC_API_KEY' }.

credentialRefs: Record<string, string & $brand<"CredentialRef">>

Credential references resolved at the connector layer, not on the bus.

definitionId: string

Provider definition ID (e.g., 'anthropic', 'alibaba').

optional endpointOverrides?: object

Endpoint URL overrides keyed by protocol.

providerContext.endpointOverrides.anthropic?
Section titled “providerContext.endpointOverrides.anthropic?”

optional anthropic?: string

optional openai?: string

providerConfigId: string

Provider config UUID. Links back to the ProviderConfig that produced this context.

optional reasoningEffort?: "none" | "low" | "medium" | "high" | "extra-high"

Reasoning effort for supporting adapters

optional resumeAdapterSessionId?: string

Previous adapter session ID for resume attempts (from recovery).

optional sessionId?: string

Makaio session identifier

optional toolLedger?: ISessionToolLedger

Session-scoped ledger tracking MCP injection/discovery/call history. Created once per agent session and passed through unchanged on connector swaps.


protected optional confirmedModel?: string

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:118


protected connector: TConnector

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:117

The underlying connector instance (created in init)


protected optional initialModel?: string

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:119


protected readonly lifecycleTracker: MessageLifecycleTracker

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:131

Tracks message lifecycle and emits turn events.


protected readonly toolCallTracker: ToolCallTracker

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:133

Tracks tool.use → tool.output correlation across adapters.

get adapterId(): string

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:269

string

Adapter instance identifier


get adapterName(): string

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:273

string

Adapter type name (e.g., ‘claude-code’, ‘gemini-sdk’)


get protected adapterSessionId(): string | undefined

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:289

string | undefined

Initial adapter session ID from config (may differ from connector’s resolved session ID)


get agentId(): string

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:265

string

Unique agent identifier


get capabilities(): string[]

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:277

string[]

Adapter capabilities for runtime feature detection


get protected globalBus(): IMakaioBus

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:293

IMakaioBus

Global bus for cross-namespace communication (defaulted in constructor)


get nativeTools(): string[]

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:281

string[]

Native tools built into the adapter


get sessionId(): string | undefined

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:285

string | undefined

Shared Makaio sessionId

abort(): void

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:906

Abort the agent immediately (panic mode). Triggers AbortController which may cause provider errors. Use close() for graceful shutdown instead.

Emits session.closed event (once per session) then delegates to the underlying connector’s abort method.

void

Error if connector is not initialized


protected addBusHandlerCleanup(cleanup): void

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:583

Registers a cleanup function for a global bus subscription. These survive connector swaps and are cleaned up in close().

() => void

Function to unsubscribe from the bus

void


protected addConnectorWiringCleanup(cleanup): void

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:574

Register a cleanup function for connector wiring. These cleanups are cleared on connector swap but preserved across bus handler changes.

() => void

Cleanup function to register

void


close(options?): Promise<void>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:768

Clean up resources and emit session closed event.

Emits session.closed event (once per session) unless explicitly suppressed, then unsubscribes from all bus handlers and aborts the connector if available.

Cleanup options; ephemeral agents suppress session-close lifecycle events because they never join a session.

boolean

Promise<void>


complete(): Promise<MessageResult | null>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:929

Complete the agent session by waiting for all messages to finish.

Delegates to the underlying connector’s complete method.

Promise<MessageResult | null>

Last message result or null if no messages processed

Error if connector is not initialized


protected createConnectorEventMapping<TSourceSubject, TNestedMessageProp, TMessage, TDiscriminator>(sourceSubject, discriminator, handlers, nestedMessageProp?): () => void

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:941

Creates a type-safe event mapping from connector events to scoped subjects or handlers.

TSourceSubject extends ScopedSubjectDefinition<TConnector extends AIAgentConnector<TBus, BaseAgentConnectorConfig<TBus, object>> ? TBus["namespace"] : never>

TNestedMessageProp extends string | number | symbol | undefined = undefined

TMessage = TNestedMessageProp extends keyof TSourceSubject["$meta"]["payload"] ? TSourceSubject["$meta"]["payload"][TNestedMessageProp] : TSourceSubject["$meta"]["payload"]

TDiscriminator extends string = DiscriminatorKeys<TMessage>

TSourceSubject

The connector subject to subscribe to

TDiscriminator

The discriminator key within the message (e.g., ‘type’)

ConnectorEventHandlers<TMessage, TDiscriminator>

Map of discriminator values to target subjects or handler functions

TNestedMessageProp

Property containing the discriminated union (e.g., ‘msg’), or undefined for top-level

Unsubscribe function for the connector event mapping subscription

() => void


protected emitCompletion(result): Promise<void>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:389

Omit<z.infer<typeof AgentSchemas.complete>, keyof AgentContext>

Promise<void>


protected emitContextWindowUpdate(input): Promise<void>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:468

Emit context window status for compression trigger decisions.

Calculates fill percentage and warning level from raw metrics. Called by subclasses after usage tracking with provider-specific metrics.

ContextWindowInput

Raw metrics: currentTokens, maxTokens, optional cachedTokens

Promise<void>


protected emitError(result): void

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:403

Stash error metadata for the next emitCompletion call.

The lifecycle tracker emits agent.complete with outcome: 'error' when the message handle completes. This method runs first (from the connector’s errorHandler) and stashes errorCategory so emitCompletion can include it in the complete payload.

No longer emits agent.error — all terminal events flow through agent.complete.

Pick<z.infer<typeof AgentSchemas.complete>, "error" | "errorCategory">

Error payload from the connector

void


protected emitGlobal<S>(subject, payload): Promise<void>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:430

Emit to a global subject with automatic payload enrichment.

S extends SubjectDefinition

S

The subject to emit to

Omit<ExtractSubjectPayload<S>, keyof AgentIdentity> & object

The payload (without AgentContext fields - they’re added automatically)

Promise<void>


protected emitSessionClosed(reason?): void

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:412

Emit agent session closed event. Emits only once per session. AIAdapter listens to cleanup agent and re-emit as AdapterSubjects.session.closed.

string

Reason for session closure (e.g., ‘aborted’, ‘closed’)

void


protected emitStart(event?): Promise<void>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:378

Omit<{ adapterId: string; adapterName: string; adapterSessionId: string; agentId: string; clientId?: string; cwd: string | null; messageId?: string; model: string | null; occurredAt?: number; providerConfigId?: string; sessionId?: string; turnId?: string; }, "model" | "cwd" | "adapterName" | "adapterId" | "agentId" | "adapterSessionId">

Promise<void>


protected emitStepFinished(stepType, content): Promise<void>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:517

Emit step.finished event with content and increment block index. Call this when a content block completes processing.

"text" | "reasoning" | "tool_use"

The type of step that finished

{ content: string; type: "text"; } | { source: { data: string; mimeType: string; type: "base64"; } | { mimeType?: string; type: "url"; url: string; }; type: "image"; } | { source: { data: string; mimeType: string; type: "base64"; } | { mimeType?: string; type: "url"; url: string; }; type: "document"; } | { attachmentType: "file" | "directory"; displayName?: string; fileName: string; filePath: string; source: { data: string; mimeType: string; type: "base64"; } | { mimeType?: string; type: "url"; url: string; }; type: "attachment"; } | { content: string; metadata?: Record<string, unknown>; type: "reasoning"; } | { args: Record<string, unknown>; name: string; toolCallId: string; type: "tool_call"; } | { isError?: boolean; output: string; toolCallId: string; type: "tool_output"; }

The complete content of the step (text, reasoning, tool_call, or tool_output)

{ attachmentType: "file" | "directory"; displayName?: string; fileName: string; filePath: string; source: { data: string; mimeType: string; type: "base64"; } | { mimeType?: string; type: "url"; url: string; }; type: "attachment"; }

The complete content of the step (text, reasoning, tool_call, or tool_output)

"file" | "directory" = AttachmentTypeSchema

Whether the attachment is a file or directory

string = ...

Optional human-readable display name override

string = ...

Original filename with extension (e.g. “api-spec.yaml”) — for display and type inference

string = ...

Server-side file path — always populated before message reaches adapters

{ data: string; mimeType: string; type: "base64"; } | { mimeType?: string; type: "url"; url: string; } = ContentSourceSchema

Inline content — base64 for binary, raw string for text

"attachment" = ...


{ content: string; metadata?: Record<string, unknown>; type: "reasoning"; }

The complete content of the step (text, reasoning, tool_call, or tool_output)

string = ...

Record<string, unknown> = ...

Optional provider/runtime metadata for reasoning blocks.

"reasoning" = ...

Promise<void>


protected emitStepStarted(stepType, blockData?, content?): Promise<void>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:503

Emit step.started event with automatic block index management. Call this when a content block begins processing.

"text" | "reasoning" | "tool_use"

The type of step (text, reasoning, tool_use)

{ toolCallId: string; toolName: string; type: "tool_use"; } | { type: "reasoning"; } | { type: "text"; }

Optional metadata for the block (e.g., toolName for tool_use)

{ content: string; type: "text"; } | { source: { data: string; mimeType: string; type: "base64"; } | { mimeType?: string; type: "url"; url: string; }; type: "image"; } | { source: { data: string; mimeType: string; type: "base64"; } | { mimeType?: string; type: "url"; url: string; }; type: "document"; } | { attachmentType: "file" | "directory"; displayName?: string; fileName: string; filePath: string; source: { data: string; mimeType: string; type: "base64"; } | { mimeType?: string; type: "url"; url: string; }; type: "attachment"; } | { content: string; metadata?: Record<string, unknown>; type: "reasoning"; } | { args: Record<string, unknown>; name: string; toolCallId: string; type: "tool_call"; } | { isError?: boolean; output: string; toolCallId: string; type: "tool_output"; }

Optional content for the step (e.g., tool_call block for tool_use)

{ attachmentType: "file" | "directory"; displayName?: string; fileName: string; filePath: string; source: { data: string; mimeType: string; type: "base64"; } | { mimeType?: string; type: "url"; url: string; }; type: "attachment"; }

Optional content for the step (e.g., tool_call block for tool_use)

"file" | "directory" = AttachmentTypeSchema

Whether the attachment is a file or directory

string = ...

Optional human-readable display name override

string = ...

Original filename with extension (e.g. “api-spec.yaml”) — for display and type inference

string = ...

Server-side file path — always populated before message reaches adapters

{ data: string; mimeType: string; type: "base64"; } | { mimeType?: string; type: "url"; url: string; } = ContentSourceSchema

Inline content — base64 for binary, raw string for text

"attachment" = ...


{ content: string; metadata?: Record<string, unknown>; type: "reasoning"; }

Optional content for the step (e.g., tool_call block for tool_use)

string = ...

Record<string, unknown> = ...

Optional provider/runtime metadata for reasoning blocks.

"reasoning" = ...

Promise<void>


protected emitToolOutput(output, hints): Promise<ToolOutputResolution>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:492

Emit tool.output event with automatic correlation resolution. Resolves the correlation ID from ToolCallTracker using provided hints. Use this instead of directly emitting to AgentSubjects.tool.output.

string

Tool output content

ResolveHints

Hints for correlation (nativeId and/or toolName)

Promise<ToolOutputResolution>

Resolved toolCallId, toolName (falls back to ‘unknown’), and args from the matched tool.use call


protected emitToolUse(toolName, args?, nativeId?): Promise<string>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:481

Emit tool.use event with automatic correlation tracking. Registers the tool call with ToolCallTracker and emits to global bus. Use this instead of directly emitting to AgentSubjects.tool.use.

string

Name of the tool being invoked

Record<string, unknown>

Tool arguments

string

Native provider ID if available (e.g., toolu_, call_)

Promise<string>

The correlation ID used (nativeId if provided, else generated UUID)


protected enrichPayload<T>(payload): Promise<T & Required<AgentIdentity> & object>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:421

Enrich a payload with agent context fields.

T extends object

T

The base payload to enrich

Promise<T & Required<AgentIdentity> & object>

Payload with AgentContext fields and optional messageId added


getAdapterSessionId(): Promise<string>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:918

Get session ID, waiting for provider to generate it if not yet available.

Delegates to the underlying connector’s getSessionId method.

Promise<string>

Session ID from provider

Error if connector is not initialized


protected getBlockIndex(): number

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:525

Get the current block index (for adapters that need to track it externally).

number

Current block index within the turn


protected getContextWindowSize(modelName?): number | undefined

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:453

Get context window size for a model.

Looks up the context window size from availableModels based on model name.

string

Model name to look up (defaults to confirmedModel or initialModel)

number | undefined

Context window size in tokens, or undefined if not found


protected incrementBlockIndex(): void

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:533

Increment block index (for adapters using SDK-provided indices). Call after emitting step.finished if managing index externally.

void


init(): Promise<void>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:304

Initialize the agent.

Creates the connector via the abstract createConnector() method and sets up handlers for agent.* subjects with agentId filtering.

Promise<void>

Error if already initialized


initialize(options?): Promise<void>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:865

Initialize the agent without sending a message (idle creation). Ensures init() is called, then delegates to connector.initialize().

AgentSendMessageOptions

Optional initialization options (system prompt, sessionContext)

Promise<void>


protected onBeforeEmitCompletion(): Promise<void>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:880

Promise<void>


protected onMessageHandle(messageHandle): Promise<void>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:882

MessageHandle

Promise<void>


protected sendMessage(ctx): Promise<void>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:547

Handle agent.sendMessage request. The filter has already been applied at subscription time - this method only receives messages intended for this agent. Runs PreUserMessage hooks before delegating to the connector’s sendMessage method. Uses sessionContext signals to decide between native resume and fresh with history. HookAbortError propagates to caller (session layer handles lifecycle). Subclasses can override for custom handling.

RequestContext<{ adapterId: string; agentId: string; deliveryMode?: "enqueue" | "immediate"; message: string | { blocks: { content: string; type: "text"; } | { source: { data: string; mimeType: string; type: "base64"; } | { mimeType?: string; type: "url"; url: string; }; type: "image"; } | { source: { data: string; mimeType: string; type: "base64"; } | { mimeType?: string; type: "url"; url: string; }; type: "document"; } | { attachmentType: "file" | "directory"; displayName?: string; fileName: string; filePath: string; source: { data: string; mimeType: string; type: "base64"; } | { mimeType?: string; type: "url"; url: string; }; type: "attachment"; } | { content: string; metadata?: Record<string, unknown>; type: "reasoning"; } | { args: Record<string, unknown>; name: string; toolCallId: string; type: "tool_call"; } | { isError?: boolean; output: string; toolCallId: string; type: "tool_output"; } | ({ content: string; type: "text"; } | { source: { data: string; mimeType: string; type: "base64"; } | { mimeType?: … | …; type: "url"; url: string; }; type: "image"; } | { source: { data: string; mimeType: string; type: "base64"; } | { mimeType?: … | …; type: "url"; url: string; }; type: "document"; } | { attachmentType: "file" | "directory"; displayName?: string; fileName: string; filePath: string; source: { data: string; mimeType: string; type: "base64"; } | { mimeType?: … | …; type: "url"; url: string; }; type: "attachment"; } | { content: string; metadata?: Record<string, unknown>; type: "reasoning"; } | { args: Record<string, unknown>; name: string; toolCallId: string; type: "tool_call"; } | { isError?: boolean; output: string; toolCallId: string; type: "tool_output"; })[]; role?: "user" | "assistant" | "system"; }; messageId?: string; responseSchema?: Record<string, unknown>; sessionContext?: { extractedContext?: unknown; hasCompression?: boolean; hasConnectorSwap?: boolean; hasNewTransforms?: boolean; isFirstTurn?: boolean; messageHistory?: object[]; turnContext?: Record<string, unknown>; }; sessionId?: string; turnId?: string; }, { messageId: string; }>

Request context with payload and response methods

Promise<void>


protected shouldUseNativeResume(sessionContext?): boolean

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:809

Determine whether to use native session resume or fresh with history.

Native resume: SDK manages history, don’t inject messageHistory, preserve cache. Fresh with history: Create new session, inject messageHistory.

Override in adapter-specific agents if needed.

Context signals from SessionOrchestrator

unknown = ...

Structured context from compression (if hasCompression=true).

boolean = ...

Whether compression is active (extractedContext present). If true, Agent should use fresh mode with compressed context.

boolean = ...

Whether a connector swap occurred before this message (e.g., cwd/model change). If true, native resume is infeasible and adapters should use fresh mode.

boolean = ...

Whether transforms have been applied since last turn. If true, Agent should use fresh mode (history changed).

boolean = ...

Whether this is the first turn in the session. If true, no native history exists yet.

object[] = ...

Curated message history assembled via getFullConversation(). Only used if Agent decides to inject (fresh mode).

Record<string, JsonValue> = ...

Turn-scoped context assembled by PreUserMessage hooks and the orchestrator. Keys are plugin-defined (e.g., ‘skillCatalog’, ‘skills’, ‘predictedTools’). Adapters consume this to prepend context blocks.

Constrained to JSON-safe types to ensure serialization succeeds.

ADAPTER CONTRACT: Every adapter MUST materialize turnContext into the LLM-facing message using serializeTurnContext().

boolean

true if native resume should be used


start(message, options?): Promise<AgentStartResult>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:841

Start the agent with an initial message.

Ensures the agent is initialized (idempotent) before delegating to the connector. Runs PreUserMessage hooks before sending the message. Uses sessionContext signals to decide between native resume and fresh with history. HookAbortError propagates to caller.

string | { blocks: { content: string; type: "text"; } | { source: { data: string; mimeType: string; type: "base64"; } | { mimeType?: string; type: "url"; url: string; }; type: "image"; } | { source: { data: string; mimeType: string; type: "base64"; } | { mimeType?: string; type: "url"; url: string; }; type: "document"; } | { attachmentType: "file" | "directory"; displayName?: string; fileName: string; filePath: string; source: { data: string; mimeType: string; type: "base64"; } | { mimeType?: string; type: "url"; url: string; }; type: "attachment"; } | { content: string; metadata?: Record<string, unknown>; type: "reasoning"; } | { args: Record<string, unknown>; name: string; toolCallId: string; type: "tool_call"; } | { isError?: boolean; output: string; toolCallId: string; type: "tool_output"; } | ({ content: string; type: "text"; } | { source: { data: string; mimeType: string; type: "base64"; } | { mimeType?: string; type: "url"; url: string; }; type: "image"; } | { source: { data: string; mimeType: string; type: "base64"; } | { mimeType?: string; type: "url"; url: string; }; type: "document"; } | { attachmentType: "file" | "directory"; displayName?: string; fileName: string; filePath: string; source: { data: string; mimeType: string; type: "base64"; } | { mimeType?: string; type: "url"; url: string; }; type: "attachment"; } | { content: string; metadata?: Record<string, unknown>; type: "reasoning"; } | { args: Record<string, unknown>; name: string; toolCallId: string; type: "tool_call"; } | { isError?: boolean; output: string; toolCallId: string; type: "tool_output"; })[]; role?: "user" | "assistant" | "system"; } | NormalizedMessageInput

User message (normalized or unnormalized)

AgentSendMessageOptions

Optional start options (e.g., delivery mode, sessionContext)

Promise<AgentStartResult>

Session ID, agent ID, and message handle for tracking


protected subscribeConnector<Subject>(connector, subject, handler, options?): void

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:752

Subscribe to a connector subject and register its cleanup as connector wiring.

Use this in adapter wireEvents() implementations so connector swaps can remove old listeners before rewiring the new connector.

Subject extends ScopedSubjectDefinition<TConnector extends AIAgentConnector<TBus, BaseAgentConnectorConfig<TBus, object>> ? TBus["namespace"] : never>

TConnector

Connector instance to subscribe on

Subject

Subject definition to subscribe to

HandlerForSubjectDefinition<Subject>

Subject handler

OnOptions

Optional bus subscription options

void


protected supportsNativeResume(): boolean

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:826

Whether this adapter supports native session resume. Override in adapter-specific agents that can resume SDK sessions.

boolean

true if native resume is supported


swapConnector(configOverrides?): Promise<void>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:603

Replace the current connector with a fresh one.

Uses create-before-close pattern with rollback for safety:

  1. Create new connector first (old connector still alive)
  2. Wire events to new connector (accumulate cleanups separately)
  3. If successful: close old connector, assign new one
  4. If failed: close new connector, restore old wiring, throw

This ensures the agent always has a working connector, even if factory or wiring fails.

Preserves runtime overrides across sequential swaps by using current connector values as baseline for non-overridden fields.

Partial<{ cwd: string; model: string; providerContext: { credentialEnvVars?: Record<string, string>; credentialRefs: Record<string, string & $brand<"CredentialRef">>; definitionId: string; endpointOverrides?: { anthropic?: string; openai?: string; }; providerConfigId: string; }; }>

Optional config overrides (e.g., new cwd, model)

Promise<void>

Error if connector is currently processing a turn


protected trackUsage(normalized): Promise<void>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:442

Track usage and emit to global bus. AIAdapter aggregates session totals from per-call usage events.

NormalizedCallUsage

Normalized usage metrics from adapter-specific normalizer

Promise<void>


abstract protected wireEvents(connector): void | Promise<void>

Defined in: ../../../adapters/core/src/agent/ai-agent.ts:740

Wire adapter-specific connector events. Called automatically during init() and connector swap. Subclasses implement this to set up their event mappings.

TConnector

Connector instance to wire

void | Promise<void>