Skip to content

Commit e6e40e2

Browse files
committed
chore(rust): align formatting and resolve clippy warnings
1 parent 5985914 commit e6e40e2

9 files changed

Lines changed: 122 additions & 83 deletions

File tree

src/agent.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ use uuid::Uuid;
1111
use crate::config::AgentConfig;
1212
use crate::logging::{summarize_json, summarize_text};
1313
use crate::providers::{
14-
ChatOptions, ContentPart, ConversationMessage, Provider, Role, StreamEvent,
15-
ThinkingBlock, ToolCall, ToolSpec, Usage,
14+
ChatOptions, ContentPart, ConversationMessage, Provider, Role, StreamEvent, ThinkingBlock,
15+
ToolCall, ToolSpec, Usage,
1616
};
1717
use crate::tools::{Tool, ToolResult};
1818
use crate::util::fs::atomic_write_text;
@@ -51,7 +51,10 @@ pub struct Agent {
5151
}
5252

5353
impl Agent {
54-
pub fn new(config: AgentConfig, compression_provider: (Arc<dyn Provider>, ChatOptions)) -> Self {
54+
pub fn new(
55+
config: AgentConfig,
56+
compression_provider: (Arc<dyn Provider>, ChatOptions),
57+
) -> Self {
5558
Self {
5659
history: Vec::new(),
5760
total_usage: Usage::default(),
@@ -104,7 +107,7 @@ impl Agent {
104107
CallStrategy::<fn(&str)>::Blocking,
105108
None,
106109
)
107-
.await
110+
.await
108111
}
109112

110113
pub async fn run_turn_stream(
@@ -365,7 +368,8 @@ impl Agent {
365368
let kind = meta.get("kind").and_then(serde_json::Value::as_str);
366369
match kind {
367370
Some("openai_reasoning_content_delta") => {
368-
if let Some(delta) = meta.get("delta").and_then(serde_json::Value::as_str)
371+
if let Some(delta) =
372+
meta.get("delta").and_then(serde_json::Value::as_str)
369373
{
370374
reasoning_buf.push_str(delta);
371375
}

src/channels/telegram.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -190,8 +190,7 @@ fn normalize_telegram_markdown(text: &str) -> String {
190190
fn escape_markdown_v2_char(ch: char, out: &mut String) {
191191
if matches!(
192192
ch,
193-
'\\'
194-
| '_'
193+
'\\' | '_'
195194
| '*'
196195
| '['
197196
| ']'
@@ -371,9 +370,10 @@ fn render_markdown_v2_safe(text: &str) -> String {
371370
}
372371
}
373372

374-
if let Some(inner) = rest.strip_prefix("**").and_then(|t| {
375-
t.find("**").map(|end| &t[..end]).filter(|t| !t.is_empty())
376-
}) {
373+
if let Some(inner) = rest
374+
.strip_prefix("**")
375+
.and_then(|t| t.find("**").map(|end| &t[..end]).filter(|t| !t.is_empty()))
376+
{
377377
out.push('*');
378378
out.push_str(&escape_markdown_v2_text(inner));
379379
out.push('*');

src/commands.rs

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -127,24 +127,31 @@ pub async fn try_handle_command(
127127
let skills = hot.skills.len();
128128
let pending = hot.todo.pending_count();
129129

130-
let has_assistant = agent.history.iter().any(|m| matches!(m.role, Role::Assistant));
130+
let has_assistant = agent
131+
.history
132+
.iter()
133+
.any(|m| matches!(m.role, Role::Assistant));
131134
let usage_warning = total == 0 && has_assistant;
132135

133136
let mut out = String::new();
134-
out.push_str(&format!("⚙️ System\n"));
137+
out.push_str("⚙️ System\n");
135138
out.push_str(&format!(" Version {}\n", env!("ZERDA_VERSION")));
136139
out.push_str(&format!(" Platform {platform} ({os_name})\n"));
137140
out.push_str(&format!(" Shell {shell}\n"));
138-
out.push_str(&format!("\n🤖 Provider\n"));
141+
out.push_str("\n🤖 Provider\n");
139142
out.push_str(&format!(" Provider {provider_name}\n"));
140143
out.push_str(&format!(" Model {model}\n"));
141144
out.push_str(&format!(" Temp/TopP {temp} / {top_p}\n"));
142-
out.push_str(&format!("\n💬 Session\n"));
143-
out.push_str(&format!(" History {non_system}/{max_history} messages\n"));
144-
out.push_str(&format!(" Tools {tool_total} ({builtin} builtin + {mcp} mcp)\n"));
145+
out.push_str("\n💬 Session\n");
146+
out.push_str(&format!(
147+
" History {non_system}/{max_history} messages\n"
148+
));
149+
out.push_str(&format!(
150+
" Tools {tool_total} ({builtin} builtin + {mcp} mcp)\n"
151+
));
145152
out.push_str(&format!(" Skills {skills} loaded\n"));
146153
out.push_str(&format!(" Todos {pending} pending\n"));
147-
out.push_str(&format!("\n📊 Tokens\n"));
154+
out.push_str("\n📊 Tokens\n");
148155
out.push_str(&format!(" Input {}\n", fmt_thousands(input_tokens)));
149156
out.push_str(&format!(" Output {}\n", fmt_thousands(output_tokens)));
150157
out.push_str(&format!(" Total {}", fmt_thousands(total)));
@@ -170,7 +177,7 @@ fn fmt_thousands(n: u64) -> String {
170177
let s = n.to_string();
171178
let mut result = String::with_capacity(s.len() + s.len() / 3);
172179
for (i, c) in s.chars().enumerate() {
173-
if i > 0 && (s.len() - i) % 3 == 0 {
180+
if i > 0 && (s.len() - i).is_multiple_of(3) {
174181
result.push(',');
175182
}
176183
result.push(c);

src/main.rs

Lines changed: 27 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -87,18 +87,16 @@ async fn main() -> Result<()> {
8787
print!("{}", include_str!("../zerda.toml.full"));
8888
return Ok(());
8989
}
90-
ConfigAction::Validate => {
91-
match config::load_config(cli.config.as_deref()) {
92-
Ok(_) => {
93-
println!("Configuration is valid.");
94-
return Ok(());
95-
}
96-
Err(e) => {
97-
eprintln!("Configuration error: {e}");
98-
std::process::exit(1);
99-
}
90+
ConfigAction::Validate => match config::load_config(cli.config.as_deref()) {
91+
Ok(_) => {
92+
println!("Configuration is valid.");
93+
return Ok(());
10094
}
101-
}
95+
Err(e) => {
96+
eprintln!("Configuration error: {e}");
97+
std::process::exit(1);
98+
}
99+
},
102100
}
103101
}
104102

@@ -154,19 +152,23 @@ async fn main() -> Result<()> {
154152
(Arc::from(p), opts)
155153
}
156154
Err(e) => {
157-
tracing::warn!("Failed to create fast_model provider, falling back to main provider: {e}");
155+
tracing::warn!(
156+
"Failed to create fast_model provider, falling back to main provider: {e}"
157+
);
158158
let p = providers::create_provider(&cfg.provider)
159159
.expect("main provider already validated");
160160
(Arc::from(p), chat_opts.clone())
161161
}
162162
}
163163
} else {
164-
let p = providers::create_provider(&cfg.provider)
165-
.expect("main provider already validated");
164+
let p = providers::create_provider(&cfg.provider).expect("main provider already validated");
166165
(Arc::from(p), chat_opts.clone())
167166
};
168167

169-
let subagent_provider = (Arc::clone(&fast_model_provider.0), fast_model_provider.1.clone());
168+
let subagent_provider = (
169+
Arc::clone(&fast_model_provider.0),
170+
fast_model_provider.1.clone(),
171+
);
170172

171173
let tools_runtime = tools::BuiltinToolsRuntime {
172174
tool_timeout: cfg.agent.tool_timeout,
@@ -181,7 +183,8 @@ async fn main() -> Result<()> {
181183
skill_cache: Arc::clone(&skill_cache),
182184
subagent_provider: Some(subagent_provider),
183185
};
184-
let (mut all_tools, todo_handle) = tools::builtin_tools((tools_runtime, tools_dependencies).into());
186+
let (mut all_tools, todo_handle) =
187+
tools::builtin_tools((tools_runtime, tools_dependencies).into());
185188

186189
let builtin_count = all_tools.len();
187190
let mcp_tools = tools::mcp::connect_mcp_servers(&cfg.mcp).await;
@@ -194,11 +197,16 @@ async fn main() -> Result<()> {
194197
None
195198
};
196199

197-
let system_prompt =
198-
prompt::build_system_prompt(identity_text.as_deref(), None);
200+
let system_prompt = prompt::build_system_prompt(identity_text.as_deref(), None);
199201

200202
let compression_provider = (fast_model_provider.0, fast_model_provider.1);
201-
let mut agent = agent::Agent::new(cfg.agent.clone(), (Arc::clone(&compression_provider.0), compression_provider.1.clone()));
203+
let mut agent = agent::Agent::new(
204+
cfg.agent.clone(),
205+
(
206+
Arc::clone(&compression_provider.0),
207+
compression_provider.1.clone(),
208+
),
209+
);
202210
agent.set_system_prompt(system_prompt);
203211

204212
let sessions_dir = config::resolve_path(config::MEMORY_DIR).join("sessions");

src/prompt.rs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,7 @@ static ENV_INFO: LazyLock<EnvInfo> = LazyLock::new(|| EnvInfo {
1414
package_manager: detect_package_manager(),
1515
});
1616

17-
pub fn build_system_prompt(
18-
identity: Option<&str>,
19-
channel_supplement: Option<&str>,
20-
) -> String {
17+
pub fn build_system_prompt(identity: Option<&str>, channel_supplement: Option<&str>) -> String {
2118
let mut parts: Vec<String> = Vec::new();
2219

2320
if let Some(id) = identity {

src/providers/anthropic.rs

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ use serde_json::{json, Value};
66

77
use super::{
88
sse_stream, truncate_for_log, ChatOptions, ContentPart, ConversationMessage, HttpClient,
9-
Provider, ProviderResponse, Role, StreamEvent, StreamResult, ThinkingBlock, ToolCall,
10-
ToolSpec, Usage,
9+
Provider, ProviderResponse, Role, StreamEvent, StreamResult, ThinkingBlock, ToolCall, ToolSpec,
10+
Usage,
1111
};
1212
use crate::config::ProviderConfig;
1313

@@ -183,7 +183,10 @@ impl AnthropicProvider {
183183
.and_then(Value::as_str)
184184
.map(std::string::ToString::to_string);
185185
if !thinking.is_empty() || signature.is_some() {
186-
thinking_blocks.push(ThinkingBlock::Thinking { thinking, signature });
186+
thinking_blocks.push(ThinkingBlock::Thinking {
187+
thinking,
188+
signature,
189+
});
187190
}
188191
}
189192
Some("redacted_thinking") => {
@@ -328,10 +331,7 @@ enum PendingThinkingKind {
328331
RedactedThinking,
329332
}
330333

331-
fn parse_sse_event(
332-
block: &str,
333-
state: &mut AnthropicStreamState,
334-
) -> Vec<Result<StreamEvent>> {
334+
fn parse_sse_event(block: &str, state: &mut AnthropicStreamState) -> Vec<Result<StreamEvent>> {
335335
let mut event_type = "";
336336
let mut data_str = String::new();
337337

@@ -373,7 +373,11 @@ fn parse_sse_event(
373373
let Some(cb) = data.get("content_block") else {
374374
return Vec::new();
375375
};
376-
let Some(index) = data.get("index").and_then(Value::as_u64).map(|v| v as usize) else {
376+
let Some(index) = data
377+
.get("index")
378+
.and_then(Value::as_u64)
379+
.map(|v| v as usize)
380+
else {
377381
return Vec::new();
378382
};
379383
let Some(block_type) = cb.get("type").and_then(Value::as_str) else {
@@ -419,7 +423,11 @@ fn parse_sse_event(
419423
let Some(delta) = data.get("delta") else {
420424
return Vec::new();
421425
};
422-
let Some(index) = data.get("index").and_then(Value::as_u64).map(|v| v as usize) else {
426+
let Some(index) = data
427+
.get("index")
428+
.and_then(Value::as_u64)
429+
.map(|v| v as usize)
430+
else {
423431
return Vec::new();
424432
};
425433
let Some(delta_type) = delta.get("type").and_then(Value::as_str) else {
@@ -472,7 +480,11 @@ fn parse_sse_event(
472480
}
473481
}
474482
"content_block_stop" => {
475-
let Some(index) = data.get("index").and_then(Value::as_u64).map(|v| v as usize) else {
483+
let Some(index) = data
484+
.get("index")
485+
.and_then(Value::as_u64)
486+
.map(|v| v as usize)
487+
else {
476488
return Vec::new();
477489
};
478490
let Some(pending) = state.pending_thinking.remove(&index) else {

src/runner.rs

Lines changed: 29 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -52,10 +52,7 @@ pub(crate) fn refresh_prompt(
5252
hot: &HotState,
5353
channel_supplement: Option<&str>,
5454
) {
55-
let system_prompt = build_system_prompt(
56-
hot.identity_text.as_deref(),
57-
channel_supplement,
58-
);
55+
let system_prompt = build_system_prompt(hot.identity_text.as_deref(), channel_supplement);
5956
agent.set_system_prompt(system_prompt);
6057
}
6158

@@ -181,7 +178,10 @@ async fn post_turn(agent: &mut agent::Agent, hot: &HotState) -> BudgetStatus {
181178
}
182179
}
183180

184-
if let Err(e) = agent.auto_compact(&config::resolve_path(config::MEMORY_DIR)).await {
181+
if let Err(e) = agent
182+
.auto_compact(&config::resolve_path(config::MEMORY_DIR))
183+
.await
184+
{
185185
tracing::warn!("Auto-compact failed: {e}");
186186
}
187187
BudgetStatus::Ok
@@ -272,10 +272,7 @@ fn light_reload_blockers(old_cfg: &Config, new_cfg: &Config) -> Vec<String> {
272272
if old_cfg.agent.max_memory_tokens != new_cfg.agent.max_memory_tokens {
273273
blockers.push("agent.max_memory_tokens".to_string());
274274
}
275-
if !fast_model_equal(
276-
&old_cfg.agent.fast_model,
277-
&new_cfg.agent.fast_model,
278-
) {
275+
if !fast_model_equal(&old_cfg.agent.fast_model, &new_cfg.agent.fast_model) {
279276
blockers.push("agent.fast_model".to_string());
280277
}
281278
if old_cfg.agent.show_usage != new_cfg.agent.show_usage {
@@ -588,7 +585,10 @@ pub async fn run_serve(
588585
} else {
589586
let mut fresh = agent::Agent::new(
590587
hot.cfg.agent.clone(),
591-
(Arc::clone(&hot.compression_provider.0), hot.compression_provider.1.clone()),
588+
(
589+
Arc::clone(&hot.compression_provider.0),
590+
hot.compression_provider.1.clone(),
591+
),
592592
);
593593
if let Ok((loaded_id, history)) =
594594
agent::Agent::load_session(sessions_dir, Some(&storage_id))
@@ -709,7 +709,10 @@ pub async fn run_serve(
709709
} else {
710710
let mut fresh = agent::Agent::new(
711711
hot.cfg.agent.clone(),
712-
(Arc::clone(&hot.compression_provider.0), hot.compression_provider.1.clone()),
712+
(
713+
Arc::clone(&hot.compression_provider.0),
714+
hot.compression_provider.1.clone(),
715+
),
713716
);
714717
if let Ok((loaded_id, history)) =
715718
agent::Agent::load_session(sessions_dir, Some(&storage_id))
@@ -760,21 +763,23 @@ pub async fn run_serve(
760763
let sender = sender.clone();
761764
let token = typing_cancel.clone();
762765
let span = turn_span.clone();
763-
tokio::spawn(async move {
764-
loop {
765-
if token.is_cancelled() {
766-
break;
767-
}
768-
if let Err(e) = ch.send_typing(&sender).await {
769-
tracing::debug!("Failed to send typing event: {e}");
770-
}
771-
tokio::select! {
772-
() = token.cancelled() => break,
773-
() = tokio::time::sleep(std::time::Duration::from_secs(4)) => {}
766+
tokio::spawn(
767+
async move {
768+
loop {
769+
if token.is_cancelled() {
770+
break;
771+
}
772+
if let Err(e) = ch.send_typing(&sender).await {
773+
tracing::debug!("Failed to send typing event: {e}");
774+
}
775+
tokio::select! {
776+
() = token.cancelled() => break,
777+
() = tokio::time::sleep(std::time::Duration::from_secs(4)) => {}
778+
}
774779
}
775780
}
776-
}
777-
.instrument(span));
781+
.instrument(span),
782+
);
778783
}
779784

780785
let mut tool_phase_handle = None;

src/tools/subagent.rs

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,7 @@ pub struct SubAgentTool {
2424
}
2525

2626
impl SubAgentTool {
27-
pub fn new(
28-
provider: Arc<dyn Provider>,
29-
mut chat_opts: ChatOptions,
30-
tool_timeout: u64,
31-
) -> Self {
27+
pub fn new(provider: Arc<dyn Provider>, mut chat_opts: ChatOptions, tool_timeout: u64) -> Self {
3228
chat_opts.max_tokens = MAX_TOKENS;
3329
Self {
3430
provider,

0 commit comments

Comments
 (0)