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 use_runtime_tasks;
144pub mod verification;
145pub mod workspace;
146
147// Re-export key types at crate root for ergonomic usage
148pub use agent::{AgentEvent, AgentResult};
149pub use agent_api::{
150    Agent, AgentRunSpawn, AgentSession, ProjectedFlowHandle, ProjectedUiHandle, ReadFileOptions,
151    SessionBuilder, SessionOptions, ToolCallResult,
152};
153pub use agent_protocol::{
154    AgentProtocolChangeSetRequestV1, AgentProtocolChangeSetV1, AgentProtocolCommandActionV1,
155    AgentProtocolCommandReceiptV1, AgentProtocolCommandV1, AgentProtocolError,
156    AgentProtocolEventPageRequestV1, AgentProtocolEventPageV1, AgentProtocolEventRecordV1,
157    AgentProtocolRunCancelV1, AgentProtocolRunIdentityV1, AgentProtocolRunRecoverExactV1,
158    AgentProtocolRunRecoverV1, AgentProtocolRunStartV1, AgentProtocolRunStateV1,
159    AGENT_PROTOCOL_CHANGE_SET_ENCODING_V1, AGENT_PROTOCOL_CHANGE_SET_FORMAT_V1,
160    AGENT_PROTOCOL_CHANGE_SET_HTTP_PATH_V1, AGENT_PROTOCOL_COMMAND_HTTP_PATH_V1,
161    AGENT_PROTOCOL_EVENT_PAGE_HTTP_PATH_V1, AGENT_PROTOCOL_MAX_CHANGE_SET_BYTES,
162    AGENT_PROTOCOL_MAX_CHANGE_SET_RESPONSE_BYTES, AGENT_PROTOCOL_MAX_EVENTS_PER_PAGE,
163    AGENT_PROTOCOL_MAX_EVENT_METADATA_BYTES, AGENT_PROTOCOL_MAX_EVENT_PAGE_BYTES,
164    AGENT_PROTOCOL_MAX_EVENT_PAYLOAD_BYTES, AGENT_PROTOCOL_MAX_EVENT_RECORD_BYTES,
165    AGENT_PROTOCOL_MAX_EVENT_TYPE_BYTES, AGENT_PROTOCOL_MAX_ID_BYTES,
166    AGENT_PROTOCOL_MAX_PROMPT_BYTES, AGENT_PROTOCOL_MAX_REASON_BYTES, AGENT_PROTOCOL_V1,
167};
168pub use agent_protocol_harness::{
169    AgentProtocolCheckpointRecoveryError, AgentProtocolHarness, AgentProtocolHarnessError,
170    AGENT_PROTOCOL_HARNESS_MAX_SESSIONS,
171};
172pub use agent_protocol_host::{
173    AgentProtocolExactRecoveryError, AgentProtocolHost, AgentProtocolHostError,
174};
175pub use code_intelligence::{
176    CodeDiagnostic, CodeDiagnosticSeverity, CodeIntelligenceCapabilities, CodeIntelligenceError,
177    CodeIntelligenceLanguageStatus, CodeIntelligenceResult, CodeIntelligenceState,
178    CodeIntelligenceStatus, CodeLocation, CodePosition, CodeQueryResult, CodeRange, CodeSymbolKind,
179    DocumentRevision, DocumentSnapshot, DocumentSymbol, LanguageId, LocalCodeIntelligence,
180    NavigationKind, SymbolInformation, WorkspaceCodeIntelligence,
181};
182pub use cognitive_context::{
183    CognitiveContextDocumentV1, CognitiveContextError, CognitiveContextLimits,
184    CognitiveContextProvider, CognitiveContextRequestV1, CognitiveContextResponseV1,
185    CognitiveContextResult, CognitiveContextSession, CognitiveKnowledgeBindingV1,
186    CognitiveKnowledgeCitationV1, CognitivePackageBindingV1,
187    COGNITIVE_CONTEXT_REQUEST_DIGEST_DOMAIN, COGNITIVE_CONTEXT_REQUEST_SCHEMA,
188    COGNITIVE_CONTEXT_RESPONSE_SCHEMA, COGNITIVE_KNOWLEDGE_BINDING_SCHEMA,
189    COGNITIVE_PACKAGE_BINDING_SCHEMA, OKF_KNOWLEDGE_CITATION_SCHEMA,
190    OKF_KNOWLEDGE_READ_REQUEST_SCHEMA, OKF_KNOWLEDGE_SEARCH_REQUEST_SCHEMA,
191};
192pub use config::{
193    AutoDelegationConfig, CodeConfig, ModelConfig, ModelCost, ModelLimit, ModelModalities,
194    OsConfig, ProviderConfig,
195};
196pub use dynamic_workflow::{
197    dynamic_workflow_store_path, DynamicWorkflowRuntime, DynamicWorkflowScriptLimits,
198    DynamicWorkflowTool, DYNAMIC_WORKFLOW_STORE_RELATIVE_PATH,
199};
200pub use embedding::{
201    EmbeddingBatchRequest, EmbeddingBatchResponse, EmbeddingError, EmbeddingExecution,
202    EmbeddingExecutor, EmbeddingExecutorConfig, EmbeddingFailureKind, EmbeddingInput,
203    EmbeddingNormalization, EmbeddingProvider, EmbeddingProviderDescriptor, EmbeddingProviderError,
204    EmbeddingResult, EmbeddingVector,
205};
206pub use error::SessionBuildResource;
207pub use error::{CodeError, Result};
208pub use event_protocol::{
209    run_event_envelope_v1, AgentEventProjectionV1, AgentEventTypeV1, EventEnvelopeV1,
210    EventProtocolError, AGENT_EVENT_TYPES_V1, EVENT_ENVELOPE_V1_VERSION,
211};
212pub use flow_graph::{
213    run_object_id as flow_run_object_id, step_object_id as flow_step_object_id,
214    FileFlowDecisionLedger, FlowDecision, FlowDecisionClaimOutcome, FlowDecisionDispatchError,
215    FlowDecisionDispatcher, FlowDecisionHealthSnapshot, FlowDecisionHealthStatus,
216    FlowDecisionLedger, FlowDecisionRequest, FlowDecisionSink, FlowDecisionStep,
217    FlowGraphHealthSnapshot, FlowGraphHealthStatus, FlowGraphObserver, MemoryFlowDecisionLedger,
218    FLOW_GRAPH_SOURCE,
219};
220pub use harness_evidence::{
221    HarnessEvidenceError, ModelInputKindV1, ModelInputSnapshotV1, ModelPresentationApplicationV1,
222    ModelPresentationSnapshotV1, ModelUsageSnapshotV1, RunCapabilitySnapshotV1,
223    RunPolicyCeilingSnapshotV1, ToolRequestOriginV1, ToolRequestSnapshotV1,
224    ToolResultContextUsageV1, WorkspaceCapabilitySnapshotV1,
225    WorkspaceRetrievalCapabilitySnapshotV1, MODEL_INPUT_SNAPSHOT_V1_SCHEMA,
226    MODEL_PRESENTATION_SNAPSHOT_V1_SCHEMA, MODEL_USAGE_SNAPSHOT_V1_SCHEMA,
227    RUN_CAPABILITY_SNAPSHOT_V1_SCHEMA, TOOL_REQUEST_SNAPSHOT_V1_SCHEMA,
228};
229pub use llm::{
230    clear_http_metrics_callback, set_http_metrics_callback, AnthropicClient, Attachment,
231    ContentBlock, HttpMetricsCallback, HttpMetricsRecord, ImageSource, LlmClient, LlmResponse,
232    Message, ModelGenerationAdmission, ModelGenerationAdmissionError, ModelGenerationConcurrency,
233    ModelGenerationPermit, OpenAiClient, TokenUsage,
234};
235pub use orchestration::{
236    execute_loop, execute_pipeline, execute_steps_parallel, execute_steps_parallel_resumable,
237    AgentExecutor, AgentStepSpec, BudgetSnapshot, LoopDecision, PipelineStage, StepOutcome,
238    Workflow, WorkflowBudget, WorkflowBuilder, WorkflowCheckpoint, WorkflowEvent,
239    WorkflowStepRecord, WORKFLOW_CHECKPOINT_SCHEMA_VERSION,
240};
241pub use prompts::{AgentStyle, DetectionConfidence, PlanningMode, SystemPromptSlots};
242pub use rl_trajectory::{RlTrajectoryConfig, RlTrajectoryMode, RlTrajectoryRecorder};
243pub use run::{
244    ActiveToolSnapshot, InMemoryRunStore, RunEventRecord, RunHandle, RunRecord, RunReservation,
245    RunSnapshot, RunStatus, RunWorkspaceChangeSet, RunWorkspaceChangeSetError,
246};
247pub use session_checkpoint::{
248    SessionCheckpointDescriptorV1, SessionCheckpointError, SessionCheckpointExportSink,
249    SessionCheckpointExportV1, SessionCheckpointPayloadV1, SessionLogicalResumeEvidenceV1,
250    SessionSnapshotEvidenceV1, SESSION_CHECKPOINT_DESCRIPTOR_SCHEMA_V1,
251    SESSION_CHECKPOINT_ENCODING_V1, SESSION_CHECKPOINT_FORMAT_V1,
252    SESSION_CHECKPOINT_LOGICAL_RESUME_SEMANTICS_V1, SESSION_CHECKPOINT_MAX_CONTENT_BYTES,
253    SESSION_CHECKPOINT_MEDIA_TYPE_V1, SESSION_CHECKPOINT_PAYLOAD_SCHEMA_V1,
254    SESSION_LOGICAL_RESUME_EVIDENCE_SCHEMA_V1, SESSION_SNAPSHOT_EVIDENCE_SCHEMA_V1,
255};
256pub use state_graph::{
257    graph_event_head, Behavior, BehaviorContext, BehaviorError, EventFilter, ExternalEvent,
258    ExternalProjectionOutcome, FileGraphEventStore, FnBehavior, GraphDiff, GraphEvent,
259    GraphEventRecord, GraphEventStore, GraphObject, GraphPatch, GraphRelation, GraphRuntime,
260    GraphSaveOutcome, MemoryGraphEventStore, ObjectId, PatchOperation, RelationId, ReplayError,
261    RuntimeError as GraphRuntimeError, RuntimeLimits, StateGraph, GRAPH_EVENT_SCHEMA_VERSION,
262};
263pub use subagent::{
264    AgentDefinition, AgentRegistry, CattleAgentKind, CattleAgentSpec, ConfirmationInheritance,
265    WorkerAgentKind, WorkerAgentSpec,
266};
267pub use subagent_task_tracker::{
268    InMemorySubagentTaskTracker, SubagentProgressEntry, SubagentStatus, SubagentTaskSnapshot,
269};
270pub use task_scheduler::{
271    TaskPriority, TaskPriorityCounts, TaskScheduler, TaskSchedulerConfig, TaskSchedulerError,
272    TaskSchedulerStats,
273};
274pub use tools::{
275    ImmutableContentAdapter, ImmutableContentAdapterBindingV1, ImmutableContentAdapterSession,
276    ImmutableContentDescriptorV1, ImmutableContentError, ImmutableContentKindV1,
277    ImmutableContentReferenceV1, ImmutableContentResult, ImmutableContentWriteRequestV1,
278    ToolPresentationError, ToolPresentationModeV1, ToolPresentationProfileV1,
279    IMMUTABLE_CONTENT_ADAPTER_BINDING_SCHEMA_V1, IMMUTABLE_CONTENT_DESCRIPTOR_SCHEMA_V1,
280    IMMUTABLE_CONTENT_REFERENCE_SCHEMA_V1, TOOL_PRESENTATION_PROFILE_V1_SCHEMA,
281    TOOL_RESULT_CONTENT_MEDIA_TYPE,
282};
283pub use tools::{ToolCapabilities, ToolErrorKind, ToolOutputKind};
284pub use use_runtime_tasks::{
285    UsePlanScope, UsePlanScopeKind, UseProjectedLifecycleIdentity, UseRuntimeTaskDispatcher,
286    UseRuntimeTaskError, UseRuntimeTaskExecutionV1, UseRuntimeTaskProjectionAdapter,
287    UseRuntimeTaskProjectionV1, UseRuntimeTaskRequestV1, UseRuntimeTaskResult,
288    MAX_USE_RUNTIME_TASK_ARGUMENTS, MAX_USE_RUNTIME_TASK_ARGUMENT_BYTES,
289    MAX_USE_RUNTIME_TASK_OUTPUT_BYTES, MAX_USE_RUNTIME_TASK_TIMEOUT_MS,
290    USE_RUNTIME_TASK_REQUEST_SCHEMA, USE_RUNTIME_TASK_RESULT_SCHEMA,
291};
292pub use workspace::{
293    ChunkCatalogLimits, ChunkCatalogSnapshot, ChunkingConfig, CommandOutput, CommandOutputObserver,
294    CommandOutputSummary, CommandRequest, CustomWorkspaceChunkingStrategy,
295    FixedWindowChunkingOptions, LexicalSearchHit, LexicalSearchRequest, LexicalSearchResult,
296    LocalWorkspaceAccessPolicy, LocalWorkspaceBackend, LocalWorkspaceFile,
297    LocalWorkspaceFileStatus, LocalWorkspaceManifest, LocalWorkspaceManifestSnapshot,
298    ManifestWorkspaceBackend, RecentWorkspaceFile, RecursiveChunkingOptions, RemoteGitBackend,
299    RemoteGitBackendConfig, RemoteGitConflict, VirtualPathResolver, WorkspaceCapabilities,
300    WorkspaceChunk, WorkspaceChunkCatalog, WorkspaceChunkId, WorkspaceChunkRange,
301    WorkspaceChunkingError, WorkspaceChunkingInput, WorkspaceChunkingStrategy,
302    WorkspaceCommandRunner, WorkspaceDirEntry, WorkspaceEligibilityPolicy,
303    WorkspaceEmbeddingBatchMetrics, WorkspaceError, WorkspaceFileChange, WorkspaceFileChangeKind,
304    WorkspaceFileSystem, WorkspaceFileSystemExt, WorkspaceFileType, WorkspaceGit,
305    WorkspaceGitBranch, WorkspaceGitCheckoutOutput, WorkspaceGitCheckoutRequest,
306    WorkspaceGitCommit, WorkspaceGitCreateBranchRequest, WorkspaceGitCreateWorktreeRequest,
307    WorkspaceGitDiffRequest, WorkspaceGitRemote, WorkspaceGitRemoveWorktreeRequest,
308    WorkspaceGitStash, WorkspaceGitStashProvider, WorkspaceGitStashRequest, WorkspaceGitStatus,
309    WorkspaceGitWorktree, WorkspaceGitWorktreeMutation, WorkspaceGitWorktreeProvider,
310    WorkspaceGlobRequest, WorkspaceGlobResult, WorkspaceGrepOutcome, WorkspaceGrepRequest,
311    WorkspaceGrepResult, WorkspaceHybridChannelRank, WorkspaceHybridChannelStatus,
312    WorkspaceHybridFallbackReason, WorkspaceHybridSearchHit, WorkspaceHybridSearchRequest,
313    WorkspaceHybridSearchResult, WorkspaceIndexError, WorkspacePath, WorkspacePathResolver,
314    WorkspaceRef, WorkspaceRerankAlgorithm, WorkspaceRerankFallbackReason, WorkspaceRerankMode,
315    WorkspaceRerankOptions, WorkspaceRerankStatus, WorkspaceResult, WorkspaceRetrievalChannel,
316    WorkspaceRetrievalError, WorkspaceRetrievalOptions, WorkspaceRetrievalPhase,
317    WorkspaceRetrievalResult, WorkspaceRetrievalRuntime, WorkspaceRetrievalStatus, WorkspaceSearch,
318    WorkspaceSemanticFallbackReason, WorkspaceSemanticIndexLimits, WorkspaceSemanticSearchHit,
319    WorkspaceSemanticSearchRequest, WorkspaceSemanticSearchResult, WorkspaceServices,
320    WorkspaceServicesBuilder, WorkspaceTextRange, WorkspaceTextReader, WorkspaceVersionConflict,
321    WorkspaceWriteOutcome,
322};
323#[cfg(feature = "s3")]
324pub use workspace::{S3BackendConfig, S3WorkspaceBackend};