Skip to main content

a3s_code_core/
lib.rs

1//! A3S Code Core Library
2//!
3//! Harness-driven runtime for coding agents.
4//!
5//! `Agent` and `AgentSession` are the primary 2.0 API. Lower-level session
6//! runtime state is internal; persistence data flows through `store::SessionData`.
7//!
8//! ## Quick Start
9//!
10//! ```rust,no_run
11//! use a3s_code_core::{Agent, AgentEvent};
12//!
13//! # async fn run() -> anyhow::Result<()> {
14//! // From an ACL-compatible config file path (.acl)
15//! let agent = Agent::new("agent.acl").await?;
16//!
17//! // Create a workspace-bound session
18//! let session = agent.session_async("/my-project", None).await?;
19//!
20//! // Non-streaming
21//! let result = session.send("What files handle auth?", None).await?;
22//! println!("{}", result.text);
23//!
24//! // Streaming (AgentEvent is #[non_exhaustive])
25//! let (mut rx, _handle) = session.stream("Refactor auth", None).await?;
26//! while let Some(event) = rx.recv().await {
27//!     match event {
28//!         AgentEvent::TextDelta { text } => print!("{text}"),
29//!         AgentEvent::End { .. } => break,
30//!         _ => {} // required: #[non_exhaustive]
31//!     }
32//! }
33//! # Ok(())
34//! # }
35//! ```
36//!
37//! ## Disposable Workers
38//!
39//! ```rust,no_run
40//! use a3s_code_core::{Agent, SessionOptions, WorkerAgentSpec};
41//!
42//! # async fn run() -> anyhow::Result<()> {
43//! let agent = Agent::new("agent.acl").await?;
44//! let frontend = WorkerAgentSpec::implementer(
45//!     "frontend-cow",
46//!     "Small verified frontend fixes",
47//! )
48//! .with_model_ref("openai/gpt-4o")
49//! .with_max_steps(24);
50//!
51//! let session = agent.session_async(
52//!     "/my-project",
53//!     Some(SessionOptions::new().with_worker_agent(frontend)),
54//! ).await?;
55//! # Ok(())
56//! # }
57//! ```
58//!
59//! ## Architecture
60//!
61//! ```text
62//! Agent (config-driven facade)
63//!   +-- AgentSession (workspace-bound execution API)
64//!       +-- internal turn runner
65//!       +-- ContextAssembler / ContextProvider
66//!       +-- ToolSelector
67//!       +-- ToolExecutor
68//!       +-- ProgramExecutor (PTC)
69//!       +-- SkillRegistry
70//!       +-- Permission / confirmation
71//!       +-- Trace / artifacts / verification evidence
72//!
73//! Advanced infrastructure:
74//!   +-- optional lane queues for explicit external/hybrid dispatch
75//! ```
76
77pub(crate) mod agent;
78pub(crate) mod agent_api;
79pub mod agent_protocol;
80pub mod agent_protocol_harness;
81pub mod agent_protocol_host;
82pub mod budget;
83pub mod capability;
84pub(crate) mod child_run;
85pub mod code_intelligence;
86pub mod cognitive_context;
87pub mod commands;
88pub(crate) mod compaction;
89pub mod config;
90pub mod context;
91pub mod dynamic_workflow;
92pub mod embedding;
93pub mod error;
94pub mod event_protocol;
95pub mod flow_graph;
96pub(crate) mod git;
97pub mod harness_evidence;
98pub mod hitl;
99pub mod hooks;
100pub mod host_env;
101pub(crate) mod language;
102pub mod llm;
103pub mod loop_checkpoint;
104pub mod mcp;
105pub mod memory;
106pub mod orchestration;
107pub(crate) mod ordered_parallel;
108pub mod permissions;
109pub mod planning;
110pub mod program;
111pub(crate) mod prompts;
112pub mod queue;
113pub mod release;
114pub mod retention;
115pub(crate) mod retry;
116pub mod rl_trajectory;
117pub mod run;
118pub(crate) mod safety_gate;
119pub mod sandbox;
120#[cfg(feature = "headless-search")]
121pub mod search_runtime;
122pub mod security;
123#[cfg(feature = "serve")]
124pub mod serve;
125pub mod session_checkpoint;
126pub(crate) mod session_lane_queue;
127pub mod skills;
128pub(crate) mod sse;
129pub mod state_graph;
130pub mod store;
131pub mod subagent;
132pub mod subagent_task_tracker;
133pub mod task_scheduler;
134pub mod telemetry;
135#[cfg(feature = "telemetry")]
136pub mod telemetry_otel;
137#[cfg(test)]
138pub(crate) mod test_support;
139pub(crate) mod text;
140pub(crate) mod tool_confirmation;
141pub mod tools;
142pub mod trace;
143pub mod verification;
144pub mod workspace;
145
146// Re-export key types at crate root for ergonomic usage
147pub use agent::{AgentEvent, AgentResult};
148pub use agent_api::{
149    Agent, AgentRunSpawn, AgentSession, ProjectedFlowHandle, ProjectedUiHandle, ReadFileOptions,
150    SessionBuilder, SessionOptions, ToolCallResult,
151};
152pub use agent_protocol::{
153    AgentProtocolChangeSetRequestV1, AgentProtocolChangeSetV1, AgentProtocolCommandActionV1,
154    AgentProtocolCommandReceiptV1, AgentProtocolCommandV1, AgentProtocolError,
155    AgentProtocolEventPageRequestV1, AgentProtocolEventPageV1, AgentProtocolEventRecordV1,
156    AgentProtocolRunCancelV1, AgentProtocolRunIdentityV1, AgentProtocolRunRecoverExactV1,
157    AgentProtocolRunRecoverV1, AgentProtocolRunStartV1, AgentProtocolRunStateV1,
158    AGENT_PROTOCOL_CHANGE_SET_ENCODING_V1, AGENT_PROTOCOL_CHANGE_SET_FORMAT_V1,
159    AGENT_PROTOCOL_CHANGE_SET_HTTP_PATH_V1, AGENT_PROTOCOL_COMMAND_HTTP_PATH_V1,
160    AGENT_PROTOCOL_EVENT_PAGE_HTTP_PATH_V1, AGENT_PROTOCOL_MAX_CHANGE_SET_BYTES,
161    AGENT_PROTOCOL_MAX_CHANGE_SET_RESPONSE_BYTES, AGENT_PROTOCOL_MAX_EVENTS_PER_PAGE,
162    AGENT_PROTOCOL_MAX_EVENT_METADATA_BYTES, AGENT_PROTOCOL_MAX_EVENT_PAGE_BYTES,
163    AGENT_PROTOCOL_MAX_EVENT_PAYLOAD_BYTES, AGENT_PROTOCOL_MAX_EVENT_RECORD_BYTES,
164    AGENT_PROTOCOL_MAX_EVENT_TYPE_BYTES, AGENT_PROTOCOL_MAX_ID_BYTES,
165    AGENT_PROTOCOL_MAX_PROMPT_BYTES, AGENT_PROTOCOL_MAX_REASON_BYTES, AGENT_PROTOCOL_V1,
166};
167pub use agent_protocol_harness::{
168    AgentProtocolCheckpointRecoveryError, AgentProtocolHarness, AgentProtocolHarnessError,
169    AGENT_PROTOCOL_HARNESS_MAX_SESSIONS,
170};
171pub use agent_protocol_host::{
172    AgentProtocolExactRecoveryError, AgentProtocolHost, AgentProtocolHostError,
173};
174pub use code_intelligence::{
175    CodeDiagnostic, CodeDiagnosticSeverity, CodeIntelligenceCapabilities, CodeIntelligenceError,
176    CodeIntelligenceLanguageStatus, CodeIntelligenceResult, CodeIntelligenceState,
177    CodeIntelligenceStatus, CodeLocation, CodePosition, CodeQueryResult, CodeRange, CodeSymbolKind,
178    DocumentRevision, DocumentSnapshot, DocumentSymbol, LanguageId, LocalCodeIntelligence,
179    NavigationKind, SymbolInformation, WorkspaceCodeIntelligence,
180};
181pub use cognitive_context::{
182    CognitiveContextDocumentV1, CognitiveContextError, CognitiveContextLimits,
183    CognitiveContextProvider, CognitiveContextRequestV1, CognitiveContextResponseV1,
184    CognitiveContextResult, CognitiveContextSession, CognitiveKnowledgeBindingV1,
185    CognitiveKnowledgeCitationV1, CognitivePackageBindingV1,
186    COGNITIVE_CONTEXT_REQUEST_DIGEST_DOMAIN, COGNITIVE_CONTEXT_REQUEST_SCHEMA,
187    COGNITIVE_CONTEXT_RESPONSE_SCHEMA, COGNITIVE_KNOWLEDGE_BINDING_SCHEMA,
188    COGNITIVE_PACKAGE_BINDING_SCHEMA, OKF_KNOWLEDGE_CITATION_SCHEMA,
189    OKF_KNOWLEDGE_READ_REQUEST_SCHEMA, OKF_KNOWLEDGE_SEARCH_REQUEST_SCHEMA,
190};
191pub use config::{
192    AutoDelegationConfig, CodeConfig, ModelConfig, ModelCost, ModelLimit, ModelModalities,
193    OsConfig, ProviderConfig,
194};
195pub use dynamic_workflow::{
196    dynamic_workflow_store_path, DynamicWorkflowRuntime, DynamicWorkflowScriptLimits,
197    DynamicWorkflowTool, DYNAMIC_WORKFLOW_STORE_RELATIVE_PATH,
198};
199pub use embedding::{
200    EmbeddingBatchRequest, EmbeddingBatchResponse, EmbeddingError, EmbeddingExecution,
201    EmbeddingExecutor, EmbeddingExecutorConfig, EmbeddingFailureKind, EmbeddingInput,
202    EmbeddingNormalization, EmbeddingProvider, EmbeddingProviderDescriptor, EmbeddingProviderError,
203    EmbeddingResult, EmbeddingVector,
204};
205pub use error::SessionBuildResource;
206pub use error::{CodeError, Result};
207pub use event_protocol::{
208    run_event_envelope_v1, AgentEventProjectionV1, AgentEventTypeV1, EventEnvelopeV1,
209    EventProtocolError, AGENT_EVENT_TYPES_V1, EVENT_ENVELOPE_V1_VERSION,
210};
211pub use flow_graph::{
212    run_object_id as flow_run_object_id, step_object_id as flow_step_object_id,
213    FileFlowDecisionLedger, FlowDecision, FlowDecisionClaimOutcome, FlowDecisionDispatchError,
214    FlowDecisionDispatcher, FlowDecisionHealthSnapshot, FlowDecisionHealthStatus,
215    FlowDecisionLedger, FlowDecisionRequest, FlowDecisionSink, FlowDecisionStep,
216    FlowGraphHealthSnapshot, FlowGraphHealthStatus, FlowGraphObserver, MemoryFlowDecisionLedger,
217    FLOW_GRAPH_SOURCE,
218};
219pub use harness_evidence::{
220    HarnessEvidenceError, ModelInputKindV1, ModelInputSnapshotV1, ModelPresentationApplicationV1,
221    ModelPresentationSnapshotV1, ModelUsageSnapshotV1, RunCapabilitySnapshotV1,
222    RunPolicyCeilingSnapshotV1, ToolRequestOriginV1, ToolRequestSnapshotV1,
223    ToolResultContextUsageV1, WorkspaceCapabilitySnapshotV1,
224    WorkspaceRetrievalCapabilitySnapshotV1, MODEL_INPUT_SNAPSHOT_V1_SCHEMA,
225    MODEL_PRESENTATION_SNAPSHOT_V1_SCHEMA, MODEL_USAGE_SNAPSHOT_V1_SCHEMA,
226    RUN_CAPABILITY_SNAPSHOT_V1_SCHEMA, TOOL_REQUEST_SNAPSHOT_V1_SCHEMA,
227};
228pub use llm::{
229    clear_http_metrics_callback, set_http_metrics_callback, AnthropicClient, Attachment,
230    ContentBlock, HttpMetricsCallback, HttpMetricsRecord, ImageSource, LlmClient, LlmResponse,
231    Message, ModelGenerationAdmission, ModelGenerationAdmissionError, ModelGenerationConcurrency,
232    ModelGenerationPermit, OpenAiClient, TokenUsage,
233};
234pub use orchestration::{
235    execute_loop, execute_pipeline, execute_steps_parallel, execute_steps_parallel_resumable,
236    AgentExecutor, AgentStepSpec, BudgetSnapshot, LoopDecision, PipelineStage, StepOutcome,
237    Workflow, WorkflowBudget, WorkflowBuilder, WorkflowCheckpoint, WorkflowEvent,
238    WorkflowStepRecord, WORKFLOW_CHECKPOINT_SCHEMA_VERSION,
239};
240pub use prompts::{AgentStyle, DetectionConfidence, PlanningMode, SystemPromptSlots};
241pub use rl_trajectory::{RlTrajectoryConfig, RlTrajectoryMode, RlTrajectoryRecorder};
242pub use run::{
243    ActiveToolSnapshot, InMemoryRunStore, RunEventRecord, RunHandle, RunRecord, RunReservation,
244    RunSnapshot, RunStatus, RunWorkspaceChangeSet, RunWorkspaceChangeSetError,
245};
246pub use session_checkpoint::{
247    SessionCheckpointDescriptorV1, SessionCheckpointError, SessionCheckpointExportSink,
248    SessionCheckpointExportV1, SessionCheckpointPayloadV1, SessionLogicalResumeEvidenceV1,
249    SessionSnapshotEvidenceV1, SESSION_CHECKPOINT_DESCRIPTOR_SCHEMA_V1,
250    SESSION_CHECKPOINT_ENCODING_V1, SESSION_CHECKPOINT_FORMAT_V1,
251    SESSION_CHECKPOINT_LOGICAL_RESUME_SEMANTICS_V1, SESSION_CHECKPOINT_MAX_CONTENT_BYTES,
252    SESSION_CHECKPOINT_MEDIA_TYPE_V1, SESSION_CHECKPOINT_PAYLOAD_SCHEMA_V1,
253    SESSION_LOGICAL_RESUME_EVIDENCE_SCHEMA_V1, SESSION_SNAPSHOT_EVIDENCE_SCHEMA_V1,
254};
255pub use state_graph::{
256    graph_event_head, Behavior, BehaviorContext, BehaviorError, EventFilter, ExternalEvent,
257    ExternalProjectionOutcome, FileGraphEventStore, FnBehavior, GraphDiff, GraphEvent,
258    GraphEventRecord, GraphEventStore, GraphObject, GraphPatch, GraphRelation, GraphRuntime,
259    GraphSaveOutcome, MemoryGraphEventStore, ObjectId, PatchOperation, RelationId, ReplayError,
260    RuntimeError as GraphRuntimeError, RuntimeLimits, StateGraph, GRAPH_EVENT_SCHEMA_VERSION,
261};
262pub use subagent::{
263    AgentDefinition, AgentRegistry, CattleAgentKind, CattleAgentSpec, ConfirmationInheritance,
264    WorkerAgentKind, WorkerAgentSpec,
265};
266pub use subagent_task_tracker::{
267    InMemorySubagentTaskTracker, SubagentProgressEntry, SubagentStatus, SubagentTaskSnapshot,
268};
269pub use task_scheduler::{
270    TaskPriority, TaskPriorityCounts, TaskScheduler, TaskSchedulerConfig, TaskSchedulerError,
271    TaskSchedulerStats,
272};
273pub use tools::{
274    ImmutableContentAdapter, ImmutableContentAdapterBindingV1, ImmutableContentAdapterSession,
275    ImmutableContentDescriptorV1, ImmutableContentError, ImmutableContentKindV1,
276    ImmutableContentReferenceV1, ImmutableContentResult, ImmutableContentWriteRequestV1,
277    ToolPresentationError, ToolPresentationModeV1, ToolPresentationProfileV1,
278    IMMUTABLE_CONTENT_ADAPTER_BINDING_SCHEMA_V1, IMMUTABLE_CONTENT_DESCRIPTOR_SCHEMA_V1,
279    IMMUTABLE_CONTENT_REFERENCE_SCHEMA_V1, TOOL_PRESENTATION_PROFILE_V1_SCHEMA,
280    TOOL_RESULT_CONTENT_MEDIA_TYPE,
281};
282pub use tools::{ToolCapabilities, ToolErrorKind, ToolOutputKind};
283pub use workspace::{
284    ChunkCatalogLimits, ChunkCatalogSnapshot, ChunkingConfig, CommandOutput, CommandOutputObserver,
285    CommandOutputSummary, CommandRequest, CustomWorkspaceChunkingStrategy,
286    FixedWindowChunkingOptions, LexicalSearchHit, LexicalSearchRequest, LexicalSearchResult,
287    LocalWorkspaceAccessPolicy, LocalWorkspaceBackend, LocalWorkspaceFile,
288    LocalWorkspaceFileStatus, LocalWorkspaceManifest, LocalWorkspaceManifestSnapshot,
289    ManifestWorkspaceBackend, RecentWorkspaceFile, RecursiveChunkingOptions, RemoteGitBackend,
290    RemoteGitBackendConfig, RemoteGitConflict, VirtualPathResolver, WorkspaceCapabilities,
291    WorkspaceChunk, WorkspaceChunkCatalog, WorkspaceChunkId, WorkspaceChunkRange,
292    WorkspaceChunkingError, WorkspaceChunkingInput, WorkspaceChunkingStrategy,
293    WorkspaceCommandRunner, WorkspaceDirEntry, WorkspaceEligibilityPolicy,
294    WorkspaceEmbeddingBatchMetrics, WorkspaceError, WorkspaceFileChange, WorkspaceFileChangeKind,
295    WorkspaceFileSystem, WorkspaceFileSystemExt, WorkspaceFileType, WorkspaceGit,
296    WorkspaceGitBranch, WorkspaceGitCheckoutOutput, WorkspaceGitCheckoutRequest,
297    WorkspaceGitCommit, WorkspaceGitCreateBranchRequest, WorkspaceGitCreateWorktreeRequest,
298    WorkspaceGitDiffRequest, WorkspaceGitRemote, WorkspaceGitRemoveWorktreeRequest,
299    WorkspaceGitStash, WorkspaceGitStashProvider, WorkspaceGitStashRequest, WorkspaceGitStatus,
300    WorkspaceGitWorktree, WorkspaceGitWorktreeMutation, WorkspaceGitWorktreeProvider,
301    WorkspaceGlobRequest, WorkspaceGlobResult, WorkspaceGrepOutcome, WorkspaceGrepRequest,
302    WorkspaceGrepResult, WorkspaceHybridChannelRank, WorkspaceHybridChannelStatus,
303    WorkspaceHybridFallbackReason, WorkspaceHybridSearchHit, WorkspaceHybridSearchRequest,
304    WorkspaceHybridSearchResult, WorkspaceIndexError, WorkspacePath, WorkspacePathResolver,
305    WorkspaceRef, WorkspaceRerankAlgorithm, WorkspaceRerankFallbackReason, WorkspaceRerankMode,
306    WorkspaceRerankOptions, WorkspaceRerankStatus, WorkspaceResult, WorkspaceRetrievalChannel,
307    WorkspaceRetrievalError, WorkspaceRetrievalOptions, WorkspaceRetrievalPhase,
308    WorkspaceRetrievalResult, WorkspaceRetrievalRuntime, WorkspaceRetrievalStatus, WorkspaceSearch,
309    WorkspaceSemanticFallbackReason, WorkspaceSemanticIndexLimits, WorkspaceSemanticSearchHit,
310    WorkspaceSemanticSearchRequest, WorkspaceSemanticSearchResult, WorkspaceServices,
311    WorkspaceServicesBuilder, WorkspaceTextRange, WorkspaceTextReader, WorkspaceVersionConflict,
312    WorkspaceWriteOutcome,
313};
314#[cfg(feature = "s3")]
315pub use workspace::{S3BackendConfig, S3WorkspaceBackend};