Class AgentSession
Manages the conversation state, kernel, compaction, and persistence.
public sealed class AgentSession
- Inheritance
-
AgentSession
- Inherited Members
Constructors
AgentSession(IProviderRegistry, Kernel, ProviderModelInfo)
public AgentSession(IProviderRegistry registry, Kernel initialKernel, ProviderModelInfo initialModel)
Parameters
registryIProviderRegistryinitialKernelKernelinitialModelProviderModelInfo
Properties
ActiveLoadoutName
The name of the active ToolLoadout for this session. When set, agents and tooling systems may use this to filter which plugins are exposed. Set to null to expose all registered plugins (default).
public string? ActiveLoadoutName { get; set; }
Property Value
ActiveWorkflowName
The name of the currently executing workflow, if any. When set, tool calls are recognized as workflow-coordinated and skip the workflow enforcement prompt.
public string? ActiveWorkflowName { get; set; }
Property Value
AgentDefinitionRegistry
Registry of agent definitions loaded from *.agent.yaml files.
public IAgentDefinitionRegistry? AgentDefinitionRegistry { get; set; }
Property Value
AllPlugins
Snapshot of all registered plugins before loadout scoping is applied.
public IReadOnlyList<KernelPlugin>? AllPlugins { get; set; }
Property Value
- IReadOnlyList<KernelPlugin>
ApprovalService
Approval service for human-in-the-loop or policy-based operation gates.
When null, approval is not enforced.
public IApprovalService? ApprovalService { get; set; }
Property Value
AuditService
Optional audit service for emitting session lifecycle events.
public AuditService? AuditService { get; set; }
Property Value
AutoRunEnabled
public bool AutoRunEnabled { get; set; }
Property Value
CapturedWorkflowSteps
Tool calls captured during an active workflow recording session. Populated by ToolConfirmationFilter, consumed by AgentLoop at turn end.
public List<(string ToolName, string? Args)> CapturedWorkflowSteps { get; }
Property Value
ConfirmedOnceTools
Tools the user has already approved once for this session. Shared across structured and text-emitted tool call paths.
public HashSet<string> ConfirmedOnceTools { get; }
Property Value
CurrentModel
public ProviderModelInfo? CurrentModel { get; }
Property Value
CurrentTurn
Current turn being tracked (set by AgentLoop before each turn).
public TurnRecord? CurrentTurn { get; set; }
Property Value
EventBus
Optional event bus for emitting tool audit events.
public IEventBus? EventBus { get; set; }
Property Value
FallbackModels
Fallback model chain — used when the primary model returns 429/503/timeout.
public IReadOnlyList<string> FallbackModels { get; set; }
Property Value
ForkPoints
public IReadOnlyList<ForkPoint> ForkPoints { get; }
Property Value
History
public ChatHistory History { get; }
Property Value
- ChatHistory
Kernel
public Kernel Kernel { get; }
Property Value
- Kernel
LastTimeline
Execution timeline from the most recent turn, used by /trace.
public ExecutionTimeline? LastTimeline { get; set; }
Property Value
LoadoutRegistry
The tool loadout registry for this session, used by loadout-aware scoping.
public IToolLoadoutRegistry? LoadoutRegistry { get; set; }
Property Value
MaxBudgetUsd
Per-session budget limit in USD (set via --max-budget-usd).
When exceeded the agent stops processing turns.
public decimal? MaxBudgetUsd { get; set; }
Property Value
MemoryService
Optional memory service for per-project daily logs and long-term memory.
public IMemoryService? MemoryService { get; set; }
Property Value
ModelSwitchHistory
public IReadOnlyList<ModelSwitchRecord> ModelSwitchHistory { get; }
Property Value
NoSessionPersistence
When true, session persistence is disabled entirely.
public bool NoSessionPersistence { get; set; }
Property Value
OriginalSystemPrompt
Original system prompt captured at session startup (before compaction or runtime edits).
public string? OriginalSystemPrompt { get; }
Property Value
PermissionMode
Controls the permission model for tool invocations within the session.
public PermissionMode PermissionMode { get; set; }
Property Value
PlanMode
When true, the agent operates in plan-only mode (read/explore, no file writes). Toggled via the /plan slash command.
public bool PlanMode { get; set; }
Property Value
PromptCacheTtl
Prompt cache time-to-live used when prompt caching is enabled.
public PromptCacheTtl PromptCacheTtl { get; set; }
Property Value
PromptCachingEnabled
When true, supported providers can automatically enable prompt caching.
public bool PromptCachingEnabled { get; set; }
Property Value
ReasoningEffortOverride
Session-level reasoning effort override. Null means provider/model default ("auto").
public ReasoningEffort? ReasoningEffortOverride { get; set; }
Property Value
SaveCapturedWorkflowAsync
Callback to save a captured workflow. Set during initialization by the host (e.g., InteractiveLoop) that has access to the workflow catalog. Parameters: (workflowName, steps as list of (toolName, args)), returns saved workflow name.
public Func<string, IReadOnlyList<(string ToolName, string? Args)>, CancellationToken, Task<string>>? SaveCapturedWorkflowAsync { get; set; }
Property Value
SessionInfo
public SessionInfo? SessionInfo { get; set; }
Property Value
SessionSpendUsd
Accumulated estimated spend for this session in USD. Updated after each turn by the budget tracker.
public decimal SessionSpendUsd { get; set; }
Property Value
SkipPermissions
When true, ALL tool confirmations are bypassed — no safety prompts at all. Set via --dangerously-skip-permissions or /permissions off.
public bool SkipPermissions { get; set; }
Property Value
Store
public SessionStore? Store { get; set; }
Property Value
SystemPromptTokens
Cached token count for the current system prompt. Recomputed only when prompt text changes.
public int SystemPromptTokens { get; }
Property Value
ToolPermissionProfile
Explicit allow/deny rules for tool invocations. A tool must either match an allow rule or receive per-call user confirmation.
public ToolPermissionProfile ToolPermissionProfile { get; set; }
Property Value
ToolSafetyTiers
Safety tier map for text-based tool call validation. Set during initialization from ToolAssemblyScanner.
public IReadOnlyDictionary<string, SafetyTier>? ToolSafetyTiers { get; set; }
Property Value
TotalTokens
public long TotalTokens { get; set; }
Property Value
TurnIndex
Current turn index (0-based).
public int TurnIndex { get; }
Property Value
UsageMeter
Optional usage meter for centralized metering.
public IUsageMeter? UsageMeter { get; set; }
Property Value
Verbose
When true, emit verbose diagnostics (tool calls, arguments) to stderr. Set via --verbose CLI flag.
public bool Verbose { get; set; }
Property Value
WorkflowDeclinedThisTurn
When true, the user has declined the workflow prompt for the current turn. Reset at the start of each turn by ResetTurnState().
public bool WorkflowDeclinedThisTurn { get; set; }
Property Value
Methods
CaptureOriginalSystemPromptIfUnset(string?)
Captures the original system prompt if it has not already been captured.
public void CaptureOriginalSystemPromptIfUnset(string? prompt = null)
Parameters
promptstring
ClearHistory()
Clears conversation history.
public void ClearHistory()
CloseSessionAsync()
Close the session (mark inactive, export).
public Task CloseSessionAsync()
Returns
CompactAsync(CancellationToken)
Forces compaction of the chat history using hierarchical summarization.
public Task CompactAsync(CancellationToken ct = default)
Parameters
Returns
CompactSystemPromptAsync(int, CancellationToken)
Compacts the system prompt using the LLM to summarize it while preserving key instructions. Returns the new token count. Skips if already within budget.
public Task<int> CompactSystemPromptAsync(int targetTokens, CancellationToken ct = default)
Parameters
targetTokensintctCancellationToken
Returns
CycleReasoningEffort()
Cycles reasoning effort for quick keyboard toggles: auto -> low -> medium -> high -> max -> auto.
public ReasoningEffort? CycleReasoningEffort()
Returns
ExportSessionAsync()
Export the current session to JSON.
public Task ExportSessionAsync()
Returns
ForkSessionAsync(string?)
Fork the current session: clone history into a new session.
public Task<SessionInfo?> ForkSessionAsync(string? forkName = null)
Parameters
forkNamestring
Returns
InitializePersistenceAsync(string, string?)
Initialize persistence — creates or resumes a session.
public Task InitializePersistenceAsync(string projectPath, string? resumeId = null)
Parameters
Returns
RecordAssistantTurnAsync(string, string?, long, long, long)
Record an assistant response turn and persist.
public Task RecordAssistantTurnAsync(string content, string? thinkingText = null, long tokensIn = 0, long tokensOut = 0, long durationMs = 0)
Parameters
Returns
RecordFileTouch(string, string)
Record a file operation on the current turn.
public void RecordFileTouch(string filePath, string operation)
Parameters
RecordToolCall(string, string?, string?, string, long)
public void RecordToolCall(string toolName, string? arguments, string? result, string status, long durationMs)
Parameters
RecordUserTurnAsync(string)
Record a user message turn and persist.
public Task RecordUserTurnAsync(string content)
Parameters
contentstring
Returns
ReplaceSystemPrompt(string)
Replaces the current system prompt in chat history, inserting one if absent.
public void ReplaceSystemPrompt(string prompt)
Parameters
promptstring
ResetTurnState()
Resets per-turn transient state. Called at the start of each agent turn.
public void ResetTurnState()
RestorePersistedModel(ProviderModelInfo, Kernel)
Restores the active model/kernel pair from persisted session state without recording an additional model switch.
public void RestorePersistedModel(ProviderModelInfo model, Kernel kernel)
Parameters
modelProviderModelInfokernelKernel
SwitchModel(ProviderModelInfo)
Switches the backing LLM while preserving chat history and tools.
public void SwitchModel(ProviderModelInfo model)
Parameters
modelProviderModelInfo
SwitchModel(ProviderModelInfo, string)
Switches the backing LLM with an explicit switch mode.
public void SwitchModel(ProviderModelInfo model, string switchMode)
Parameters
modelProviderModelInfoswitchModestring
SwitchProviderAsync(ProviderModelInfo, SwitchMode, CancellationToken)
Switches provider/model with conversation transformation.
public Task SwitchProviderAsync(ProviderModelInfo newModel, SwitchMode mode, CancellationToken ct = default)
Parameters
newModelProviderModelInfomodeSwitchModectCancellationToken
Returns
TryRegisterToolCallForCurrentTurn(string, string?)
Registers a tool-call fingerprint for the current turn. Returns false when the same tool/argument signature was already seen.
public bool TryRegisterToolCallForCurrentTurn(string canonicalToolName, string? argsSummary)
Parameters
Returns
TryResetSystemPrompt()
Restores the current system prompt to the originally captured startup text.
public bool TryResetSystemPrompt()
Returns
TrySwitchModelAsync(string, CancellationToken)
Attempts to resolve a model by name/id and switch to it. Returns true if the switch succeeded, false if the model was not found.
public Task<bool> TrySwitchModelAsync(string modelNameOrId, CancellationToken ct = default)
Parameters
modelNameOrIdstringctCancellationToken
Returns
UpdateModelMetadata(ProviderModelInfo)
Updates only the metadata fields on the current model (no kernel rebuild or fork point).
public void UpdateModelMetadata(ProviderModelInfo enrichedModel)
Parameters
enrichedModelProviderModelInfo
Events
ModelChanged
[SuppressMessage("Design", "CA1003:Use generic event handler instances", Justification = "ProviderModelInfo is the event data")]
public event EventHandler<ProviderModelInfo>? ModelChanged