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 durable_memory;
92pub mod dynamic_workflow;
93pub mod embedding;
94pub mod error;
95pub mod event_protocol;
96pub mod flow_graph;
97pub(crate) mod git;
98pub mod harness_evidence;
99pub mod hitl;
100pub mod hooks;
101pub mod host_env;
102pub(crate) mod language;
103pub mod llm;
104pub mod loop_checkpoint;
105pub mod mcp;
106pub mod memory;
107#[cfg(feature = "headless-search")]
108pub mod moli_runtime;
109pub mod orchestration;
110pub(crate) mod ordered_parallel;
111pub mod permissions;
112pub mod planning;
113pub mod program;
114pub(crate) mod prompts;
115pub mod queue;
116pub mod release;
117pub mod retention;
118pub(crate) mod retry;
119pub mod rl_trajectory;
120pub mod run;
121pub mod run_control;
122pub(crate) mod safety_gate;
123pub mod sandbox;
124pub mod sdk_capabilities;
125#[cfg(feature = "headless-search")]
126pub mod search_runtime;
127pub mod security;
128#[cfg(feature = "serve")]
129pub mod serve;
130pub mod session_checkpoint;
131pub(crate) mod session_lane_queue;
132pub mod skills;
133pub(crate) mod sse;
134pub mod state_graph;
135pub mod store;
136pub mod subagent;
137pub mod subagent_task_tracker;
138pub mod task_scheduler;
139pub mod telemetry;
140#[cfg(feature = "telemetry")]
141pub mod telemetry_otel;
142#[cfg(test)]
143pub(crate) mod test_support;
144pub(crate) mod text;
145pub(crate) mod tool_confirmation;
146pub mod tools;
147pub mod trace;
148pub mod use_runtime_tasks;
149pub mod verification;
150pub mod workspace;
151
152// Re-export key types at crate root for ergonomic usage
153pub use agent::{AgentEvent, AgentExecutionFailure, AgentResult};
154pub use agent_api::{
155    Agent, AgentRunSpawn, AgentSession, ProjectedFlowHandle, ProjectedUiHandle, ReadFileOptions,
156    SessionBuilder, SessionOptions, ToolCallResult,
157};
158pub use agent_protocol::{
159    AgentProtocolChangeSetRequestV1, AgentProtocolChangeSetV1, AgentProtocolCommandActionV1,
160    AgentProtocolCommandReceiptV1, AgentProtocolCommandV1, AgentProtocolError,
161    AgentProtocolEventPageRequestV1, AgentProtocolEventPageV1, AgentProtocolEventRecordV1,
162    AgentProtocolRunCancelV1, AgentProtocolRunIdentityV1, AgentProtocolRunRecoverExactV1,
163    AgentProtocolRunRecoverV1, AgentProtocolRunStartV1, AgentProtocolRunStateV1,
164    AGENT_PROTOCOL_CHANGE_SET_ENCODING_V1, AGENT_PROTOCOL_CHANGE_SET_FORMAT_V1,
165    AGENT_PROTOCOL_CHANGE_SET_HTTP_PATH_V1, AGENT_PROTOCOL_COMMAND_HTTP_PATH_V1,
166    AGENT_PROTOCOL_EVENT_PAGE_HTTP_PATH_V1, AGENT_PROTOCOL_MAX_CHANGE_SET_BYTES,
167    AGENT_PROTOCOL_MAX_CHANGE_SET_RESPONSE_BYTES, AGENT_PROTOCOL_MAX_EVENTS_PER_PAGE,
168    AGENT_PROTOCOL_MAX_EVENT_METADATA_BYTES, AGENT_PROTOCOL_MAX_EVENT_PAGE_BYTES,
169    AGENT_PROTOCOL_MAX_EVENT_PAYLOAD_BYTES, AGENT_PROTOCOL_MAX_EVENT_RECORD_BYTES,
170    AGENT_PROTOCOL_MAX_EVENT_TYPE_BYTES, AGENT_PROTOCOL_MAX_ID_BYTES,
171    AGENT_PROTOCOL_MAX_PROMPT_BYTES, AGENT_PROTOCOL_MAX_REASON_BYTES, AGENT_PROTOCOL_V1,
172};
173pub use agent_protocol_harness::{
174    AgentProtocolCheckpointRecoveryError, AgentProtocolHarness, AgentProtocolHarnessError,
175    AGENT_PROTOCOL_HARNESS_MAX_SESSIONS,
176};
177pub use agent_protocol_host::{
178    AgentProtocolExactRecoveryError, AgentProtocolHost, AgentProtocolHostError,
179};
180pub use code_intelligence::{
181    CodeDiagnostic, CodeDiagnosticSeverity, CodeIntelligenceCapabilities, CodeIntelligenceError,
182    CodeIntelligenceLanguageStatus, CodeIntelligenceResult, CodeIntelligenceState,
183    CodeIntelligenceStatus, CodeLocation, CodePosition, CodeQueryResult, CodeRange, CodeSymbolKind,
184    DocumentRevision, DocumentSnapshot, DocumentSymbol, LanguageId, LocalCodeIntelligence,
185    NavigationKind, SymbolInformation, WorkspaceCodeIntelligence,
186};
187pub use cognitive_context::{
188    CognitiveContextDocumentV1, CognitiveContextError, CognitiveContextLimits,
189    CognitiveContextProvider, CognitiveContextRequestV1, CognitiveContextResponseV1,
190    CognitiveContextResult, CognitiveContextSession, CognitiveKnowledgeBindingV1,
191    CognitiveKnowledgeCitationV1, CognitivePackageBindingV1,
192    COGNITIVE_CONTEXT_REQUEST_DIGEST_DOMAIN, COGNITIVE_CONTEXT_REQUEST_SCHEMA,
193    COGNITIVE_CONTEXT_RESPONSE_SCHEMA, COGNITIVE_KNOWLEDGE_BINDING_SCHEMA,
194    COGNITIVE_PACKAGE_BINDING_SCHEMA, OKF_KNOWLEDGE_CITATION_SCHEMA,
195    OKF_KNOWLEDGE_READ_REQUEST_SCHEMA, OKF_KNOWLEDGE_SEARCH_REQUEST_SCHEMA,
196};
197pub use config::{
198    AutoDelegationConfig, CodeConfig, ModelConfig, ModelCost, ModelLimit, ModelModalities,
199    OsConfig, ProviderConfig,
200};
201pub use durable_memory::{
202    DurableMemoryActivation, DurableMemoryBindingV1, DurableMemoryMode, DurableMemoryRecallChannel,
203    DurableMemoryRecallHit, DurableMemoryRecallPolicy, DurableMemoryRecallPreview,
204    DurableMemorySemanticBindingV1, DurableMemorySemanticError, DurableMemorySemanticRecall,
205    DurableMemorySemanticRecallPolicy, DurableMemorySemanticRefreshCheckpoint,
206    DurableMemorySemanticRefreshReceipt, DurableMemorySession, DurableMemoryUse,
207    DURABLE_MEMORY_BINDING_SCHEMA_VERSION, DURABLE_MEMORY_CONTEXT_ID_PROFILE_V1,
208    DURABLE_MEMORY_CONTEXT_ID_PROFILE_V2, DURABLE_MEMORY_HYBRID_BINDING_SCHEMA_VERSION,
209    DURABLE_MEMORY_RETRIEVAL_PROFILE_V1, DURABLE_MEMORY_SEMANTIC_BINDING_SCHEMA_V1,
210    DURABLE_MEMORY_SEMANTIC_FUSION_PROFILE_V1,
211    DURABLE_MEMORY_SEMANTIC_REFRESH_CHECKPOINT_SCHEMA_V1,
212    DURABLE_MEMORY_SEMANTIC_REFRESH_PROFILE_V1,
213};
214pub use dynamic_workflow::{
215    dynamic_workflow_store_path, DynamicWorkflowRuntime, DynamicWorkflowScriptLimits,
216    DynamicWorkflowTool, DYNAMIC_WORKFLOW_STORE_RELATIVE_PATH,
217};
218pub use embedding::{
219    EmbeddingBatchRequest, EmbeddingBatchResponse, EmbeddingError, EmbeddingExecution,
220    EmbeddingExecutor, EmbeddingExecutorConfig, EmbeddingFailureKind, EmbeddingInput,
221    EmbeddingNormalization, EmbeddingProvider, EmbeddingProviderDescriptor, EmbeddingProviderError,
222    EmbeddingResult, EmbeddingVector,
223};
224pub use error::SessionBuildResource;
225pub use error::{CodeError, Result};
226pub use event_protocol::{
227    run_event_envelope_v1, AgentEventProjectionV1, AgentEventTypeV1, EventEnvelopeV1,
228    EventProtocolError, AGENT_EVENT_TYPES_V1, EVENT_ENVELOPE_V1_VERSION,
229};
230pub use flow_graph::{
231    run_object_id as flow_run_object_id, step_object_id as flow_step_object_id,
232    FileFlowDecisionLedger, FlowDecision, FlowDecisionClaimOutcome, FlowDecisionDispatchError,
233    FlowDecisionDispatcher, FlowDecisionHealthSnapshot, FlowDecisionHealthStatus,
234    FlowDecisionLedger, FlowDecisionRequest, FlowDecisionSink, FlowDecisionStep,
235    FlowGraphHealthSnapshot, FlowGraphHealthStatus, FlowGraphObserver, MemoryFlowDecisionLedger,
236    FLOW_GRAPH_SOURCE,
237};
238pub use harness_evidence::{
239    HarnessEvidenceError, ModelInputKindV1, ModelInputSnapshotV1, ModelPresentationApplicationV1,
240    ModelPresentationSnapshotV1, ModelUsageSnapshotV1, RunCapabilitySnapshotV1,
241    RunPolicyCeilingSnapshotV1, ToolRequestOriginV1, ToolRequestSnapshotV1,
242    ToolResultContextUsageV1, WorkspaceCapabilitySnapshotV1,
243    WorkspaceRetrievalCapabilitySnapshotV1, MODEL_INPUT_SNAPSHOT_V1_SCHEMA,
244    MODEL_PRESENTATION_SNAPSHOT_V1_SCHEMA, MODEL_USAGE_SNAPSHOT_V1_SCHEMA,
245    RUN_CAPABILITY_SNAPSHOT_V1_SCHEMA, TOOL_REQUEST_SNAPSHOT_V1_SCHEMA,
246};
247pub use llm::{
248    clear_http_metrics_callback, set_http_metrics_callback, AnthropicClient, Attachment,
249    ContentBlock, HttpMetricsCallback, HttpMetricsRecord, ImageSource, LlmClient, LlmResponse,
250    Message, ModelGenerationAdmission, ModelGenerationAdmissionError, ModelGenerationConcurrency,
251    ModelGenerationPermit, OpenAiClient, TokenUsage,
252};
253#[cfg(feature = "headless-search")]
254pub use moli_runtime::{
255    default_moli_version, ensure_moli, moli_runtime_info, packaged_moli, MoliRuntimeInfo,
256    MOLI_RUNTIME_INFO_SCHEMA_V1,
257};
258pub use orchestration::{
259    execute_loop, execute_pipeline, execute_steps_parallel, execute_steps_parallel_resumable,
260    AgentExecutor, AgentStepSpec, BudgetSnapshot, LoopDecision, PipelineStage, StepOutcome,
261    Workflow, WorkflowBudget, WorkflowBuilder, WorkflowCheckpoint, WorkflowEvent,
262    WorkflowStepRecord, WORKFLOW_CHECKPOINT_SCHEMA_VERSION,
263};
264pub use prompts::{AgentStyle, DetectionConfidence, PlanningMode, SystemPromptSlots};
265pub use rl_trajectory::{RlTrajectoryConfig, RlTrajectoryMode, RlTrajectoryRecorder};
266pub use run::{
267    ActiveToolSnapshot, InMemoryRunStore, RunEventRecord, RunHandle, RunRecord, RunReservation,
268    RunSnapshot, RunStatus, RunWorkspaceChangeSet, RunWorkspaceChangeSetError,
269};
270pub use run_control::{
271    InterruptRequest, RunControlCommand, RunControlError, RunControlErrorInfo, RunControlOperation,
272    RunControlReceipt, RunControlReceiptState, RunControlRequest, RunControlSnapshot, SteerRequest,
273    RUN_CONTROL_MAX_ID_BYTES, RUN_CONTROL_MAX_INPUT_BYTES, RUN_CONTROL_MAX_QUEUE,
274    RUN_CONTROL_MAX_REASON_BYTES, RUN_CONTROL_MAX_SEEN_REQUESTS, RUN_CONTROL_RECEIPT_SCHEMA_V1,
275    RUN_CONTROL_REQUEST_SCHEMA_V1,
276};
277pub use sdk_capabilities::{
278    sdk_capabilities, sdk_capabilities_schema, SdkCapability, SDK_CAPABILITIES_SCHEMA_V1,
279};
280pub use session_checkpoint::{
281    SessionCheckpointDescriptorV1, SessionCheckpointError, SessionCheckpointExportSink,
282    SessionCheckpointExportV1, SessionCheckpointPayloadV1, SessionLogicalResumeEvidenceV1,
283    SessionSnapshotEvidenceV1, SESSION_CHECKPOINT_DESCRIPTOR_SCHEMA_V1,
284    SESSION_CHECKPOINT_ENCODING_V1, SESSION_CHECKPOINT_FORMAT_V1,
285    SESSION_CHECKPOINT_LOGICAL_RESUME_SEMANTICS_V1, SESSION_CHECKPOINT_MAX_CONTENT_BYTES,
286    SESSION_CHECKPOINT_MEDIA_TYPE_V1, SESSION_CHECKPOINT_PAYLOAD_SCHEMA_V1,
287    SESSION_LOGICAL_RESUME_EVIDENCE_SCHEMA_V1, SESSION_SNAPSHOT_EVIDENCE_SCHEMA_V1,
288};
289pub use state_graph::{
290    graph_event_head, Behavior, BehaviorContext, BehaviorError, EventFilter, ExternalEvent,
291    ExternalProjectionOutcome, FileGraphEventStore, FnBehavior, GraphDiff, GraphEvent,
292    GraphEventRecord, GraphEventStore, GraphObject, GraphPatch, GraphRelation, GraphRuntime,
293    GraphSaveOutcome, MemoryGraphEventStore, ObjectId, PatchOperation, RelationId, ReplayError,
294    RuntimeError as GraphRuntimeError, RuntimeLimits, StateGraph, GRAPH_EVENT_SCHEMA_VERSION,
295};
296pub use subagent::{
297    AgentDefinition, AgentRegistry, CattleAgentKind, CattleAgentSpec, ConfirmationInheritance,
298    WorkerAgentKind, WorkerAgentSpec,
299};
300pub use subagent_task_tracker::{
301    InMemorySubagentTaskTracker, SubagentProgressEntry, SubagentStatus, SubagentTaskSnapshot,
302};
303pub use task_scheduler::{
304    TaskPriority, TaskPriorityCounts, TaskScheduler, TaskSchedulerConfig, TaskSchedulerError,
305    TaskSchedulerStats,
306};
307pub use tools::{
308    ImmutableContentAdapter, ImmutableContentAdapterBindingV1, ImmutableContentAdapterSession,
309    ImmutableContentDescriptorV1, ImmutableContentError, ImmutableContentKindV1,
310    ImmutableContentReferenceV1, ImmutableContentResult, ImmutableContentWriteRequestV1,
311    ToolPresentationError, ToolPresentationModeV1, ToolPresentationProfileV1,
312    IMMUTABLE_CONTENT_ADAPTER_BINDING_SCHEMA_V1, IMMUTABLE_CONTENT_DESCRIPTOR_SCHEMA_V1,
313    IMMUTABLE_CONTENT_REFERENCE_SCHEMA_V1, TOOL_PRESENTATION_PROFILE_V1_SCHEMA,
314    TOOL_RESULT_CONTENT_MEDIA_TYPE,
315};
316pub use tools::{ToolCapabilities, ToolErrorKind, ToolOutputKind};
317pub use use_runtime_tasks::{
318    UsePlanScope, UsePlanScopeKind, UseProjectedLifecycleIdentity, UseRuntimeTaskDispatcher,
319    UseRuntimeTaskError, UseRuntimeTaskExecutionV1, UseRuntimeTaskProjectionAdapter,
320    UseRuntimeTaskProjectionV1, UseRuntimeTaskRequestV1, UseRuntimeTaskResult,
321    MAX_USE_RUNTIME_TASK_ARGUMENTS, MAX_USE_RUNTIME_TASK_ARGUMENT_BYTES,
322    MAX_USE_RUNTIME_TASK_OUTPUT_BYTES, MAX_USE_RUNTIME_TASK_TIMEOUT_MS,
323    USE_RUNTIME_TASK_REQUEST_SCHEMA, USE_RUNTIME_TASK_RESULT_SCHEMA,
324};
325pub use workspace::{
326    ChunkCatalogLimits, ChunkCatalogSnapshot, ChunkingConfig, CommandOutput, CommandOutputObserver,
327    CommandOutputSummary, CommandRequest, CustomWorkspaceChunkingStrategy,
328    FixedWindowChunkingOptions, LexicalSearchHit, LexicalSearchRequest, LexicalSearchResult,
329    LocalWorkspaceAccessPolicy, LocalWorkspaceBackend, LocalWorkspaceFile,
330    LocalWorkspaceFileStatus, LocalWorkspaceManifest, LocalWorkspaceManifestSnapshot,
331    ManifestWorkspaceBackend, RecentWorkspaceFile, RecursiveChunkingOptions, RemoteGitBackend,
332    RemoteGitBackendConfig, RemoteGitConflict, VirtualPathResolver, WorkspaceCapabilities,
333    WorkspaceChunk, WorkspaceChunkCatalog, WorkspaceChunkId, WorkspaceChunkRange,
334    WorkspaceChunkingError, WorkspaceChunkingInput, WorkspaceChunkingStrategy,
335    WorkspaceCommandRunner, WorkspaceDirEntry, WorkspaceEligibilityPolicy,
336    WorkspaceEmbeddingBatchMetrics, WorkspaceError, WorkspaceFileChange, WorkspaceFileChangeKind,
337    WorkspaceFileSystem, WorkspaceFileSystemExt, WorkspaceFileType, WorkspaceGit,
338    WorkspaceGitBranch, WorkspaceGitCheckoutOutput, WorkspaceGitCheckoutRequest,
339    WorkspaceGitCommit, WorkspaceGitCreateBranchRequest, WorkspaceGitCreateWorktreeRequest,
340    WorkspaceGitDiffRequest, WorkspaceGitRemote, WorkspaceGitRemoveWorktreeRequest,
341    WorkspaceGitStash, WorkspaceGitStashProvider, WorkspaceGitStashRequest, WorkspaceGitStatus,
342    WorkspaceGitWorktree, WorkspaceGitWorktreeMutation, WorkspaceGitWorktreeProvider,
343    WorkspaceGlobRequest, WorkspaceGlobResult, WorkspaceGrepOutcome, WorkspaceGrepRequest,
344    WorkspaceGrepResult, WorkspaceHybridChannelRank, WorkspaceHybridChannelStatus,
345    WorkspaceHybridFallbackReason, WorkspaceHybridSearchHit, WorkspaceHybridSearchRequest,
346    WorkspaceHybridSearchResult, WorkspaceIndexError, WorkspacePath, WorkspacePathResolver,
347    WorkspaceRef, WorkspaceRerankAlgorithm, WorkspaceRerankFallbackReason, WorkspaceRerankMode,
348    WorkspaceRerankOptions, WorkspaceRerankStatus, WorkspaceResult, WorkspaceRetrievalChannel,
349    WorkspaceRetrievalError, WorkspaceRetrievalOptions, WorkspaceRetrievalPhase,
350    WorkspaceRetrievalResult, WorkspaceRetrievalRuntime, WorkspaceRetrievalStatus, WorkspaceSearch,
351    WorkspaceSemanticFallbackReason, WorkspaceSemanticIndexLimits, WorkspaceSemanticSearchHit,
352    WorkspaceSemanticSearchRequest, WorkspaceSemanticSearchResult, WorkspaceServices,
353    WorkspaceServicesBuilder, WorkspaceTextRange, WorkspaceTextReader, WorkspaceVecShadowPhase,
354    WorkspaceVecShadowStatus, WorkspaceVectorEngine, WorkspaceVersionConflict,
355    WorkspaceWriteOutcome,
356};
357#[cfg(feature = "s3")]
358pub use workspace::{S3BackendConfig, S3WorkspaceBackend};