Skip to content
This repository was archived by the owner on Apr 8, 2026. It is now read-only.

Commit 22ad54c

Browse files
committed
docs: describe the runtime public API surface
This adds crate-level and type-level Rustdoc to the runtime crate's core exported types so downstream crates and contributors can understand the session, prompt, permission, OAuth, usage, and tool I/O primitives without spelunking every implementation file. Constraint: The docs pass needed to stay focused on public runtime types without changing behavior Rejected: Add blanket docs to every public item in one sweep | larger churn than needed for a targeted docs pass Confidence: high Scope-risk: narrow Reversibility: clean Directive: When exporting new runtime primitives from lib.rs, add a short Rustdoc summary in the defining module at the same time Tested: cargo build --workspace; cargo test --workspace Not-tested: rustdoc HTML rendering beyond doc-test coverage
1 parent 953513f commit 22ad54c

11 files changed

Lines changed: 106 additions & 6 deletions

File tree

rust/crates/runtime/src/bash.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ use crate::sandbox::{
1414
};
1515
use crate::ConfigLoader;
1616

17+
/// Input schema for the built-in bash execution tool.
1718
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1819
pub struct BashCommandInput {
1920
pub command: String,
@@ -33,6 +34,7 @@ pub struct BashCommandInput {
3334
pub allowed_mounts: Option<Vec<String>>,
3435
}
3536

37+
/// Output returned from a bash tool invocation.
3638
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3739
pub struct BashCommandOutput {
3840
pub stdout: String,
@@ -64,6 +66,7 @@ pub struct BashCommandOutput {
6466
pub sandbox_status: Option<SandboxStatus>,
6567
}
6668

69+
/// Executes a shell command with the requested sandbox settings.
6770
pub fn execute_bash(input: BashCommandInput) -> io::Result<BashCommandOutput> {
6871
let cwd = env::current_dir()?;
6972
let sandbox_status = sandbox_status_for_input(&input, &cwd);

rust/crates/runtime/src/compact.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ const COMPACT_CONTINUATION_PREAMBLE: &str =
55
const COMPACT_RECENT_MESSAGES_NOTE: &str = "Recent messages are preserved verbatim.";
66
const COMPACT_DIRECT_RESUME_INSTRUCTION: &str = "Continue the conversation from where it left off without asking the user any further questions. Resume directly — do not acknowledge the summary, do not recap what was happening, and do not preface with continuation text.";
77

8+
/// Thresholds controlling when and how a session is compacted.
89
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
910
pub struct CompactionConfig {
1011
pub preserve_recent_messages: usize,
@@ -20,6 +21,7 @@ impl Default for CompactionConfig {
2021
}
2122
}
2223

24+
/// Result of compacting a session into a summary plus preserved tail messages.
2325
#[derive(Debug, Clone, PartialEq, Eq)]
2426
pub struct CompactionResult {
2527
pub summary: String,
@@ -28,11 +30,13 @@ pub struct CompactionResult {
2830
pub removed_message_count: usize,
2931
}
3032

33+
/// Roughly estimates the token footprint of the current session transcript.
3134
#[must_use]
3235
pub fn estimate_session_tokens(session: &Session) -> usize {
3336
session.messages.iter().map(estimate_message_tokens).sum()
3437
}
3538

39+
/// Returns `true` when the session exceeds the configured compaction budget.
3640
#[must_use]
3741
pub fn should_compact(session: &Session, config: CompactionConfig) -> bool {
3842
let start = compacted_summary_prefix_len(session);
@@ -46,6 +50,7 @@ pub fn should_compact(session: &Session, config: CompactionConfig) -> bool {
4650
>= config.max_estimated_tokens
4751
}
4852

53+
/// Normalizes a compaction summary into user-facing continuation text.
4954
#[must_use]
5055
pub fn format_compact_summary(summary: &str) -> String {
5156
let without_analysis = strip_tag_block(summary, "analysis");
@@ -61,6 +66,7 @@ pub fn format_compact_summary(summary: &str) -> String {
6166
collapse_blank_lines(&formatted).trim().to_string()
6267
}
6368

69+
/// Builds the synthetic system message used after session compaction.
6470
#[must_use]
6571
pub fn get_compact_continuation_message(
6672
summary: &str,
@@ -85,6 +91,7 @@ pub fn get_compact_continuation_message(
8591
base
8692
}
8793

94+
/// Compacts a session by summarizing older messages and preserving the recent tail.
8895
#[must_use]
8996
pub fn compact_session(session: &Session, config: CompactionConfig) -> CompactionResult {
9097
if !should_compact(session, config) {

rust/crates/runtime/src/config.rs

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,35 +6,41 @@ use std::path::{Path, PathBuf};
66
use crate::json::JsonValue;
77
use crate::sandbox::{FilesystemIsolationMode, SandboxConfig};
88

9+
/// Schema name advertised by generated settings files.
910
pub const CLAW_SETTINGS_SCHEMA_NAME: &str = "SettingsSchema";
1011

12+
/// Origin of a loaded settings file in the configuration precedence chain.
1113
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1214
pub enum ConfigSource {
1315
User,
1416
Project,
1517
Local,
1618
}
1719

20+
/// Effective permission mode after decoding config values.
1821
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1922
pub enum ResolvedPermissionMode {
2023
ReadOnly,
2124
WorkspaceWrite,
2225
DangerFullAccess,
2326
}
2427

28+
/// A discovered config file and the scope it contributes to.
2529
#[derive(Debug, Clone, PartialEq, Eq)]
2630
pub struct ConfigEntry {
2731
pub source: ConfigSource,
2832
pub path: PathBuf,
2933
}
3034

35+
/// Fully merged runtime configuration plus parsed feature-specific views.
3136
#[derive(Debug, Clone, PartialEq, Eq)]
3237
pub struct RuntimeConfig {
3338
merged: BTreeMap<String, JsonValue>,
3439
loaded_entries: Vec<ConfigEntry>,
3540
feature_config: RuntimeFeatureConfig,
3641
}
3742

43+
/// Parsed plugin-related settings extracted from runtime config.
3844
#[derive(Debug, Clone, PartialEq, Eq, Default)]
3945
pub struct RuntimePluginConfig {
4046
enabled_plugins: BTreeMap<String, bool>,
@@ -44,6 +50,7 @@ pub struct RuntimePluginConfig {
4450
bundled_root: Option<String>,
4551
}
4652

53+
/// Structured feature configuration consumed by runtime subsystems.
4754
#[derive(Debug, Clone, PartialEq, Eq, Default)]
4855
pub struct RuntimeFeatureConfig {
4956
hooks: RuntimeHookConfig,
@@ -56,31 +63,36 @@ pub struct RuntimeFeatureConfig {
5663
sandbox: SandboxConfig,
5764
}
5865

66+
/// Hook command lists grouped by lifecycle stage.
5967
#[derive(Debug, Clone, PartialEq, Eq, Default)]
6068
pub struct RuntimeHookConfig {
6169
pre_tool_use: Vec<String>,
6270
post_tool_use: Vec<String>,
6371
post_tool_use_failure: Vec<String>,
6472
}
6573

74+
/// Raw permission rule lists grouped by allow, deny, and ask behavior.
6675
#[derive(Debug, Clone, PartialEq, Eq, Default)]
6776
pub struct RuntimePermissionRuleConfig {
6877
allow: Vec<String>,
6978
deny: Vec<String>,
7079
ask: Vec<String>,
7180
}
7281

82+
/// Collection of configured MCP servers after scope-aware merging.
7383
#[derive(Debug, Clone, PartialEq, Eq, Default)]
7484
pub struct McpConfigCollection {
7585
servers: BTreeMap<String, ScopedMcpServerConfig>,
7686
}
7787

88+
/// MCP server config paired with the scope that defined it.
7889
#[derive(Debug, Clone, PartialEq, Eq)]
7990
pub struct ScopedMcpServerConfig {
8091
pub scope: ConfigSource,
8192
pub config: McpServerConfig,
8293
}
8394

95+
/// Transport families supported by configured MCP servers.
8496
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8597
pub enum McpTransport {
8698
Stdio,
@@ -91,6 +103,7 @@ pub enum McpTransport {
91103
ManagedProxy,
92104
}
93105

106+
/// Scope-normalized MCP server configuration variants.
94107
#[derive(Debug, Clone, PartialEq, Eq)]
95108
pub enum McpServerConfig {
96109
Stdio(McpStdioServerConfig),
@@ -101,6 +114,7 @@ pub enum McpServerConfig {
101114
ManagedProxy(McpManagedProxyServerConfig),
102115
}
103116

117+
/// Configuration for an MCP server launched as a local stdio process.
104118
#[derive(Debug, Clone, PartialEq, Eq)]
105119
pub struct McpStdioServerConfig {
106120
pub command: String,
@@ -109,6 +123,7 @@ pub struct McpStdioServerConfig {
109123
pub tool_call_timeout_ms: Option<u64>,
110124
}
111125

126+
/// Configuration for an MCP server reached over HTTP or SSE.
112127
#[derive(Debug, Clone, PartialEq, Eq)]
113128
pub struct McpRemoteServerConfig {
114129
pub url: String,
@@ -117,24 +132,28 @@ pub struct McpRemoteServerConfig {
117132
pub oauth: Option<McpOAuthConfig>,
118133
}
119134

135+
/// Configuration for an MCP server reached over WebSocket.
120136
#[derive(Debug, Clone, PartialEq, Eq)]
121137
pub struct McpWebSocketServerConfig {
122138
pub url: String,
123139
pub headers: BTreeMap<String, String>,
124140
pub headers_helper: Option<String>,
125141
}
126142

143+
/// Configuration for an MCP server addressed through an SDK name.
127144
#[derive(Debug, Clone, PartialEq, Eq)]
128145
pub struct McpSdkServerConfig {
129146
pub name: String,
130147
}
131148

149+
/// Configuration for an MCP managed-proxy endpoint.
132150
#[derive(Debug, Clone, PartialEq, Eq)]
133151
pub struct McpManagedProxyServerConfig {
134152
pub url: String,
135153
pub id: String,
136154
}
137155

156+
/// OAuth overrides associated with a remote MCP server.
138157
#[derive(Debug, Clone, PartialEq, Eq)]
139158
pub struct McpOAuthConfig {
140159
pub client_id: Option<String>,
@@ -143,6 +162,7 @@ pub struct McpOAuthConfig {
143162
pub xaa: Option<bool>,
144163
}
145164

165+
/// OAuth client configuration used by the main Claw runtime.
146166
#[derive(Debug, Clone, PartialEq, Eq)]
147167
pub struct OAuthConfig {
148168
pub client_id: String,
@@ -153,6 +173,7 @@ pub struct OAuthConfig {
153173
pub scopes: Vec<String>,
154174
}
155175

176+
/// Errors raised while reading or parsing runtime configuration files.
156177
#[derive(Debug)]
157178
pub enum ConfigError {
158179
Io(std::io::Error),
@@ -176,6 +197,7 @@ impl From<std::io::Error> for ConfigError {
176197
}
177198
}
178199

200+
/// Discovers config files and merges them into a [`RuntimeConfig`].
179201
#[derive(Debug, Clone, PartialEq, Eq)]
180202
pub struct ConfigLoader {
181203
cwd: PathBuf,
@@ -441,6 +463,7 @@ impl RuntimePluginConfig {
441463
}
442464

443465
#[must_use]
466+
/// Returns the default per-user config directory used by the runtime.
444467
pub fn default_config_home() -> PathBuf {
445468
std::env::var_os("CLAW_CONFIG_HOME")
446469
.map(PathBuf::from)
@@ -1338,7 +1361,10 @@ mod tests {
13381361
.load()
13391362
.expect("config should load");
13401363

1341-
let remote_server = loaded.mcp().get("remote").expect("remote server should exist");
1364+
let remote_server = loaded
1365+
.mcp()
1366+
.get("remote")
1367+
.expect("remote server should exist");
13421368
assert_eq!(remote_server.transport(), McpTransport::Http);
13431369
match &remote_server.config {
13441370
McpServerConfig::Http(config) => {

rust/crates/runtime/src/conversation.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,14 @@ use crate::usage::{TokenUsage, UsageTracker};
1818
const DEFAULT_AUTO_COMPACTION_INPUT_TOKENS_THRESHOLD: u32 = 100_000;
1919
const AUTO_COMPACTION_THRESHOLD_ENV_VAR: &str = "CLAUDE_CODE_AUTO_COMPACT_INPUT_TOKENS";
2020

21+
/// Fully assembled request payload sent to the upstream model client.
2122
#[derive(Debug, Clone, PartialEq, Eq)]
2223
pub struct ApiRequest {
2324
pub system_prompt: Vec<String>,
2425
pub messages: Vec<ConversationMessage>,
2526
}
2627

28+
/// Streamed events emitted while processing a single assistant turn.
2729
#[derive(Debug, Clone, PartialEq, Eq)]
2830
pub enum AssistantEvent {
2931
TextDelta(String),
@@ -37,6 +39,7 @@ pub enum AssistantEvent {
3739
MessageStop,
3840
}
3941

42+
/// Prompt-cache telemetry captured from the provider response stream.
4043
#[derive(Debug, Clone, PartialEq, Eq)]
4144
pub struct PromptCacheEvent {
4245
pub unexpected: bool,
@@ -46,14 +49,17 @@ pub struct PromptCacheEvent {
4649
pub token_drop: u32,
4750
}
4851

52+
/// Minimal streaming API contract required by [`ConversationRuntime`].
4953
pub trait ApiClient {
5054
fn stream(&mut self, request: ApiRequest) -> Result<Vec<AssistantEvent>, RuntimeError>;
5155
}
5256

57+
/// Trait implemented by tool dispatchers that execute model-requested tools.
5358
pub trait ToolExecutor {
5459
fn execute(&mut self, tool_name: &str, input: &str) -> Result<String, ToolError>;
5560
}
5661

62+
/// Error returned when a tool invocation fails locally.
5763
#[derive(Debug, Clone, PartialEq, Eq)]
5864
pub struct ToolError {
5965
message: String,
@@ -76,6 +82,7 @@ impl Display for ToolError {
7682

7783
impl std::error::Error for ToolError {}
7884

85+
/// Error returned when a conversation turn cannot be completed.
7986
#[derive(Debug, Clone, PartialEq, Eq)]
8087
pub struct RuntimeError {
8188
message: String,
@@ -98,6 +105,7 @@ impl Display for RuntimeError {
98105

99106
impl std::error::Error for RuntimeError {}
100107

108+
/// Summary of one completed runtime turn, including tool results and usage.
101109
#[derive(Debug, Clone, PartialEq, Eq)]
102110
pub struct TurnSummary {
103111
pub assistant_messages: Vec<ConversationMessage>,
@@ -108,11 +116,13 @@ pub struct TurnSummary {
108116
pub auto_compaction: Option<AutoCompactionEvent>,
109117
}
110118

119+
/// Details about automatic session compaction applied during a turn.
111120
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112121
pub struct AutoCompactionEvent {
113122
pub removed_message_count: usize,
114123
}
115124

125+
/// Coordinates the model loop, tool execution, hooks, and session updates.
116126
pub struct ConversationRuntime<C, T> {
117127
session: Session,
118128
api_client: C,
@@ -637,6 +647,7 @@ where
637647
}
638648
}
639649

650+
/// Reads the automatic compaction threshold from the environment.
640651
#[must_use]
641652
pub fn auto_compaction_threshold_from_env() -> u32 {
642653
parse_auto_compaction_threshold(
@@ -739,6 +750,7 @@ fn merge_hook_feedback(messages: &[String], output: String, is_error: bool) -> S
739750

740751
type ToolHandler = Box<dyn FnMut(&str) -> Result<String, ToolError>>;
741752

753+
/// Simple in-memory tool executor for tests and lightweight integrations.
742754
#[derive(Default)]
743755
pub struct StaticToolExecutor {
744756
handlers: BTreeMap<String, ToolHandler>,

0 commit comments

Comments
 (0)