1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
//! Agent helper functions and utilities.
use anyhow::Result;
use std::sync::atomic::Ordering;
use tokio::sync::mpsc;
use crate::event::AgentEvent;
use crate::providers::{ContentBlock, MessageContent, Role, Usage};
use crate::truncate::truncate_chars;
use super::types::Agent;
impl Agent {
/// Track token usage
pub(crate) fn track_usage(&self, usage: &Usage) {
self.total_input_tokens
.fetch_add(usage.input_tokens as u64, Ordering::Relaxed);
self.total_output_tokens
.fetch_add(usage.output_tokens as u64, Ordering::Relaxed);
self.last_input_tokens
.store(usage.input_tokens as u64, Ordering::Relaxed);
crate::debug::debug_log().log(
"usage",
&format!(
"tracked: input_tokens={}, output_tokens={}, cache_read={}, cache_created={}",
usage.input_tokens,
usage.output_tokens,
usage.cache_read_input_tokens,
usage.cache_creation_input_tokens
),
);
let _ = self.event_tx.try_send(AgentEvent::usage_with_cache(
self.total_input_tokens.load(Ordering::Relaxed),
usage.output_tokens as u64,
usage.cache_read_input_tokens as u64,
usage.cache_creation_input_tokens as u64,
));
}
/// Emit event (non-blocking)
pub(crate) fn emit(&self, event: AgentEvent) -> Result<()> {
log::debug!("Agent emit: event_type={:?}", event.event_type);
match self.event_tx.try_send(event) {
Ok(_) => {
log::debug!("Agent emit: sent successfully");
Ok(())
}
Err(mpsc::error::TrySendError::Full(_)) => {
log::warn!("Agent emit: channel full, skipping event");
Ok(())
}
Err(mpsc::error::TrySendError::Closed(_)) => {
log::error!("Agent emit: channel closed");
Err(anyhow::anyhow!("Event channel closed"))
}
}
}
/// Get pending (uncompleted) todos from the most recent todo_write.
/// Returns list of (status, content) for non-completed tasks that haven't exceeded reminder limit.
/// Note: todo_write replaces the entire list each time, so only the last one matters.
///
/// # Arguments
/// * `todo_reminder_count` - Reference to the reminder counter map (immutable, will be cloned inside)
/// * `max_reminders` - Maximum number of reminders allowed per todo (default: 2)
///
/// # Returns
/// Tuple of (pending todos, whether all todos are at reminder limit)
pub(crate) fn get_pending_todos_with_limit(
&self,
todo_reminder_count: &std::collections::HashMap<String, usize>,
max_reminders: usize,
) -> (Vec<(String, String)>, bool) {
// Find the most recent todo_write (current state)
for msg in self.messages.iter().rev().take(10) {
if let MessageContent::Blocks(blocks) = &msg.content {
for block in blocks {
if let ContentBlock::ToolUse { name, input, .. } = block
&& name == "todo_write"
{
// Extract non-completed todos from this todo_write
if let Some(todos) = input.get("todos").and_then(|t| t.as_array()) {
let pending: Vec<(String, String)> = todos
.iter()
.filter_map(|todo| {
let status = todo.get("status").and_then(|s| s.as_str())?;
let content = todo.get("content").and_then(|c| c.as_str())?;
if status != "completed" {
Some((status.to_string(), content.to_string()))
} else {
None
}
})
.collect();
// Check which todos are at the reminder limit
let mut filtered_pending = Vec::new();
let mut all_at_limit = true;
for (status, content) in pending {
let count = todo_reminder_count.get(&content).copied().unwrap_or(0);
if count < max_reminders {
filtered_pending.push((status, content));
all_at_limit = false;
}
}
return (filtered_pending, all_at_limit); // Return immediately - this is the current state
}
}
}
}
}
(Vec::new(), true)
}
/// Check if the last user message was a todo reminder.
/// This prevents adding duplicate reminders in consecutive iterations.
pub(crate) fn last_message_was_todo_reminder(&self) -> bool {
// Check the last few messages for a todo reminder
for msg in self.messages.iter().rev().take(3) {
if msg.role == Role::User {
if let MessageContent::Text(text) = &msg.content {
if text.contains("任务尚未完成") && text.contains("待办项需要处理") {
return true;
}
}
}
}
false
}
/// Legacy method for backwards compatibility
#[allow(dead_code)]
pub(crate) fn get_pending_todos(&self) -> Vec<(String, String)> {
// Find the most recent todo_write (current state)
for msg in self.messages.iter().rev().take(10) {
if let MessageContent::Blocks(blocks) = &msg.content {
for block in blocks {
if let ContentBlock::ToolUse { name, input, .. } = block
&& name == "todo_write"
{
// Extract non-completed todos from this todo_write
if let Some(todos) = input.get("todos").and_then(|t| t.as_array()) {
let pending: Vec<(String, String)> = todos
.iter()
.filter_map(|todo| {
let status = todo.get("status").and_then(|s| s.as_str())?;
let content = todo.get("content").and_then(|c| c.as_str())?;
if status != "completed" {
Some((status.to_string(), content.to_string()))
} else {
None
}
})
.collect();
return pending; // Return immediately - this is the current state
}
}
}
}
}
Vec::new()
}
}
/// Extract tool detail for display
pub(crate) fn extract_tool_detail(tool_name: &str, input: &serde_json::Value) -> Option<String> {
match tool_name.to_lowercase().as_str() {
"read" => input
.get("path")
.and_then(|v| v.as_str())
.map(|s| truncate_str(s, 50)),
"write" => input
.get("path")
.and_then(|v| v.as_str())
.map(|s| truncate_str(s, 50)),
"edit" | "multi_edit" => {
let path = input.get("path").and_then(|v| v.as_str());
let old = input.get("old_string").and_then(|v| v.as_str());
match (path, old) {
(Some(p), Some(o)) => Some(format!(
"{}: \"{}\"",
truncate_str(p, 30),
truncate_str(o, 20)
)),
(Some(p), None) => Some(truncate_str(p, 50)),
_ => None,
}
}
"bash" => input
.get("command")
.and_then(|v| v.as_str())
.map(|s| truncate_str(s, 60)),
"search" | "grep" => input
.get("pattern")
.and_then(|v| v.as_str())
.map(|s| format!("\"{}\"", truncate_str(s, 30))),
"glob" => input
.get("pattern")
.and_then(|v| v.as_str())
.map(|s| truncate_str(s, 40)),
"ls" => input
.get("path")
.and_then(|v| v.as_str())
.map(|s| truncate_str(s, 50)),
"websearch" => input
.get("query")
.and_then(|v| v.as_str())
.map(|s| truncate_str(s, 40)),
"webfetch" => input
.get("url")
.and_then(|v| v.as_str())
.map(|s| truncate_str(s, 50)),
"task" => input
.get("description")
.and_then(|v| v.as_str())
.map(|s| truncate_str(s, 40)),
"task_create" => input
.get("description")
.and_then(|v| v.as_str())
.map(|s| truncate_str(s, 40)),
"task_get" | "task_stop" => input
.get("task_id")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
_ => None,
}
}
/// Truncate string at char boundary (using character count, not bytes)
pub(crate) fn truncate_str(s: &str, max: usize) -> String {
truncate_chars(s, max)
}