Abstract Class: AIAgent<TBus, TConnector>
Makaio Framework / ai-adapters-core / AIAgent
Abstract Class: AIAgent<TBus, TConnector>
Section titled “Abstract Class: AIAgent<TBus, TConnector>”Defined in: ../../../adapters/core/src/agent/ai-agent.ts:112
Abstract base class for AI agents.
Bridges adapter/agent bus subjects to connector sessions.
Type Parameters
Section titled “Type Parameters”TBus extends ScopedBus<string> = ScopedBus<string>
The scoped bus type for this adapter
TConnector
Section titled “TConnector”TConnector extends AIAgentConnector<TBus> = AIAgentConnector<TBus>
The connector type this agent wraps
Constructors
Section titled “Constructors”Constructor
Section titled “Constructor”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.
Parameters
Section titled “Parameters”config
Section titled “config”AIAgentConfig<TBus, TConnector>
Agent configuration
Returns
Section titled “Returns”AIAgent<TBus, TConnector>
Properties
Section titled “Properties”availableModels?
Section titled “availableModels?”
protectedreadonlyoptionalavailableModels?:object[]
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:151
Available models for context window lookup
contextWindowSize
Section titled “contextWindowSize”contextWindowSize:
number
Maximum context window size in tokens.
family?
Section titled “family?”
optionalfamily?:string
Model family name (e.g., ‘opus’, ‘sonnet’, ‘gpt-4o’). Used for alias resolution and UI grouping.
friendlyName?
Section titled “friendlyName?”
optionalfriendlyName?:string
Human-readable display name (e.g., ‘Sonnet 4.5’, ‘GPT-4o’).
labId:
string
Lab that created this model (e.g., ‘anthropic’, ‘openai’, ‘google’).
metadata?
Section titled “metadata?”
optionalmetadata?:object
Supplementary metadata from rich provider APIs (pricing, capabilities, etc.). Not used for routing or adapter logic — purely informational.
metadata.capabilities?
Section titled “metadata.capabilities?”
optionalcapabilities?:object
Provider-scoped capabilities for this model offering.
metadata.capabilities.parallelToolCalls?
Section titled “metadata.capabilities.parallelToolCalls?”
optionalparallelToolCalls?:boolean
Whether multiple tool calls can be issued in a single turn.
metadata.capabilities.pdfUpload?
Section titled “metadata.capabilities.pdfUpload?”
optionalpdfUpload?:boolean
Whether the provider accepts PDF file uploads.
metadata.capabilities.speechToText?
Section titled “metadata.capabilities.speechToText?”
optionalspeechToText?:object
Speech-to-text capability descriptor.
metadata.capabilities.speechToText.modes
Section titled “metadata.capabilities.speechToText.modes”modes: (… | …)[]
Supported transcription modes.
metadata.capabilities.speechToText.vocabularyBiasing?
Section titled “metadata.capabilities.speechToText.vocabularyBiasing?”
optionalvocabularyBiasing?:boolean
Whether the model supports vocabulary/terminology biasing. Optional by design because model metadata can be partial, unlike provider runtime capabilities.
metadata.capabilities.structuredOutput?
Section titled “metadata.capabilities.structuredOutput?”
optionalstructuredOutput?:boolean
Whether the provider supports structured (JSON schema) output.
metadata.capabilities.textToSpeech?
Section titled “metadata.capabilities.textToSpeech?”
optionaltextToSpeech?:object
Text-to-speech capability descriptor.
metadata.capabilities.textToSpeech.modes
Section titled “metadata.capabilities.textToSpeech.modes”modes: (… | …)[]
Supported synthesis modes.
metadata.capabilities.textToSpeech.outputFormats?
Section titled “metadata.capabilities.textToSpeech.outputFormats?”
optionaloutputFormats?: …[]
Supported output audio formats. Optional because metadata may omit it.
metadata.capabilities.textToSpeech.voiceInstructions?
Section titled “metadata.capabilities.textToSpeech.voiceInstructions?”
optionalvoiceInstructions?: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?”
optionalvoiceSelection?:boolean
Whether the user can select a voice preset. Optional because model metadata may omit it.
metadata.capabilities.toolCalling?
Section titled “metadata.capabilities.toolCalling?”
optionaltoolCalling?:boolean
Whether the provider’s API supports tool/function calling.
metadata.capabilities.vision?
Section titled “metadata.capabilities.vision?”
optionalvision?:boolean
Whether the model accepts image inputs.
metadata.description?
Section titled “metadata.description?”
optionaldescription?:string
Optional description of the model *
metadata.includedInSubscription?
Section titled “metadata.includedInSubscription?”
optionalincludedInSubscription?:boolean
Whether this model is included in the provider’s subscription plan.
metadata.maxOutputTokens?
Section titled “metadata.maxOutputTokens?”
optionalmaxOutputTokens?:number
Maximum output tokens the provider allows for this model.
metadata.pricing?
Section titled “metadata.pricing?”
optionalpricing?:object
Token pricing for this model offering.
metadata.pricing.request?
Section titled “metadata.pricing.request?”
optionalrequest?:object
Per-request pricing (GitHub Copilot premium requests, etc.).
metadata.pricing.request.multiplier
Section titled “metadata.pricing.request.multiplier”multiplier:
number
Cost per request in provider billing units (0 = free).
metadata.pricing.token?
Section titled “metadata.pricing.token?”
optionaltoken?:object
Per-token pricing (Anthropic direct, OpenAI direct, etc.).
metadata.pricing.token.cacheWritePerMillion?
Section titled “metadata.pricing.token.cacheWritePerMillion?”
optionalcacheWritePerMillion?:number
Cost per million cache-write input tokens (USD).
metadata.pricing.token.inputCachedPerMillion?
Section titled “metadata.pricing.token.inputCachedPerMillion?”
optionalinputCachedPerMillion?:number
Cost per million cache-read input tokens (USD).
metadata.pricing.token.inputPerMillion
Section titled “metadata.pricing.token.inputPerMillion”inputPerMillion:
number
Cost per million input tokens (USD).
metadata.pricing.token.outputPerMillion
Section titled “metadata.pricing.token.outputPerMillion”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’).
supportedReasoningLevels?
Section titled “supportedReasoningLevels?”
optionalsupportedReasoningLevels?:object
Maps supported reasoning levels to provider-native values. When omitted, the model does not support extended thinking / reasoning.
supportedReasoningLevels.extra-high?
Section titled “supportedReasoningLevels.extra-high?”
optionalextra-high?:string|number=reasoningLevelValue
supportedReasoningLevels.high?
Section titled “supportedReasoningLevels.high?”
optionalhigh?:string|number=reasoningLevelValue
supportedReasoningLevels.low?
Section titled “supportedReasoningLevels.low?”
optionallow?:string|number=reasoningLevelValue
supportedReasoningLevels.medium?
Section titled “supportedReasoningLevels.medium?”
optionalmedium?:string|number=reasoningLevelValue
supportedReasoningLevels.none?
Section titled “supportedReasoningLevels.none?”
optionalnone?:string|number=reasoningLevelValue
config
Section titled “config”
protectedreadonlyconfig:object
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:149
Normalized config with defaults applied
adapterBus
Section titled “adapterBus”adapterBus:
TBus
Scoped bus for adapter-specific events
adapterId
Section titled “adapterId”adapterId:
string
Adapter instance identifier
adapterName
Section titled “adapterName”adapterName:
string
Adapter type name (e.g., ‘claude-code’, ‘gemini-sdk’)
adapterSessionId?
Section titled “adapterSessionId?”
optionaladapterSessionId?:string
Adapter-specific session identifier for multi-turn conversations
agentId
Section titled “agentId”agentId:
string
Unique agent identifier
allowedDirectories?
Section titled “allowedDirectories?”
optionalallowedDirectories?:string[]
Directory restrictions for file-system tool execution.
allowedTools?
Section titled “allowedTools?”
optionalallowedTools?:string[]
Allowed tool names (adapter-specific). Empty array = disable all tools.
availableModels?
Section titled “availableModels?”
optionalavailableModels?:object[]
Available models for this adapter (used for context window lookup)
capabilities
Section titled “capabilities”capabilities:
string[]
Adapter capabilities (e.g., [‘streaming’, ‘tools’, ‘vision’])
clientId?
Section titled “clientId?”
optionalclientId?:string
Client identifier for the application this adapter belongs to (e.g., ‘claude-code’, ‘gemini’).
configFactory
Section titled “configFactory”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).
Parameters
Section titled “Parameters”ConfigFactoryInput<TBus>
Returns
Section titled “Returns”Promise<BaseAgentConnectorConfig<TBus, object> & object>
connectorFactory
Section titled “connectorFactory”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).
Parameters
Section titled “Parameters”config
Section titled “config”BaseAgentConnectorConfig<TBus, object> & object
Returns
Section titled “Returns”TConnector | Promise<TConnector>
optionalcwd?:string
Working directory for agent execution (optional - platform provides default)
disallowedTools?
Section titled “disallowedTools?”
optionaldisallowedTools?:string[]
Disallowed tool names (adapter-specific). Takes precedence over allowedTools.
optionalenv?:Record<string,string>
Environment variables to pass to agent execution
ephemeral?
Section titled “ephemeral?”
optionalephemeral?: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
Section titled “globalBus”globalBus:
IMakaioBus
Global bus instance (defaults to MakaioBus singleton)
harnessId?
Section titled “harnessId?”
optionalharnessId?:string
Resolved harness ID for tool policy lookup.
mcpSessionContext?
Section titled “mcpSessionContext?”
optionalmcpSessionContext?:LedgerSessionContext
MCP session context resolved by the orchestrator. Passed through to the connector config so adapters can inject direct tools.
model?
Section titled “model?”
optionalmodel?:string
Model to use (optional - adapter provides default)
nativeTools
Section titled “nativeTools”nativeTools:
string[]
Native tools built into the adapter (e.g., [‘shell_command’, ‘apply_patch’])
providerContext?
Section titled “providerContext?”
optionalproviderContext?:object
Unresolved provider context (credential refs, not plaintext).
Set by the orchestrator before forwarding the startAgent request.
Connectors resolve credentials locally via resolveConnectorCredentials().
providerContext.credentialEnvVars?
Section titled “providerContext.credentialEnvVars?”
optionalcredentialEnvVars?:Record<string,string>
Maps credential keys to environment variable names for subprocess adapters.
E.g., { apiKey: 'ANTHROPIC_API_KEY' }.
providerContext.credentialRefs
Section titled “providerContext.credentialRefs”credentialRefs:
Record<string,string&$brand<"CredentialRef">>
Credential references resolved at the connector layer, not on the bus.
providerContext.definitionId
Section titled “providerContext.definitionId”definitionId:
string
Provider definition ID (e.g., 'anthropic', 'alibaba').
providerContext.endpointOverrides?
Section titled “providerContext.endpointOverrides?”
optionalendpointOverrides?:object
Endpoint URL overrides keyed by protocol.
providerContext.endpointOverrides.anthropic?
Section titled “providerContext.endpointOverrides.anthropic?”
optionalanthropic?:string
providerContext.endpointOverrides.openai?
Section titled “providerContext.endpointOverrides.openai?”
optionalopenai?:string
providerContext.providerConfigId
Section titled “providerContext.providerConfigId”providerConfigId:
string
Provider config UUID. Links back to the ProviderConfig that produced this context.
reasoningEffort?
Section titled “reasoningEffort?”
optionalreasoningEffort?:"none"|"low"|"medium"|"high"|"extra-high"
Reasoning effort for supporting adapters
resumeAdapterSessionId?
Section titled “resumeAdapterSessionId?”
optionalresumeAdapterSessionId?:string
Previous adapter session ID for resume attempts (from recovery).
sessionId?
Section titled “sessionId?”
optionalsessionId?:string
Makaio session identifier
toolLedger?
Section titled “toolLedger?”
optionaltoolLedger?:ISessionToolLedger
Session-scoped ledger tracking MCP injection/discovery/call history. Created once per agent session and passed through unchanged on connector swaps.
confirmedModel?
Section titled “confirmedModel?”
protectedoptionalconfirmedModel?:string
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:118
connector
Section titled “connector”
protectedconnector:TConnector
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:117
The underlying connector instance (created in init)
initialModel?
Section titled “initialModel?”
protectedoptionalinitialModel?:string
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:119
lifecycleTracker
Section titled “lifecycleTracker”
protectedreadonlylifecycleTracker:MessageLifecycleTracker
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:131
Tracks message lifecycle and emits turn events.
toolCallTracker
Section titled “toolCallTracker”
protectedreadonlytoolCallTracker:ToolCallTracker
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:133
Tracks tool.use → tool.output correlation across adapters.
Accessors
Section titled “Accessors”adapterId
Section titled “adapterId”Get Signature
Section titled “Get Signature”get adapterId():
string
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:269
Returns
Section titled “Returns”string
Adapter instance identifier
adapterName
Section titled “adapterName”Get Signature
Section titled “Get Signature”get adapterName():
string
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:273
Returns
Section titled “Returns”string
Adapter type name (e.g., ‘claude-code’, ‘gemini-sdk’)
adapterSessionId
Section titled “adapterSessionId”Get Signature
Section titled “Get Signature”get
protectedadapterSessionId():string|undefined
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:289
Returns
Section titled “Returns”string | undefined
Initial adapter session ID from config (may differ from connector’s resolved session ID)
agentId
Section titled “agentId”Get Signature
Section titled “Get Signature”get agentId():
string
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:265
Returns
Section titled “Returns”string
Unique agent identifier
capabilities
Section titled “capabilities”Get Signature
Section titled “Get Signature”get capabilities():
string[]
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:277
Returns
Section titled “Returns”string[]
Adapter capabilities for runtime feature detection
globalBus
Section titled “globalBus”Get Signature
Section titled “Get Signature”get
protectedglobalBus():IMakaioBus
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:293
Returns
Section titled “Returns”Global bus for cross-namespace communication (defaulted in constructor)
nativeTools
Section titled “nativeTools”Get Signature
Section titled “Get Signature”get nativeTools():
string[]
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:281
Returns
Section titled “Returns”string[]
Native tools built into the adapter
sessionId
Section titled “sessionId”Get Signature
Section titled “Get Signature”get sessionId():
string|undefined
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:285
Returns
Section titled “Returns”string | undefined
Shared Makaio sessionId
Methods
Section titled “Methods”abort()
Section titled “abort()”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.
Returns
Section titled “Returns”void
Throws
Section titled “Throws”Error if connector is not initialized
addBusHandlerCleanup()
Section titled “addBusHandlerCleanup()”
protectedaddBusHandlerCleanup(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().
Parameters
Section titled “Parameters”cleanup
Section titled “cleanup”() => void
Function to unsubscribe from the bus
Returns
Section titled “Returns”void
addConnectorWiringCleanup()
Section titled “addConnectorWiringCleanup()”
protectedaddConnectorWiringCleanup(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.
Parameters
Section titled “Parameters”cleanup
Section titled “cleanup”() => void
Cleanup function to register
Returns
Section titled “Returns”void
close()
Section titled “close()”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.
Parameters
Section titled “Parameters”options?
Section titled “options?”Cleanup options; ephemeral agents suppress session-close lifecycle events because they never join a session.
emitSessionClosed?
Section titled “emitSessionClosed?”boolean
Returns
Section titled “Returns”Promise<void>
complete()
Section titled “complete()”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.
Returns
Section titled “Returns”Promise<MessageResult | null>
Last message result or null if no messages processed
Throws
Section titled “Throws”Error if connector is not initialized
createConnectorEventMapping()
Section titled “createConnectorEventMapping()”
protectedcreateConnectorEventMapping<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.
Type Parameters
Section titled “Type Parameters”TSourceSubject
Section titled “TSourceSubject”TSourceSubject extends ScopedSubjectDefinition<TConnector extends AIAgentConnector<TBus, BaseAgentConnectorConfig<TBus, object>> ? TBus["namespace"] : never>
TNestedMessageProp
Section titled “TNestedMessageProp”TNestedMessageProp extends string | number | symbol | undefined = undefined
TMessage
Section titled “TMessage”TMessage = TNestedMessageProp extends keyof TSourceSubject["$meta"]["payload"] ? TSourceSubject["$meta"]["payload"][TNestedMessageProp] : TSourceSubject["$meta"]["payload"]
TDiscriminator
Section titled “TDiscriminator”TDiscriminator extends string = DiscriminatorKeys<TMessage>
Parameters
Section titled “Parameters”sourceSubject
Section titled “sourceSubject”TSourceSubject
The connector subject to subscribe to
discriminator
Section titled “discriminator”TDiscriminator
The discriminator key within the message (e.g., ‘type’)
handlers
Section titled “handlers”ConnectorEventHandlers<TMessage, TDiscriminator>
Map of discriminator values to target subjects or handler functions
nestedMessageProp?
Section titled “nestedMessageProp?”TNestedMessageProp
Property containing the discriminated union (e.g., ‘msg’), or undefined for top-level
Returns
Section titled “Returns”Unsubscribe function for the connector event mapping subscription
() => void
emitCompletion()
Section titled “emitCompletion()”
protectedemitCompletion(result):Promise<void>
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:389
Parameters
Section titled “Parameters”result
Section titled “result”Omit<z.infer<typeof AgentSchemas.complete>, keyof AgentContext>
Returns
Section titled “Returns”Promise<void>
emitContextWindowUpdate()
Section titled “emitContextWindowUpdate()”
protectedemitContextWindowUpdate(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.
Parameters
Section titled “Parameters”ContextWindowInput
Raw metrics: currentTokens, maxTokens, optional cachedTokens
Returns
Section titled “Returns”Promise<void>
emitError()
Section titled “emitError()”
protectedemitError(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.
Parameters
Section titled “Parameters”result
Section titled “result”Pick<z.infer<typeof AgentSchemas.complete>, "error" | "errorCategory">
Error payload from the connector
Returns
Section titled “Returns”void
emitGlobal()
Section titled “emitGlobal()”
protectedemitGlobal<S>(subject,payload):Promise<void>
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:430
Emit to a global subject with automatic payload enrichment.
Type Parameters
Section titled “Type Parameters”S extends SubjectDefinition
Parameters
Section titled “Parameters”subject
Section titled “subject”S
The subject to emit to
payload
Section titled “payload”Omit<ExtractSubjectPayload<S>, keyof AgentIdentity> & object
The payload (without AgentContext fields - they’re added automatically)
Returns
Section titled “Returns”Promise<void>
emitSessionClosed()
Section titled “emitSessionClosed()”
protectedemitSessionClosed(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.
Parameters
Section titled “Parameters”reason?
Section titled “reason?”string
Reason for session closure (e.g., ‘aborted’, ‘closed’)
Returns
Section titled “Returns”void
emitStart()
Section titled “emitStart()”
protectedemitStart(event?):Promise<void>
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:378
Parameters
Section titled “Parameters”event?
Section titled “event?”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">
Returns
Section titled “Returns”Promise<void>
emitStepFinished()
Section titled “emitStepFinished()”
protectedemitStepFinished(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.
Parameters
Section titled “Parameters”stepType
Section titled “stepType”"text" | "reasoning" | "tool_use"
The type of step that finished
content
Section titled “content”{ 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)
Type Literal
Section titled “Type Literal”{ 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)
attachmentType
Section titled “attachmentType”"file" | "directory" = AttachmentTypeSchema
Whether the attachment is a file or directory
displayName?
Section titled “displayName?”string = ...
Optional human-readable display name override
fileName
Section titled “fileName”string = ...
Original filename with extension (e.g. “api-spec.yaml”) — for display and type inference
filePath
Section titled “filePath”string = ...
Server-side file path — always populated before message reaches adapters
source
Section titled “source”{ data: string; mimeType: string; type: "base64"; } | { mimeType?: string; type: "url"; url: string; } = ContentSourceSchema
Inline content — base64 for binary, raw string for text
"attachment" = ...
Type Literal
Section titled “Type Literal”{ content: string; metadata?: Record<string, unknown>; type: "reasoning"; }
The complete content of the step (text, reasoning, tool_call, or tool_output)
content
Section titled “content”string = ...
metadata?
Section titled “metadata?”Record<string, unknown> = ...
Optional provider/runtime metadata for reasoning blocks.
"reasoning" = ...
Returns
Section titled “Returns”Promise<void>
emitStepStarted()
Section titled “emitStepStarted()”
protectedemitStepStarted(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.
Parameters
Section titled “Parameters”stepType
Section titled “stepType”"text" | "reasoning" | "tool_use"
The type of step (text, reasoning, tool_use)
blockData?
Section titled “blockData?”{ toolCallId: string; toolName: string; type: "tool_use"; } | { type: "reasoning"; } | { type: "text"; }
Optional metadata for the block (e.g., toolName for tool_use)
content?
Section titled “content?”{ 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)
Type Literal
Section titled “Type Literal”{ 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)
attachmentType
Section titled “attachmentType”"file" | "directory" = AttachmentTypeSchema
Whether the attachment is a file or directory
displayName?
Section titled “displayName?”string = ...
Optional human-readable display name override
fileName
Section titled “fileName”string = ...
Original filename with extension (e.g. “api-spec.yaml”) — for display and type inference
filePath
Section titled “filePath”string = ...
Server-side file path — always populated before message reaches adapters
source
Section titled “source”{ data: string; mimeType: string; type: "base64"; } | { mimeType?: string; type: "url"; url: string; } = ContentSourceSchema
Inline content — base64 for binary, raw string for text
"attachment" = ...
Type Literal
Section titled “Type Literal”{ content: string; metadata?: Record<string, unknown>; type: "reasoning"; }
Optional content for the step (e.g., tool_call block for tool_use)
content
Section titled “content”string = ...
metadata?
Section titled “metadata?”Record<string, unknown> = ...
Optional provider/runtime metadata for reasoning blocks.
"reasoning" = ...
Returns
Section titled “Returns”Promise<void>
emitToolOutput()
Section titled “emitToolOutput()”
protectedemitToolOutput(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.
Parameters
Section titled “Parameters”output
Section titled “output”string
Tool output content
Hints for correlation (nativeId and/or toolName)
Returns
Section titled “Returns”Promise<ToolOutputResolution>
Resolved toolCallId, toolName (falls back to ‘unknown’), and args from the matched tool.use call
emitToolUse()
Section titled “emitToolUse()”
protectedemitToolUse(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.
Parameters
Section titled “Parameters”toolName
Section titled “toolName”string
Name of the tool being invoked
Record<string, unknown>
Tool arguments
nativeId?
Section titled “nativeId?”string
Native provider ID if available (e.g., toolu_, call_)
Returns
Section titled “Returns”Promise<string>
The correlation ID used (nativeId if provided, else generated UUID)
enrichPayload()
Section titled “enrichPayload()”
protectedenrichPayload<T>(payload):Promise<T&Required<AgentIdentity> &object>
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:421
Enrich a payload with agent context fields.
Type Parameters
Section titled “Type Parameters”T extends object
Parameters
Section titled “Parameters”payload
Section titled “payload”T
The base payload to enrich
Returns
Section titled “Returns”Promise<T & Required<AgentIdentity> & object>
Payload with AgentContext fields and optional messageId added
getAdapterSessionId()
Section titled “getAdapterSessionId()”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.
Returns
Section titled “Returns”Promise<string>
Session ID from provider
Throws
Section titled “Throws”Error if connector is not initialized
getBlockIndex()
Section titled “getBlockIndex()”
protectedgetBlockIndex():number
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:525
Get the current block index (for adapters that need to track it externally).
Returns
Section titled “Returns”number
Current block index within the turn
getContextWindowSize()
Section titled “getContextWindowSize()”
protectedgetContextWindowSize(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.
Parameters
Section titled “Parameters”modelName?
Section titled “modelName?”string
Model name to look up (defaults to confirmedModel or initialModel)
Returns
Section titled “Returns”number | undefined
Context window size in tokens, or undefined if not found
incrementBlockIndex()
Section titled “incrementBlockIndex()”
protectedincrementBlockIndex():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.
Returns
Section titled “Returns”void
init()
Section titled “init()”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.
Returns
Section titled “Returns”Promise<void>
Throws
Section titled “Throws”Error if already initialized
initialize()
Section titled “initialize()”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().
Parameters
Section titled “Parameters”options?
Section titled “options?”Optional initialization options (system prompt, sessionContext)
Returns
Section titled “Returns”Promise<void>
onBeforeEmitCompletion()
Section titled “onBeforeEmitCompletion()”
protectedonBeforeEmitCompletion():Promise<void>
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:880
Returns
Section titled “Returns”Promise<void>
onMessageHandle()
Section titled “onMessageHandle()”
protectedonMessageHandle(messageHandle):Promise<void>
Defined in: ../../../adapters/core/src/agent/ai-agent.ts:882
Parameters
Section titled “Parameters”messageHandle
Section titled “messageHandle”Returns
Section titled “Returns”Promise<void>
sendMessage()
Section titled “sendMessage()”
protectedsendMessage(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.
Parameters
Section titled “Parameters”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
Returns
Section titled “Returns”Promise<void>
shouldUseNativeResume()
Section titled “shouldUseNativeResume()”
protectedshouldUseNativeResume(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.
Parameters
Section titled “Parameters”sessionContext?
Section titled “sessionContext?”Context signals from SessionOrchestrator
extractedContext?
Section titled “extractedContext?”unknown = ...
Structured context from compression (if hasCompression=true).
hasCompression?
Section titled “hasCompression?”boolean = ...
Whether compression is active (extractedContext present). If true, Agent should use fresh mode with compressed context.
hasConnectorSwap?
Section titled “hasConnectorSwap?”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.
hasNewTransforms?
Section titled “hasNewTransforms?”boolean = ...
Whether transforms have been applied since last turn. If true, Agent should use fresh mode (history changed).
isFirstTurn?
Section titled “isFirstTurn?”boolean = ...
Whether this is the first turn in the session. If true, no native history exists yet.
messageHistory?
Section titled “messageHistory?”object[] = ...
Curated message history assembled via getFullConversation(). Only used if Agent decides to inject (fresh mode).
turnContext?
Section titled “turnContext?”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().
Returns
Section titled “Returns”boolean
true if native resume should be used
start()
Section titled “start()”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.
Parameters
Section titled “Parameters”message
Section titled “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?: 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)
options?
Section titled “options?”Optional start options (e.g., delivery mode, sessionContext)
Returns
Section titled “Returns”Promise<AgentStartResult>
Session ID, agent ID, and message handle for tracking
subscribeConnector()
Section titled “subscribeConnector()”
protectedsubscribeConnector<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.
Type Parameters
Section titled “Type Parameters”Subject
Section titled “Subject”Subject extends ScopedSubjectDefinition<TConnector extends AIAgentConnector<TBus, BaseAgentConnectorConfig<TBus, object>> ? TBus["namespace"] : never>
Parameters
Section titled “Parameters”connector
Section titled “connector”TConnector
Connector instance to subscribe on
subject
Section titled “subject”Subject
Subject definition to subscribe to
handler
Section titled “handler”HandlerForSubjectDefinition<Subject>
Subject handler
options?
Section titled “options?”Optional bus subscription options
Returns
Section titled “Returns”void
supportsNativeResume()
Section titled “supportsNativeResume()”
protectedsupportsNativeResume():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.
Returns
Section titled “Returns”boolean
true if native resume is supported
swapConnector()
Section titled “swapConnector()”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:
- Create new connector first (old connector still alive)
- Wire events to new connector (accumulate cleanups separately)
- If successful: close old connector, assign new one
- 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.
Parameters
Section titled “Parameters”configOverrides?
Section titled “configOverrides?”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)
Returns
Section titled “Returns”Promise<void>
Throws
Section titled “Throws”Error if connector is currently processing a turn
trackUsage()
Section titled “trackUsage()”
protectedtrackUsage(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.
Parameters
Section titled “Parameters”normalized
Section titled “normalized”Normalized usage metrics from adapter-specific normalizer
Returns
Section titled “Returns”Promise<void>
wireEvents()
Section titled “wireEvents()”
abstractprotectedwireEvents(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.
Parameters
Section titled “Parameters”connector
Section titled “connector”TConnector
Connector instance to wire
Returns
Section titled “Returns”void | Promise<void>