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