Public declaration syntax from forge-rs/crates/forge-agent/src/agent.rs Original source SHA-256: 8c7c889ebea73ce8d66dc6dea8423514b4491404b1b301fef701f21b44290503 Function bodies and constant values are omitted. This is not the complete implementation. Source line 54 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] pub struct BoundaryContract { } Source line 62 pub fn new() -> Self; Source line 67 pub fn with_network_access(mut self) -> Self; Source line 73 pub fn with_delegation_access(mut self) -> Self; Source line 79 pub fn allow_provider_namespace(mut self, namespace: impl Into) -> Self; Source line 99 #[derive(Debug, Clone, PartialEq, Eq)] pub struct ProviderIdentityVerification { /// The DID that was verified. pub did: String, /// Whether the DID document's signature validated successfully. pub signature_valid: bool, /// Whether the DID's lineage chain validated successfully. pub lineage_valid: bool, /// Forge-owned conformance level derived from the upstream verification pipeline. pub conformance_level: u8 } Source line 112 #[async_trait] pub trait ProviderAuthorityVerifier: Send + Sync { /// Verifies the given DID and returns the normalized authority result. async fn verify_did(&self, did: &str) -> Result; } Source line 119 #[derive(Debug, Clone, PartialEq, Eq)] pub struct CodingProviderPreflight { /// The negotiated provider contract. pub negotiation: ProviderNegotiationResult, /// The DID that passed execution-authority verification. pub verified_did: String, /// The provider scopes that were validated against the active ACT. pub required_scopes: Vec } Source line 129 #[cfg(not(target_arch = "wasm32"))] pub struct AegisProviderAuthorityVerifier { } Source line 136 #[cfg(not(target_arch = "wasm32"))] pub fn new( registry: std::sync::Arc, config: aegis_core::VerificationConfig, ) -> Self; Source line 146 #[cfg(not(target_arch = "wasm32"))] pub fn from_pipeline(pipeline: aegis_verify::VerificationPipeline) -> Self; Source line 206 #[derive(Clone, Serialize, Deserialize)] pub struct AgentConfig { } Source line 314 pub fn new(name: impl Into, model: impl Into) -> Self; Source line 391 pub fn with_system_prompt(mut self, prompt: impl Into) -> Self; Source line 415 pub fn with_max_steps(mut self, max: u32) -> Self; Source line 441 pub fn with_tool(mut self, tool: ToolDefinition) -> Self; Source line 455 pub fn with_tools(mut self, tools: Vec) -> Self; Source line 501 pub fn with_tool_registry(mut self, registry: &forge_tool::registry::ToolRegistry) -> Self; Source line 507 pub fn with_boundary_contract(mut self, boundary_contract: BoundaryContract) -> Self; Source line 544 pub fn with_identity(mut self, identity: ForgeAgentIdentity) -> Self; Source line 577 pub fn with_act(mut self, act: AgentCapabilityToken) -> Self; Source line 583 pub fn name(&self) -> &str; Source line 588 pub fn model(&self) -> &ProviderRef; Source line 593 pub fn tools(&self) -> &[ToolDefinition]; Source line 598 pub fn max_steps(&self) -> u32; Source line 603 pub fn system_prompt(&self) -> Option<&str>; Source line 608 pub fn boundary_contract(&self) -> Option<&BoundaryContract>; Source line 619 pub fn identity(&self) -> Option<&ForgeAgentIdentity>; Source line 629 pub fn act(&self) -> Option<&AgentCapabilityToken>; Source line 647 pub fn agent_did(&self) -> Option<&str>; Source line 652 pub async fn preflight_coding_provider_execution( &self, registry: &ProviderRegistry, request: &ProviderNegotiationRequest, verifier: &V, ) -> Result; Source line 815 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ToolInvocationRecord { /// The tool call id that the model assigned. pub id: String, /// The tool's registered name. pub name: String, /// Wall-clock timestamp at which the agent began executing the tool. /// /// Serialized as RFC 3339. Set from `chrono::Utc::now()` immediately /// before the executor (or authorization gate / lookup) is invoked. #[serde(with = "tool_invocation_started_at_serde")] pub started_at: chrono::DateTime, /// Time elapsed between the start and the resolution of the invocation. /// /// Captures the full latency: authorization check + executor + approval /// handler. Serialized as a struct (`{ "secs": u64, "nanos": u32 }`). pub duration: std::time::Duration, /// Final status of the invocation. pub status: ToolInvocationStatus } Source line 842 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ModelInferenceRecord { /// Host or loop assigned id for this model call. pub id: String, /// Model identifier selected for the call. pub model: String, /// Provider identifier or namespace that served the call. pub provider_id: String, /// Optional model-router or Foundry route id. pub route_id: Option, /// Governed artifact ref for the prompt payload. pub prompt_ref: Option, /// Governed artifact ref for the completion payload. pub completion_ref: Option, /// Prompt/input token count, when reported. pub prompt_tokens: Option, /// Completion/output token count, when reported. pub completion_tokens: Option, /// Wall-clock timestamp at which the model call began. #[serde(with = "tool_invocation_started_at_serde")] pub started_at: chrono::DateTime, /// Time elapsed between model call start and stream completion. pub duration: std::time::Duration, /// Canonical Cambium outcome label, such as `success` or `failed`. pub outcome: String } Source line 873 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SubAgentDelegationRecord { /// OAS/stable child agent id. pub subagent_id: String, /// Host-assigned run id for the delegated sub-agent. pub subagent_run_id: String, /// Optional summary of why the delegation happened. pub delegation_reason: Option, /// Governed artifact ref for the delegated instruction. pub instruction_ref: Option, /// Capability refs granted to the child. pub capability_refs: Vec, /// Governed artifact ref for handoff state. pub handoff_ref: Option, /// Wall-clock timestamp at which delegation started. #[serde(with = "tool_invocation_started_at_serde")] pub started_at: chrono::DateTime } Source line 900 #[derive(Debug, Clone, PartialEq, Eq)] pub enum AgentEvent { /// A user message was added to the conversation. UserMessage(String), /// A system message was added to the conversation. SystemMessage(String), /// The assistant produced a text turn (no tool calls). AssistantText(String), /// The assistant called a tool. Pairs with a later [`AgentEvent::ToolResult`] /// (matched on `id`) and, if the run captured timing, /// [`AgentEvent::ToolInvocationCompleted`]. AssistantToolCall { id: String, name: String, arguments: serde_json::Value, }, /// The tool returned a result (already in the conversation as a `Role::Tool` /// message). `is_error` reflects the tool result's own flag. ToolResult { id: String, name: String, content: String, is_error: bool, }, /// A timed tool invocation completed (lifted from /// [`AgentOutput::tool_invocations`]). Carries the typed status, the /// captured duration, and the wall-clock start. ToolInvocationCompleted(ToolInvocationRecord), } Source line 932 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ToolInvocationStatus { /// The executor returned `Ok` and the tool result is not flagged as an error. Succeeded, /// The executor returned `Ok` but the tool result is flagged as an error. /// Distinguished from `Failed` so callers can see "the tool ran fine but /// the model's request was wrong" vs. "the tool itself blew up." SucceededWithToolError, /// The tool name was not present in the registry. NotFound, /// Authorization (ACT scope check) denied the invocation. AuthorizationDenied, /// The executor returned `Err`. Failed, } Source line 951 pub fn serialize(value: &DateTime, serializer: S) -> Result where S: Serializer,; Source line 958 pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>,; Source line 970 pub const AGENT_RUN_CHECKPOINT_SCHEMA: &str; Source line 979 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct AgentRunCheckpoint { /// Stable schema id. Must be [`AGENT_RUN_CHECKPOINT_SCHEMA`]. pub schema: String, /// Host-assigned run identifier. pub run_id: String, /// Agent name from the originating [`AgentConfig`]. pub agent_name: String, /// Provider model reference from the originating [`AgentConfig`]. pub model: String, /// Number of tool-loop steps already consumed. pub step_count: u32, /// Maximum steps allowed for the originating run. pub max_steps: u32, /// Conversation state to pass back into [`Agent::run_with_messages`]. pub messages: Vec, /// Usage accumulated before the checkpoint was written. pub usage: Usage, /// Final or latest assistant text available when the checkpoint was written. pub final_text: String, /// Tool invocation audit records accumulated before the checkpoint was /// written. #[serde(default)] pub tool_invocations: Vec } Source line 1014 pub fn validate_for(&self, config: &AgentConfig) -> Result<(), AgentCheckpointValidationError>; Source line 1054 pub fn resume_messages(&self) -> &[ModelMessage]; Source line 1059 pub fn remaining_steps(&self) -> u32; Source line 1075 pub fn resume_config_for( &self, config: &AgentConfig, ) -> Result; Source line 1099 pub fn digest_sha256(&self) -> Result; Source line 1115 pub fn verify_digest_sha256( &self, expected: &str, ) -> Result<(), AgentCheckpointValidationError>; Source line 1156 #[derive(Debug, Clone, PartialEq, Eq)] pub enum AgentCheckpointValidationError { /// Checkpoint schema is not the supported Forge checkpoint schema. SchemaMismatch { /// Expected schema id. expected: String, /// Schema id found in the checkpoint. found: String, }, /// Checkpoint run id is empty. EmptyRunId, /// Checkpoint belongs to a different agent name. AgentNameMismatch { /// Expected agent name. expected: String, /// Agent name found in the checkpoint. found: String, }, /// Checkpoint belongs to a different model reference. ModelMismatch { /// Expected provider model reference. expected: String, /// Model reference found in the checkpoint. found: String, }, /// Checkpoint max-step budget differs from the resume config. MaxStepsMismatch { /// Expected max-step budget. expected: u32, /// Max-step budget found in the checkpoint. found: u32, }, /// Checkpoint has already consumed more steps than the budget allows. StepCountExceedsMax { /// Steps already consumed. step_count: u32, /// Maximum allowed steps. max_steps: u32, }, /// Checkpoint has no remaining steps for a resumed run. StepBudgetExhausted { /// Original maximum allowed steps. max_steps: u32, }, /// Expected checkpoint digest is not a SHA-256 hex string. InvalidDigest { /// Digest value that failed shape validation. found: String, }, /// Checkpoint could not be serialized for digest verification. DigestSerializationFailed { /// Serialization failure message. message: String, }, /// Checkpoint digest does not match expected evidence. DigestMismatch { /// Expected checkpoint digest. expected: String, /// Actual checkpoint digest. found: String, }, } Source line 1303 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AgentOutput { /// The complete conversation history including all user, assistant, /// and tool messages exchanged during execution. pub messages: Vec, /// Cumulative token usage across all LLM calls during execution. pub usage: Usage, /// The number of tool loop steps taken (each LLM call counts as one step). pub steps_taken: u32, /// The final text response produced by the agent. /// /// This is the text content of the last assistant message that did not /// contain tool calls (i.e., the terminal response). pub final_text: String, /// Per-tool invocation records collected during the run. /// /// One entry per tool call attempted, in the order they were executed. /// Includes name, wall-clock start, duration, and final status (succeeded / /// failed / authorization-denied / not-found). Backfilled to an empty /// `Vec` when constructing `AgentOutput` from older code paths or when /// deserializing payloads that pre-date this field. #[serde(default)] pub tool_invocations: Vec } Source line 1337 pub fn to_checkpoint( &self, run_id: impl Into, config: &AgentConfig, ) -> AgentRunCheckpoint; Source line 1391 pub fn events(&self) -> impl Iterator + '_; Source line 1504 #[async_trait] pub trait Agent: Send + Sync { /// Returns the agent's configuration. /// /// # Returns /// /// A reference to the [`AgentConfig`] used to create this agent. fn config(&self) -> &AgentConfig; /// Returns a snapshot of the agent's current health profile. /// /// The health profile contains runtime metrics: uptime, error counts, /// tool invocations, inference statistics, and resource usage. Returns /// a clone because the profile is mutated concurrently during execution /// (behind interior mutability). /// /// # ANVIL Spec SS14.1 /// /// Health profiles are part of the telemetry contract. They are exposed /// for monitoring and audit trail consumption. /// /// # Returns /// /// A cloned snapshot of the agent's [`HealthProfile`]. fn health(&self) -> HealthProfile; /// Returns the agent's current lifecycle state. /// /// # ANVIL Spec SS13.2 /// /// The lifecycle state machine has six states: Initializing, Ready, /// Running, Paused, Error, Terminated. See the spec for the complete /// transition table. /// /// # Returns /// /// The current [`LifecycleState`]. fn lifecycle(&self) -> LifecycleState; /// Runs the agent with a text prompt. /// /// This is the primary entry point for agent execution. It creates an /// initial user message from the prompt and delegates to /// [`run_with_messages`](Self::run_with_messages). /// /// # ANVIL Spec SS7.1 /// /// The agent execution loop: /// 1. Send messages to the LLM. /// 2. If the response contains tool calls, execute them and loop. /// 3. If the response is text only, return the final result. /// 4. Check stop conditions after each step. /// /// # Arguments /// /// * `prompt` - The user's text prompt to process. /// /// # Returns /// /// An [`AgentOutput`] containing the final response, conversation history, /// usage statistics, and step count. /// /// # Errors /// /// * [`ForgeAgentError::ToolLoopFailed`] -- if a tool loop step fails. /// * [`ForgeAgentError::LifecycleError`] -- if the agent is not in a runnable state. /// * [`ForgeAgentError::StopConditionReached`] -- if max steps or tokens are exceeded. /// * [`ForgeAgentError::Generate`] -- if the underlying model call fails. /// * [`ForgeAgentError::Tool`] -- if a tool execution fails. async fn run(&self, prompt: &str) -> Result; /// Runs the agent with a pre-constructed message list. /// /// This is the lower-level entry point that allows callers to provide /// the complete conversation history, including system messages, tool /// results, and previous exchanges. /// /// # Arguments /// /// * `messages` - The initial message list to process. /// /// # Returns /// /// An [`AgentOutput`] containing the final response and metadata. /// /// # Errors /// /// Same error variants as [`run()`](Self::run). async fn run_with_messages( &self, messages: Vec, ) -> Result; }