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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
//! Agent streaming implementation.
use anyhow::Result;
use tokio::time::{Duration, sleep};
use crate::event::AgentEvent;
use crate::providers::{ChatRequest, ChatResponse, ContentBlock, StopReason, StreamEvent, Usage};
use super::types::Agent;
/// Wait for cancellation signal, checking periodically.
async fn wait_for_cancel_stream(token: &crate::cancel::CancellationToken) {
while !token.is_cancelled() {
sleep(Duration::from_millis(100)).await;
}
}
impl Agent {
/// Drain any pending input messages from the channel.
/// Called during streaming to collect real-time appended messages.
pub(crate) fn drain_pending_inputs(&mut self) {
if let Some(rx) = &mut self.pending_input_rx {
while let Ok(msg) = rx.try_recv() {
log::info!(
"Agent received pending input: {}",
msg.chars().take(50).collect::<String>()
);
self.pending_inputs.push(msg);
}
}
}
/// Check if there are pending inputs waiting to be processed.
pub fn has_pending_inputs(&self) -> bool {
!self.pending_inputs.is_empty()
}
/// Get and clear all pending inputs.
pub fn take_pending_inputs(&mut self) -> Vec<String> {
let inputs = self.pending_inputs.clone();
self.pending_inputs.clear();
inputs
}
/// Call provider with streaming and emit events in real-time.
/// Also monitors pending_input_rx for real-time message appending.
pub(crate) async fn call_streaming(&mut self, request: &ChatRequest) -> Result<ChatResponse> {
const MAX_RETRIES: u32 = 5;
const RETRY_DELAY_MS: u64 = 1000;
let mut attempt = 0;
loop {
attempt += 1;
log::info!(
"Agent: API call attempt {} with {} messages",
attempt,
request.messages.len()
);
if let Some(token) = &self.cancel_token
&& token.is_cancelled()
{
return Err(anyhow::anyhow!("Operation cancelled"));
}
log::info!("Agent: calling provider.chat_stream");
let rx_result = self.provider.chat_stream(request.clone()).await;
log::info!("Agent: provider.chat_stream returned");
match rx_result {
Ok(mut rx) => {
let mut response_content: Vec<ContentBlock> = Vec::new();
let mut current_text = String::new();
let mut current_thinking = String::new();
let mut usage = Usage {
input_tokens: 0,
output_tokens: 0,
cache_creation_input_tokens: 0,
cache_read_input_tokens: 0,
};
let mut should_retry = false;
loop {
// Use select! with cancellation and pending input checks
let event = if let Some(token) = &self.cancel_token {
tokio::select! {
// Primary: receive stream event
event = rx.recv() => event,
// Check for pending inputs periodically
_ = sleep(Duration::from_millis(50)) => {
self.drain_pending_inputs();
continue;
}
// Cancellation signal
_ = wait_for_cancel_stream(token) => {
return Err(anyhow::anyhow!("Operation cancelled"));
}
}
} else {
// No cancellation token, but still check pending inputs
tokio::select! {
event = rx.recv() => event,
_ = sleep(Duration::from_millis(50)) => {
self.drain_pending_inputs();
continue;
}
}
};
match event {
None => break,
Some(StreamEvent::FirstByte) => {}
Some(StreamEvent::ThinkingDelta(delta)) => {
// Check cancellation before emitting
if let Some(token) = &self.cancel_token
&& token.is_cancelled()
{
return Err(anyhow::anyhow!("Operation cancelled"));
}
if current_thinking.is_empty() {
self.emit(AgentEvent::thinking_start())?;
}
current_thinking.push_str(&delta);
self.emit(AgentEvent::thinking_delta(delta, None))?;
}
Some(StreamEvent::TextDelta(delta)) => {
// Check cancellation before emitting
if let Some(token) = &self.cancel_token
&& token.is_cancelled()
{
return Err(anyhow::anyhow!("Operation cancelled"));
}
if current_text.is_empty() {
self.emit(AgentEvent::text_start())?;
}
current_text.push_str(&delta);
self.emit(AgentEvent::text_delta(delta))?;
}
Some(StreamEvent::ToolUseStart { id, name }) => {
// Emit events for UI but don't push content blocks
// Content will be added from Done event's resp.content
if !current_thinking.is_empty() {
self.emit(AgentEvent::thinking_end())?;
// Don't push - will be added from resp.content
}
if !current_text.is_empty() {
self.emit(AgentEvent::text_end())?;
// Don't push - will be added from resp.content
}
self.emit(AgentEvent::tool_use_start(&id, &name, None))?;
}
Some(StreamEvent::ToolInputDelta { bytes_so_far: _ }) => {}
Some(StreamEvent::ToolInputComplete { id, name, input }) => {
self.previewed_tool_inputs.insert(id.clone());
self.emit(AgentEvent::tool_use_start(&id, &name, Some(input)))?;
}
Some(StreamEvent::Usage { output_tokens }) => {
self.emit(AgentEvent::usage_with_cache(
0,
output_tokens as u64,
0,
0,
))?;
usage.output_tokens = output_tokens;
}
Some(StreamEvent::Done(resp)) => {
// Check cancellation before processing final response
if let Some(token) = &self.cancel_token
&& token.is_cancelled()
{
return Err(anyhow::anyhow!("Operation cancelled"));
}
// Final drain of pending inputs before completing
self.drain_pending_inputs();
// Don't add current_thinking/current_text here - use resp.content directly
// This avoids duplicates since resp.content contains everything
// Just emit events for UI updates if we have pending content
if !current_thinking.is_empty() {
self.emit(AgentEvent::thinking_end())?;
// Don't push to response_content - will be added from resp.content
}
if !current_text.is_empty() {
self.emit(AgentEvent::text_end())?;
// Don't push to response_content - will be added from resp.content
}
// Add all blocks from final response with smart deduplication
for block in &resp.content {
// Smart deduplication: compare content, not entire block
let is_duplicate = response_content.iter().any(|b| {
match (b, block) {
// For Thinking blocks, compare thinking content only (signature may differ)
(
ContentBlock::Thinking { thinking: t1, .. },
ContentBlock::Thinking { thinking: t2, .. },
) => t1 == t2,
// For Text blocks, compare text content
(
ContentBlock::Text { text: t1 },
ContentBlock::Text { text: t2 },
) => t1 == t2,
// For ToolUse, compare id
(
ContentBlock::ToolUse { id: id1, .. },
ContentBlock::ToolUse { id: id2, .. },
) => id1 == id2,
// For ToolResult, compare tool_use_id
(
ContentBlock::ToolResult {
tool_use_id: id1, ..
},
ContentBlock::ToolResult {
tool_use_id: id2, ..
},
) => id1 == id2,
// Default: exact comparison
_ => b == block,
}
});
if !is_duplicate {
response_content.push(block.clone());
}
}
usage = resp.usage;
}
Some(StreamEvent::Error(msg)) => {
if attempt < MAX_RETRIES {
self.emit(AgentEvent::progress(
format!(
"⚠️ Stream error, retrying ({}/{}): {}",
attempt, MAX_RETRIES, &msg
),
None,
))?;
let delay = RETRY_DELAY_MS * (1 << (attempt - 1));
tokio::time::sleep(tokio::time::Duration::from_millis(delay))
.await;
should_retry = true;
break;
} else {
self.emit(AgentEvent::error(msg.clone(), None, None))?;
return Err(anyhow::anyhow!(
"Stream error after {} retries: {}",
MAX_RETRIES,
msg
));
}
}
}
}
if should_retry {
continue;
}
return Ok(ChatResponse {
content: response_content,
stop_reason: StopReason::EndTurn,
usage,
});
}
Err(e) => {
if attempt < MAX_RETRIES {
let error_msg = e.to_string();
self.emit(AgentEvent::progress(
format!(
"⚠️ API error, retrying ({}/{}): {}",
attempt, MAX_RETRIES, &error_msg
),
None,
))?;
let delay = RETRY_DELAY_MS * (1 << (attempt - 1));
tokio::time::sleep(tokio::time::Duration::from_millis(delay)).await;
} else {
return Err(anyhow::anyhow!(
"API error after {} retries: {}",
MAX_RETRIES,
e
));
}
}
}
}
}
}