Table of Contents

Class AgentSession

Namespace
JD.AI.Core.Agents
Assembly
JD.AI.Core.dll

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

registry IProviderRegistry
initialKernel Kernel
initialModel ProviderModelInfo

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

string

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

string

AgentDefinitionRegistry

Registry of agent definitions loaded from *.agent.yaml files.

public IAgentDefinitionRegistry? AgentDefinitionRegistry { get; set; }

Property Value

IAgentDefinitionRegistry

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

IApprovalService

AuditService

Optional audit service for emitting session lifecycle events.

public AuditService? AuditService { get; set; }

Property Value

AuditService

AutoRunEnabled

public bool AutoRunEnabled { get; set; }

Property Value

bool

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

List<(string ToolName, string Args)>

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

HashSet<string>

CurrentModel

public ProviderModelInfo? CurrentModel { get; }

Property Value

ProviderModelInfo

CurrentTurn

Current turn being tracked (set by AgentLoop before each turn).

public TurnRecord? CurrentTurn { get; set; }

Property Value

TurnRecord

EventBus

Optional event bus for emitting tool audit events.

public IEventBus? EventBus { get; set; }

Property Value

IEventBus

FallbackModels

Fallback model chain — used when the primary model returns 429/503/timeout.

public IReadOnlyList<string> FallbackModels { get; set; }

Property Value

IReadOnlyList<string>

ForkPoints

public IReadOnlyList<ForkPoint> ForkPoints { get; }

Property Value

IReadOnlyList<ForkPoint>

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

ExecutionTimeline

LoadoutRegistry

The tool loadout registry for this session, used by loadout-aware scoping.

public IToolLoadoutRegistry? LoadoutRegistry { get; set; }

Property Value

IToolLoadoutRegistry

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

decimal?

MemoryService

Optional memory service for per-project daily logs and long-term memory.

public IMemoryService? MemoryService { get; set; }

Property Value

IMemoryService

ModelSwitchHistory

public IReadOnlyList<ModelSwitchRecord> ModelSwitchHistory { get; }

Property Value

IReadOnlyList<ModelSwitchRecord>

NoSessionPersistence

When true, session persistence is disabled entirely.

public bool NoSessionPersistence { get; set; }

Property Value

bool

OriginalSystemPrompt

Original system prompt captured at session startup (before compaction or runtime edits).

public string? OriginalSystemPrompt { get; }

Property Value

string

PermissionMode

Controls the permission model for tool invocations within the session.

public PermissionMode PermissionMode { get; set; }

Property Value

PermissionMode

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

bool

PromptCacheTtl

Prompt cache time-to-live used when prompt caching is enabled.

public PromptCacheTtl PromptCacheTtl { get; set; }

Property Value

PromptCacheTtl

PromptCachingEnabled

When true, supported providers can automatically enable prompt caching.

public bool PromptCachingEnabled { get; set; }

Property Value

bool

ReasoningEffortOverride

Session-level reasoning effort override. Null means provider/model default ("auto").

public ReasoningEffort? ReasoningEffortOverride { get; set; }

Property Value

ReasoningEffort?

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

Func<string, IReadOnlyList<(string ToolName, string Args)>, CancellationToken, Task<string>>

SessionInfo

public SessionInfo? SessionInfo { get; set; }

Property Value

SessionInfo

SessionSpendUsd

Accumulated estimated spend for this session in USD. Updated after each turn by the budget tracker.

public decimal SessionSpendUsd { get; set; }

Property Value

decimal

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

bool

Store

public SessionStore? Store { get; set; }

Property Value

SessionStore

SystemPromptTokens

Cached token count for the current system prompt. Recomputed only when prompt text changes.

public int SystemPromptTokens { get; }

Property Value

int

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

ToolPermissionProfile

ToolSafetyTiers

Safety tier map for text-based tool call validation. Set during initialization from ToolAssemblyScanner.

public IReadOnlyDictionary<string, SafetyTier>? ToolSafetyTiers { get; set; }

Property Value

IReadOnlyDictionary<string, SafetyTier>

TotalTokens

public long TotalTokens { get; set; }

Property Value

long

TurnIndex

Current turn index (0-based).

public int TurnIndex { get; }

Property Value

int

UsageMeter

Optional usage meter for centralized metering.

public IUsageMeter? UsageMeter { get; set; }

Property Value

IUsageMeter

Verbose

When true, emit verbose diagnostics (tool calls, arguments) to stderr. Set via --verbose CLI flag.

public bool Verbose { get; set; }

Property Value

bool

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

bool

Methods

CaptureOriginalSystemPromptIfUnset(string?)

Captures the original system prompt if it has not already been captured.

public void CaptureOriginalSystemPromptIfUnset(string? prompt = null)

Parameters

prompt string

ClearHistory()

Clears conversation history.

public void ClearHistory()

CloseSessionAsync()

Close the session (mark inactive, export).

public Task CloseSessionAsync()

Returns

Task

CompactAsync(CancellationToken)

Forces compaction of the chat history using hierarchical summarization.

public Task CompactAsync(CancellationToken ct = default)

Parameters

ct CancellationToken

Returns

Task

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

targetTokens int
ct CancellationToken

Returns

Task<int>

CycleReasoningEffort()

Cycles reasoning effort for quick keyboard toggles: auto -> low -> medium -> high -> max -> auto.

public ReasoningEffort? CycleReasoningEffort()

Returns

ReasoningEffort?

ExportSessionAsync()

Export the current session to JSON.

public Task ExportSessionAsync()

Returns

Task

ForkSessionAsync(string?)

Fork the current session: clone history into a new session.

public Task<SessionInfo?> ForkSessionAsync(string? forkName = null)

Parameters

forkName string

Returns

Task<SessionInfo>

InitializePersistenceAsync(string, string?)

Initialize persistence — creates or resumes a session.

public Task InitializePersistenceAsync(string projectPath, string? resumeId = null)

Parameters

projectPath string
resumeId string

Returns

Task

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

content string
thinkingText string
tokensIn long
tokensOut long
durationMs long

Returns

Task

RecordFileTouch(string, string)

Record a file operation on the current turn.

public void RecordFileTouch(string filePath, string operation)

Parameters

filePath string
operation string

RecordToolCall(string, string?, string?, string, long)

public void RecordToolCall(string toolName, string? arguments, string? result, string status, long durationMs)

Parameters

toolName string
arguments string
result string
status string
durationMs long

RecordUserTurnAsync(string)

Record a user message turn and persist.

public Task RecordUserTurnAsync(string content)

Parameters

content string

Returns

Task

ReplaceSystemPrompt(string)

Replaces the current system prompt in chat history, inserting one if absent.

public void ReplaceSystemPrompt(string prompt)

Parameters

prompt string

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

model ProviderModelInfo
kernel Kernel

SwitchModel(ProviderModelInfo)

Switches the backing LLM while preserving chat history and tools.

public void SwitchModel(ProviderModelInfo model)

Parameters

model ProviderModelInfo

SwitchModel(ProviderModelInfo, string)

Switches the backing LLM with an explicit switch mode.

public void SwitchModel(ProviderModelInfo model, string switchMode)

Parameters

model ProviderModelInfo
switchMode string

SwitchProviderAsync(ProviderModelInfo, SwitchMode, CancellationToken)

Switches provider/model with conversation transformation.

public Task SwitchProviderAsync(ProviderModelInfo newModel, SwitchMode mode, CancellationToken ct = default)

Parameters

newModel ProviderModelInfo
mode SwitchMode
ct CancellationToken

Returns

Task

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

canonicalToolName string
argsSummary string

Returns

bool

TryResetSystemPrompt()

Restores the current system prompt to the originally captured startup text.

public bool TryResetSystemPrompt()

Returns

bool

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

modelNameOrId string
ct CancellationToken

Returns

Task<bool>

UpdateModelMetadata(ProviderModelInfo)

Updates only the metadata fields on the current model (no kernel rebuild or fork point).

public void UpdateModelMetadata(ProviderModelInfo enrichedModel)

Parameters

enrichedModel ProviderModelInfo

Events

ModelChanged

[SuppressMessage("Design", "CA1003:Use generic event handler instances", Justification = "ProviderModelInfo is the event data")]
public event EventHandler<ProviderModelInfo>? ModelChanged

Event Type

EventHandler<ProviderModelInfo>