a3s_code_core/agent_api.rs
1//! Agent Facade API
2//!
3//! High-level, ergonomic API for using A3S Code as an embedded library.
4//!
5//! ## Example
6//!
7//! ```rust,no_run
8//! use a3s_code_core::Agent;
9//!
10//! # async fn run() -> anyhow::Result<()> {
11//! let agent = Agent::new("agent.acl").await?;
12//! let session = agent.session_async("/my-project", None).await?;
13//! let result = session.send("Explain the auth module", None).await?;
14//! println!("{}", result.text);
15//! # Ok(())
16//! # }
17//! ```
18
19use crate::agent::{AgentConfig, AgentEvent, AgentResult};
20use crate::commands::CommandRegistry;
21use crate::config::CodeConfig;
22use crate::error::Result;
23use crate::hitl::PendingConfirmationInfo;
24use crate::llm::{LlmClient, Message};
25use crate::prompts::{PlanningMode, SystemPromptSlots};
26use crate::queue::{
27 ExternalTask, ExternalTaskResult, LaneHandlerConfig, SessionLane, SessionQueueConfig,
28 SessionQueueStats,
29};
30use crate::tools::{ToolContext, ToolExecutor};
31use a3s_lane::{DeadLetter, MetricsSnapshot};
32use a3s_memory::MemoryStore;
33use std::collections::HashMap;
34use std::path::{Path, PathBuf};
35use std::sync::{Arc, RwLock};
36use tokio::sync::mpsc;
37use tokio::task::JoinHandle;
38mod agent_binding;
39mod agent_bootstrap;
40mod agent_facade;
41mod agent_loop_runtime;
42mod agent_sessions;
43mod capabilities;
44mod capability_facade;
45mod command_runtime;
46mod conversation_runtime;
47pub(crate) use conversation_runtime::{
48 ExactRecoveryError, ExactRecoveryPreparation, PreparedExactRecovery,
49};
50mod direct_tool_facade;
51mod direct_tools;
52mod governance_facade;
53mod hook_control;
54mod project_instructions;
55mod projected_flow;
56mod projected_host_capability;
57mod projected_ui;
58mod run_admission;
59mod run_facade;
60mod run_hook_executor;
61mod run_lifecycle;
62mod runtime;
63mod runtime_checkpoints;
64mod runtime_events;
65mod session_builder;
66mod session_clock;
67mod session_close;
68mod session_commands;
69mod session_config;
70mod session_extensions;
71mod session_facade;
72mod session_hitl;
73mod session_options;
74mod session_persistence;
75mod session_queue;
76mod session_runs;
77mod session_runtime;
78mod session_save;
79mod session_verification;
80mod session_view;
81mod workflow_facade;
82pub use agent_facade::{Agent, SessionBuilder};
83use direct_tools::DirectToolRuntime;
84use hook_control::HookControl;
85pub use projected_flow::ProjectedFlowHandle;
86pub use projected_ui::ProjectedUiHandle;
87use runtime_events::ActiveToolState;
88use session_close::SessionCloseHandle;
89use session_extensions::SessionExtensionRuntime;
90use session_hitl::HitlControl;
91use session_queue::QueueControl;
92use session_runs::RunControl;
93use session_verification::VerificationRuntime;
94use session_view::SessionView;
95
96/// Canonicalize a path, stripping the Windows `\\?\` UNC prefix to avoid
97/// polluting workspace strings throughout the system (prompts, session data, etc.).
98fn safe_canonicalize(path: &Path) -> PathBuf {
99 match std::fs::canonicalize(path) {
100 Ok(p) => strip_unc_prefix(p),
101 Err(_) => path.to_path_buf(),
102 }
103}
104
105/// Strip the Windows extended-length path prefix (`\\?\`) that `canonicalize()` adds.
106/// On non-Windows this is a no-op.
107fn strip_unc_prefix(path: PathBuf) -> PathBuf {
108 #[cfg(windows)]
109 {
110 let s = path.to_string_lossy();
111 if let Some(stripped) = s.strip_prefix(r"\\?\") {
112 return PathBuf::from(stripped);
113 }
114 }
115 path
116}
117
118// ============================================================================
119// ToolCallResult
120// ============================================================================
121
122/// Result of a direct tool execution (no LLM).
123#[derive(Debug, Clone)]
124pub struct ToolCallResult {
125 pub name: String,
126 pub output: String,
127 pub exit_code: i32,
128 pub metadata: Option<serde_json::Value>,
129 /// Structured discriminant for tool failures. `None` when the tool
130 /// either succeeded or failed without a typed reason (the message in
131 /// `output` is then the only diagnostic). Populated for known
132 /// kinds such as `VersionConflict` so SDK callers can branch on the
133 /// `type` field instead of regex-matching `output`.
134 pub error_kind: Option<crate::tools::ToolErrorKind>,
135}
136
137/// Result of admitting a host-selected run identity for detached execution.
138///
139/// `Started` owns a supervisor task that drains the ordinary Code event stream
140/// into the authoritative run store. Dropping the handle detaches the task;
141/// call [`AgentSession::close`] for graceful cancellation and cleanup.
142pub enum AgentRunSpawn {
143 Started {
144 snapshot: crate::run::RunSnapshot,
145 worker: JoinHandle<()>,
146 },
147 Replayed {
148 snapshot: crate::run::RunSnapshot,
149 },
150}
151
152impl AgentRunSpawn {
153 pub const fn replayed(&self) -> bool {
154 matches!(self, Self::Replayed { .. })
155 }
156
157 pub fn snapshot(&self) -> &crate::run::RunSnapshot {
158 match self {
159 Self::Started { snapshot, .. } | Self::Replayed { snapshot } => snapshot,
160 }
161 }
162}
163
164// ============================================================================
165// ReadFileOptions
166// ============================================================================
167
168/// Optional line-range controls for direct `read` tool calls.
169#[derive(Debug, Clone, Copy, Default)]
170pub struct ReadFileOptions {
171 /// 0-indexed line offset to start reading from.
172 pub offset: Option<usize>,
173 /// Maximum number of lines to read.
174 pub limit: Option<usize>,
175}
176
177// ============================================================================
178// SessionOptions
179// ============================================================================
180
181/// Optional per-session overrides.
182#[derive(Clone, Default)]
183pub struct SessionOptions {
184 /// Override the default model. Format: `"provider/model"` (e.g., `"openai/gpt-4o"`).
185 pub model: Option<String>,
186 /// Priority used for top-level operations created by this session.
187 pub task_priority: crate::task_scheduler::TaskPriority,
188 /// Extra directories to scan for agent files.
189 /// Merged with any global `agent_dirs` from [`CodeConfig`].
190 pub agent_dirs: Vec<PathBuf>,
191 /// Reproducible disposable workers registered for task delegation.
192 /// Explicit session workers override agents loaded from directories by name.
193 pub worker_agents: Vec<crate::subagent::WorkerAgentSpec>,
194 /// Optional queue configuration for lane-based tool execution.
195 ///
196 /// When set, enables priority-based tool scheduling with parallel execution
197 /// of read-only (Query-lane) tools, DLQ, metrics, and external task handling.
198 pub queue_config: Option<SessionQueueConfig>,
199 /// Optional security provider for taint tracking and output sanitization
200 pub security_provider: Option<Arc<dyn crate::security::SecurityProvider>>,
201 /// Optional host-supplied LLM client.
202 ///
203 /// When set, it is used directly, overriding the `provider/model`
204 /// factory resolution — the one Action-layer backend that was previously
205 /// only injectable in test code. Lets a host plug in a provider the
206 /// built-in factory does not cover, a deterministic record/replay client,
207 /// or an HTTP-layer proxy/audit wrapper. Mirrors `workspace_services`.
208 pub llm_client: Option<Arc<dyn crate::llm::LlmClient>>,
209 /// Optional context providers for RAG
210 pub context_providers: Vec<Arc<dyn crate::context::ContextProvider>>,
211 /// One exact-generation cognitive package supplied by the embedding host.
212 ///
213 /// This is separate from general-purpose RAG providers: Code persists the
214 /// immutable package binding and treats provider failure as fatal. The host
215 /// retains A3S Use lease, Registry, installation, and lifecycle authority.
216 pub cognitive_context: Option<crate::cognitive_context::CognitiveContextSession>,
217 /// Optional confirmation manager for HITL
218 pub confirmation_manager: Option<Arc<dyn crate::hitl::ConfirmationProvider>>,
219 /// Optional confirmation policy (will be used to create ConfirmationManager if confirmation_manager is not set)
220 pub confirmation_policy: Option<crate::hitl::ConfirmationPolicy>,
221 /// Optional permission checker
222 pub permission_checker: Option<Arc<dyn crate::permissions::PermissionChecker>>,
223 /// Serializable permission policy used to build the checker, when available.
224 pub permission_policy: Option<crate::permissions::PermissionPolicy>,
225 /// Enable planning
226 pub planning_mode: PlanningMode,
227 /// Enable goal tracking
228 pub goal_tracking: bool,
229 /// Extra directories to scan for skill files (*.md).
230 /// Merged with any global `skill_dirs` from [`CodeConfig`].
231 pub skill_dirs: Vec<PathBuf>,
232 /// Optional skill registry for instruction injection
233 pub skill_registry: Option<Arc<crate::skills::SkillRegistry>>,
234 /// Whether active skill `allowed-tools` restrict ordinary session tool calls.
235 ///
236 /// Defaults to false so ordinary tools continue through permission policy,
237 /// hooks, and HITL. Set true to restore the legacy global active-skill
238 /// restriction behavior.
239 pub enforce_active_skill_tool_restrictions: Option<bool>,
240 /// Custom memory store override for long-term memory persistence.
241 ///
242 /// Sessions resolve a default store when this is not set.
243 pub memory_store: Option<Arc<dyn MemoryStore>>,
244 /// Host observers notified after successful durable memory writes.
245 pub memory_observers: Vec<Arc<dyn crate::memory::MemoryObserver>>,
246 /// Deferred file memory directory — constructed async in `build_session()`
247 pub(crate) file_memory_dir: Option<PathBuf>,
248 /// Optional session store for persistence
249 pub session_store: Option<Arc<dyn crate::store::SessionStore>>,
250 /// Host-owned destination for exact live tool-boundary checkpoints.
251 ///
252 /// This extension does not replace the Session store. Code captures one
253 /// canonical `SessionSnapshotV1` and its matching logical resume boundary,
254 /// then hands the immutable export to this sink. Host storage policy and
255 /// cross-process fencing remain outside Code.
256 pub session_checkpoint_export_sink:
257 Option<Arc<dyn crate::session_checkpoint::SessionCheckpointExportSink>>,
258 /// Deferred file session-store directory, initialized by the async builder.
259 pub(crate) file_session_store_dir: Option<PathBuf>,
260 /// Explicit session ID (auto-generated if not set)
261 pub session_id: Option<String>,
262 /// Multi-tenant identifier. Framework only transports this string;
263 /// the host decides what "tenant" means and how to
264 /// aggregate/bill on it. Emitted to hooks/traces, persisted in
265 /// `SessionData`, never interpreted by core.
266 pub tenant_id: Option<String>,
267 /// Identity of the principal that triggered this session (user id,
268 /// service account, etc). Treated as opaque.
269 pub principal: Option<String>,
270 /// Logical identifier of the agent template / definition the session
271 /// was instantiated from. Lets the host aggregate sessions by
272 /// "which agent recipe" independent of the concrete session id.
273 pub agent_template_id: Option<String>,
274 /// Distributed-trace correlation id. Propagated through hooks/traces
275 /// so a session's events join with upstream/downstream work in the
276 /// host's observability pipeline.
277 pub correlation_id: Option<String>,
278 /// Optional host-supplied budget / quota guard. The framework calls
279 /// into it before each LLM call (and reports actuals after) so the
280 /// host can refuse or rate-limit at the cluster level. Default is
281 /// `None` (no enforcement — equivalent to
282 /// [`NoopBudgetGuard`](crate::budget::NoopBudgetGuard)).
283 pub budget_guard: Option<Arc<dyn crate::budget::BudgetGuard>>,
284 /// Optional host-provided ID/Clock pair. Replaces the default
285 /// random-UUID + wall-clock pair, enabling deterministic replay
286 /// on another node. `None` keeps pre-P2 behaviour.
287 pub host_env: Option<Arc<crate::host_env::HostEnv>>,
288 /// Optional FIFO retention caps on the session's in-memory stores
289 /// (run records, run events, trace events, terminal subagent
290 /// tasks). `None` selects [`SessionRetentionLimits::default`](crate::retention::SessionRetentionLimits::default),
291 /// which is finite. Pass [`SessionRetentionLimits::unbounded`](crate::retention::SessionRetentionLimits::unbounded)
292 /// explicitly to retain everything.
293 pub retention_limits: Option<crate::retention::SessionRetentionLimits>,
294 /// Optional structured JSONL trajectory config.
295 ///
296 /// When set, a3s-code records user prompts, LLM turns, tool calls,
297 /// tool observations, token usage, and execution end status for RL
298 /// training or service data collection. If unset, the same config can
299 /// be enabled by `A3S_CODE_TRAJECTORY_PATH`.
300 pub rl_trajectory: Option<crate::rl_trajectory::RlTrajectoryConfig>,
301 /// Request token-level log probabilities from compatible LLM providers.
302 ///
303 /// This is off by default because many public providers reject logprob
304 /// requests with tool calls. Training/evaluation harnesses using compatible
305 /// OpenAI-style backends can enable it explicitly.
306 pub llm_logprobs: Option<bool>,
307 /// Number of alternative token logprobs to request per generated token.
308 pub llm_top_logprobs: Option<usize>,
309 /// Auto-save after each completed `send()` or default-history `stream()` call.
310 pub auto_save: bool,
311 /// Optional artifact retention limits for large tool/program outputs.
312 pub artifact_store_limits: Option<crate::tools::ArtifactStoreLimits>,
313 /// Host-authorized immutable content adapter for original Tool content.
314 ///
315 /// The adapter is session-scoped and Rust-only. Its secret-free binding is
316 /// persisted; a resumed session must re-inject the exact same binding.
317 pub immutable_content_adapter: Option<crate::tools::ImmutableContentAdapterSession>,
318 /// Host-pinned deterministic policy for projecting large tool results.
319 ///
320 /// `None` selects the conservative compatibility profile. The resolved
321 /// policy is persisted and cannot drift when the session is resumed.
322 pub tool_result_transform_policy: Option<crate::tools::ToolResultTransformPolicyV1>,
323 /// Typed model-facing Tool presentation policy.
324 ///
325 /// The resolved value is frozen per Run and persisted for exact resume.
326 /// It never changes the Session's governed executor or A3S Use generation.
327 pub tool_presentation_profile: Option<crate::tools::ToolPresentationProfileV1>,
328 /// Max consecutive parse errors before aborting (overrides default of 2).
329 /// `None` uses the `AgentConfig` default.
330 pub max_parse_retries: Option<u32>,
331 /// Per-tool execution timeout in milliseconds.
332 /// `None` = no timeout (default).
333 pub tool_timeout_ms: Option<u64>,
334 /// Per-model API HTTP timeout in milliseconds.
335 /// `None` = no timeout (default).
336 pub llm_api_timeout_ms: Option<u64>,
337 /// Circuit-breaker threshold: max consecutive LLM API failures before
338 /// aborting in non-streaming mode (overrides default of 3).
339 /// `None` uses the `AgentConfig` default.
340 pub circuit_breaker_threshold: Option<u32>,
341 /// Max consecutive identical tool signatures before the guard turns the
342 /// duplicate call into a failed tool observation.
343 ///
344 /// `None` uses the `AgentConfig` default. Hosts can raise this for long
345 /// research sessions where repeating a read/search with the same arguments
346 /// is wasteful but should not make the whole run brittle.
347 pub duplicate_tool_call_threshold: Option<u32>,
348 /// Optional concrete sandbox implementation.
349 ///
350 /// When set, `bash` tool commands are routed through this sandbox instead
351 /// of `std::process::Command`. The host application constructs and owns
352 /// the implementation (e.g., an A3S Box–backed handle).
353 pub sandbox_handle: Option<Arc<dyn crate::sandbox::BashSandbox>>,
354 /// Optional host-provided workspace backend.
355 ///
356 /// When set, built-in tools such as `read`, `write`, `ls`, and `bash`
357 /// execute against these workspace capabilities instead of assuming the
358 /// server-local filesystem. This is the primary extension point for DFS,
359 /// browser, container, and remote workspace deployments.
360 pub workspace_services: Option<Arc<crate::workspace::WorkspaceServices>>,
361 /// Optional session-owned semantic workspace retrieval configuration.
362 ///
363 /// Construction is asynchronous and ephemeral. Source chunks stay in the
364 /// workspace catalog, vectors stay in memory, and no vector state is
365 /// serialized with the session snapshot.
366 pub workspace_retrieval: Option<crate::workspace::WorkspaceRetrievalOptions>,
367 /// Enable auto-compaction when context usage exceeds threshold.
368 pub auto_compact: bool,
369 /// Context usage percentage threshold for auto-compaction (0.0 - 1.0).
370 /// Default: 0.80 (80%).
371 pub auto_compact_threshold: Option<f32>,
372 /// Model context window used for automatic compaction accounting.
373 ///
374 /// When omitted, the configured model's declared context limit is used,
375 /// falling back to the agent default when the model has no declaration.
376 pub max_context_tokens: Option<usize>,
377 /// Inject a continuation message when the LLM stops without completing the task.
378 /// `None` uses the `AgentConfig` default (true).
379 pub continuation_enabled: Option<bool>,
380 /// Maximum continuation injections per execution.
381 /// `None` uses the `AgentConfig` default (3).
382 pub max_continuation_turns: Option<u32>,
383 /// Maximum execution time in milliseconds.
384 /// `None` = no timeout (default).
385 /// When set, the execution loop will abort if it exceeds this duration.
386 pub max_execution_time_ms: Option<u64>,
387 /// Optional MCP manager for connecting to external MCP servers.
388 ///
389 /// When set, all tools from connected MCP servers are registered and
390 /// available during agent execution with names like `mcp__server__tool`.
391 pub mcp_manager: Option<Arc<crate::mcp::manager::McpManager>>,
392 /// Sampling temperature (0.0–1.0). Overrides the provider default.
393 pub temperature: Option<f32>,
394 /// Extended thinking budget in tokens (Anthropic only).
395 pub thinking_budget: Option<usize>,
396 /// Per-session tool round limit override.
397 ///
398 /// When set, overrides the agent-level `max_tool_rounds` for this session only.
399 /// Maps directly from [`AgentDefinition::max_steps`](crate::subagent::AgentDefinition::max_steps)
400 /// when creating sessions
401 /// via [`Agent::session_for_agent`].
402 pub max_tool_rounds: Option<usize>,
403 /// Per-session parallel fan-out limit override.
404 ///
405 /// Applies to delegated `task` fan-out, the legacy `parallel_task` alias,
406 /// plan wave execution, and safe parallel write batches.
407 pub max_parallel_tasks: Option<usize>,
408 /// Per-session automatic subagent delegation override.
409 pub auto_delegation: Option<crate::config::AutoDelegationConfig>,
410 /// Per-session switch for model-visible manual child-agent tools.
411 ///
412 /// This overlays the effective automatic delegation config instead of
413 /// replacing it, so callers can hide `task` and its compatibility alias
414 /// while preserving other delegation settings.
415 pub manual_delegation_enabled: Option<bool>,
416 /// Per-session kill switch for automatic parallel child-agent fan-out.
417 ///
418 /// This overlays the effective automatic delegation config instead of
419 /// replacing it, so callers can disable auto fan-out without disabling
420 /// automatic delegation itself.
421 pub auto_parallel_delegation: Option<bool>,
422 /// Slot-based system prompt customization.
423 ///
424 /// When set, overrides the agent-level prompt slots for this session.
425 /// Users can customize role, guidelines, response style, and extra instructions
426 /// without losing the core agentic capabilities.
427 pub prompt_slots: Option<SystemPromptSlots>,
428 /// Optional external hook executor.
429 ///
430 /// When set, it replaces the built-in `HookEngine` for this session.
431 pub hook_executor: Option<Arc<dyn crate::hooks::HookExecutor>>,
432}
433
434// ============================================================================
435// AgentSession
436// ============================================================================
437
438/// Workspace-bound session. All LLM and tool operations happen here.
439///
440/// History is automatically accumulated after each `send()` call and after
441/// `stream()` completes when no custom history is supplied.
442/// Use `history()` to retrieve the current conversation log.
443///
444/// Conversation operations are single-flight, including slash commands and
445/// checkpoint resume. An overlapping call returns
446/// [`CodeError::SessionBusy`](crate::error::CodeError::SessionBusy) immediately.
447/// A streaming operation remains active until its returned handle completes.
448pub struct AgentSession {
449 llm_client: Arc<dyn LlmClient>,
450 /// Provider-reported generation capacity shared by every loop and
451 /// host-direct tool call created for this session.
452 model_generation_admission: crate::llm::ModelGenerationAdmission,
453 /// Agent-wide execution admission shared across sibling sessions.
454 task_scheduler: Arc<crate::task_scheduler::TaskScheduler>,
455 /// Base priority for this session's top-level operations.
456 task_priority: crate::task_scheduler::TaskPriority,
457 tool_executor: Arc<ToolExecutor>,
458 /// Session-owned atomic host capability catalog. A Run pins one immutable
459 /// generation before its model definitions and executor are assembled.
460 capability_catalog: Arc<crate::capability::CapabilityCatalog>,
461 tool_context: ToolContext,
462 config: AgentConfig,
463 tool_result_transform_policy: crate::tools::ToolResultTransformPolicyV1,
464 /// Host provider plus the durable exact-generation package binding.
465 cognitive_context: Option<crate::cognitive_context::CognitiveContextSession>,
466 /// General-purpose providers supplied by the embedding host before Code
467 /// adds its own workspace-instruction and Skill-catalog providers.
468 /// Projected Knowledge must not silently compose with this ambient RAG
469 /// surface.
470 host_context_provider_names: std::collections::BTreeSet<String>,
471 workspace: PathBuf,
472 /// Unique session identifier.
473 session_id: String,
474 /// Internal conversation history, auto-updated after each `send()` and default-history `stream()`.
475 history: Arc<RwLock<Vec<Message>>>,
476 /// Fail-fast single-flight admission for transcript-affecting operations.
477 run_admission: Arc<run_admission::RunAdmission>,
478 /// Optional lane queue for priority-based tool execution.
479 command_queue: Option<Arc<crate::session_lane_queue::SessionLaneQueue>>,
480 /// Long-term memory handle.
481 ///
482 /// Built sessions resolve a default memory store. This remains optional for
483 /// compatibility with lower-level/manual construction paths.
484 memory: Option<Arc<crate::memory::AgentMemory>>,
485 /// Optional session store for persistence.
486 session_store: Option<Arc<dyn crate::store::SessionStore>>,
487 /// Host-owned destination for same-boundary portable checkpoints.
488 session_checkpoint_export_sink:
489 Option<Arc<dyn crate::session_checkpoint::SessionCheckpointExportSink>>,
490 /// Runtime-owned fields used to build lossless persistence generations.
491 persistence_state: Arc<RwLock<session_persistence::SessionPersistenceState>>,
492 /// Auto-save after each completed `send()` or default-history `stream()`.
493 auto_save: bool,
494 /// Hook engine for lifecycle event interception.
495 hook_engine: Arc<crate::hooks::HookEngine>,
496 /// Optional external hook executor. When set, replaces `hook_engine` as the
497 /// executor passed to each `AgentLoop`.
498 hook_executor: Option<Arc<dyn crate::hooks::HookExecutor>>,
499 /// Deferred init warning: emitted as PersistenceFailed on first send() if set.
500 init_warning: Option<String>,
501 /// Slash command registry for `/command` dispatch.
502 /// Uses interior mutability so commands can be registered on a shared `Arc<AgentSession>`.
503 command_registry: std::sync::Mutex<CommandRegistry>,
504 /// Model identifier for display (e.g., "anthropic/claude-sonnet-4-20250514").
505 model_name: String,
506 /// Session-private MCP manager used by live add/remove operations.
507 mcp_manager: Arc<crate::mcp::manager::McpManager>,
508 /// Read-only MCP sources inherited from the parent agent and session options.
509 inherited_mcp_managers: Vec<Arc<crate::mcp::manager::McpManager>>,
510 /// Ordered MCP capability sources inherited by delegated child runs.
511 mcp_managers: Vec<Arc<crate::mcp::manager::McpManager>>,
512 /// Shared agent registry — populated at session creation; extended via register_agent_dir().
513 agent_registry: Arc<crate::subagent::AgentRegistry>,
514 /// Cancellation token for the current operation (send/stream).
515 /// Stored so that cancel() can abort ongoing LLM calls.
516 cancel_token: Arc<tokio::sync::Mutex<Option<tokio_util::sync::CancellationToken>>>,
517 /// ID of the run currently attached to the active cancellation token.
518 current_run_id: Arc<tokio::sync::Mutex<Option<String>>>,
519 /// In-memory run snapshots and event replay buffer for this session.
520 run_store: Arc<crate::run::InMemoryRunStore>,
521 /// Materialized view of delegated subagent task lifecycle, populated from runtime events.
522 subagent_tasks: Arc<crate::subagent_task_tracker::InMemorySubagentTaskTracker>,
523 /// Currently executing tools observed from runtime events.
524 active_tools: Arc<tokio::sync::RwLock<HashMap<String, ActiveToolState>>>,
525 /// Compact execution traces for this session.
526 trace_sink: crate::trace::InMemoryTraceSink,
527 /// Structured completion evidence collected from agent and explicit verification runs.
528 verification_reports: Arc<RwLock<Vec<crate::verification::VerificationReport>>>,
529 /// Set once `close()` has been called. Subsequent send/stream calls
530 /// fast-fail with [`crate::error::CodeError::SessionClosed`].
531 closed: Arc<std::sync::atomic::AtomicBool>,
532 /// Session-level parent cancellation token.
533 ///
534 /// Every in-flight run (blocking send, stream, delegated subagent task)
535 /// derives its per-operation token from this one via `child_token()`,
536 /// so `session_cancel.cancel()` cascades to all of them. `close()` fires
537 /// this token first, after which any new `child_token()` returns an
538 /// already-cancelled token (defending against close/spawn races).
539 pub(crate) session_cancel: tokio_util::sync::CancellationToken,
540 /// Optional asynchronous semantic workspace index owned by this session.
541 workspace_retrieval: Option<Arc<crate::workspace::WorkspaceRetrievalRuntime>>,
542 /// Shared `Arc`-handle used by both [`AgentSession::close`] and the
543 /// parent [`Agent`]'s registry. The handle bundles every field needed
544 /// to perform the close sequence so the two entry points cannot drift.
545 close_handle: Arc<SessionCloseHandle>,
546 /// Runtime-mutable override for the budget guard. When set, takes
547 /// precedence over `config.budget_guard` on the next agent-loop
548 /// build. Lets SDK callers (Node especially) install a host-side
549 /// guard after `session()` has returned without ever putting a
550 /// JS callable into `SessionOptions`.
551 runtime_budget_guard: std::sync::Mutex<Option<Arc<dyn crate::budget::BudgetGuard>>>,
552 /// Multi-tenant label. Framework only carries the string; semantics
553 /// belong to the host.
554 pub(crate) tenant_id: Option<String>,
555 /// Principal that triggered the session (user / service / etc.).
556 pub(crate) principal: Option<String>,
557 /// Logical identifier of the agent template the session was
558 /// instantiated from.
559 pub(crate) agent_template_id: Option<String>,
560 /// Distributed-trace correlation id propagated to hooks / traces.
561 pub(crate) correlation_id: Option<String>,
562}
563
564// ============================================================================
565// Tests
566// ============================================================================
567
568#[cfg(test)]
569mod capability_runtime_tests;
570#[cfg(test)]
571mod replacement_tests;
572#[cfg(test)]
573mod retrieval_qa_tests;
574#[cfg(test)]
575mod retrieval_tests;
576#[cfg(test)]
577mod tests;