1use std::pin::Pin;
8use std::sync::Arc;
9
10use crate::protocol::{
11 AssistantBlock, BackgroundTask, InboundMessage, InboundUserMessage, ResultMessage, TurnErrorKind,
12 UserMessage,
13};
14use crate::session::{Session, SessionError};
15
16#[derive(Debug, Clone)]
20#[non_exhaustive]
21pub enum AgentEvent {
22 Text(String),
24 Thinking(String),
26 RedactedThinking(String),
28 ToolUse {
31 id: String,
33 name: String,
35 input: serde_json::Value,
37 server: bool,
39 },
40 ToolResult {
44 tool_use_id: String,
46 content: serde_json::Value,
48 is_error: bool,
50 structured: Option<serde_json::Value>,
52 },
53 Subagent {
56 parent_tool_use_id: String,
58 event: Box<AgentEvent>,
60 },
61 BackgroundTasks(Vec<BackgroundTask>),
63 ModelFallback {
65 from: String,
67 to: String,
69 trigger: String,
71 },
72 Compacted {
74 trigger: String,
76 pre_tokens: Option<u64>,
78 post_tokens: Option<u64>,
80 },
81 System {
84 subtype: String,
86 data: serde_json::Value,
88 },
89 Other {
92 kind: String,
94 data: serde_json::Value,
96 },
97 Done(TurnResult),
99 Error(TurnError),
101}
102
103#[derive(Debug, Clone, PartialEq)]
105#[non_exhaustive]
106pub struct TurnResult {
107 pub session_id: Option<String>,
109 pub result: Option<String>,
111 pub structured_output: Option<serde_json::Value>,
113 pub total_cost_usd: Option<f64>,
115 pub ttft_ms: Option<u64>,
117 pub duration_ms: Option<u64>,
119 pub duration_api_ms: Option<u64>,
121 pub num_turns: Option<u64>,
123 pub input_tokens: Option<u64>,
125 pub output_tokens: Option<u64>,
127 pub cache_read_input_tokens: Option<u64>,
129 pub cache_creation_input_tokens: Option<u64>,
131 pub model_usage: Option<serde_json::Value>,
133 pub stop_reason: Option<String>,
135 pub terminal_reason: Option<String>,
137 pub permission_denials: Vec<serde_json::Value>,
139 pub origin: Option<serde_json::Value>,
142}
143
144impl From<&ResultMessage> for TurnResult {
145 fn from(r: &ResultMessage) -> Self {
146 let usage = r.usage.as_ref();
147 TurnResult {
148 session_id: r.session_id.clone(),
149 result: r.result.clone(),
150 structured_output: r.structured_output.clone(),
151 total_cost_usd: r.total_cost_usd,
152 ttft_ms: r.ttft_ms,
153 duration_ms: r.duration_ms,
154 duration_api_ms: r.duration_api_ms,
155 num_turns: r.num_turns,
156 input_tokens: usage.map(|u| u.input_tokens),
157 output_tokens: usage.map(|u| u.output_tokens),
158 cache_read_input_tokens: usage.and_then(|u| u.cache_read_input_tokens),
159 cache_creation_input_tokens: usage.and_then(|u| u.cache_creation_input_tokens),
160 model_usage: r.model_usage.clone(),
161 stop_reason: r.stop_reason.clone(),
162 terminal_reason: r.terminal_reason.clone(),
163 permission_denials: r.permission_denials.clone(),
164 origin: r.origin.clone(),
165 }
166 }
167}
168
169#[derive(Debug, Clone, PartialEq, thiserror::Error)]
171#[error("{message}")]
172#[non_exhaustive]
173pub struct TurnError {
174 pub kind: TurnErrorKind,
176 pub message: String,
178 pub result: Option<TurnResult>,
181}
182
183impl From<&ResultMessage> for TurnError {
184 fn from(r: &ResultMessage) -> Self {
185 TurnError { kind: r.error_kind(), message: r.error_message(), result: Some(TurnResult::from(r)) }
186 }
187}
188
189impl TurnError {
190 fn cancelled() -> Self {
191 TurnError { kind: TurnErrorKind::Cancelled, message: "prompt cancelled before it ran".into(), result: None }
192 }
193
194 fn session_closed() -> Self {
195 TurnError {
196 kind: TurnErrorKind::SessionClosed,
197 message: "session closed before the turn finished".into(),
198 result: None,
199 }
200 }
201}
202
203#[derive(Debug, thiserror::Error)]
205#[non_exhaustive]
206pub enum AgentError {
207 #[error("session error: {0}")]
209 Session(#[from] SessionError),
210}
211
212pub type AgentStream = Pin<Box<dyn tokio_stream::Stream<Item = AgentEvent> + Send + 'static>>;
215
216pub struct Agent {
220 session: Session,
221}
222
223impl Agent {
224 #[must_use]
226 pub fn new(session: Session) -> Self {
227 Self { session }
228 }
229
230 #[must_use]
232 pub fn session(&self) -> &Session {
233 &self.session
234 }
235
236 pub async fn prompt(&self, text: impl Into<String>) -> Result<AgentStream, AgentError> {
240 self.prompt_message(UserMessage::text(text.into())).await
241 }
242
243 pub async fn prompt_message(&self, message: UserMessage) -> Result<AgentStream, AgentError> {
249 let mut rx = self.session.subscribe();
251 let uuid = message.uuid.clone();
252 self.session.send_prompt(&message).await?;
253 let partial = self.session.include_partial();
256 let span = tracing::info_span!(
258 "claude.turn",
259 session_id = self.session.session_id().unwrap_or_default(),
260 cost_usd = tracing::field::Empty,
261 input_tokens = tracing::field::Empty,
262 output_tokens = tracing::field::Empty,
263 ttft_ms = tracing::field::Empty,
264 error = tracing::field::Empty,
265 );
266
267 let mut guard = CancelOnDrop { session: self.session.clone(), uuid: uuid.clone(), armed: true };
271 let stream = async_stream::stream! {
272 let mut started = false;
280 let mut held: Vec<Arc<InboundMessage>> = vec![];
281 loop {
282 let Some(msg) = rx.recv().await else {
283 guard.disarm();
284 yield AgentEvent::Error(TurnError::session_closed());
285 break;
286 };
287 if let InboundMessage::Other(frame) = msg.as_ref()
290 && is_cancelled(frame, &uuid)
291 {
292 guard.disarm();
293 yield AgentEvent::Error(TurnError::cancelled());
294 break;
295 }
296
297 if !started {
298 match msg.as_ref() {
299 InboundMessage::User(u) if u.uuid.as_deref() == Some(uuid.as_str()) => {
300 started = true;
301 for m in held.drain(..) {
302 for ev in to_events(&m, partial) {
303 yield ev;
304 }
305 }
306 }
307 InboundMessage::Result(r) if r.answers(&uuid) => {
310 started = true;
311 for m in held.drain(..) {
312 for ev in to_events(&m, partial) {
313 yield ev;
314 }
315 }
316 }
317 InboundMessage::Result(_) => {
318 held.clear();
319 continue;
320 }
321 _ => {
322 held.push(msg);
323 continue;
324 }
325 }
326 if !matches!(msg.as_ref(), InboundMessage::Result(_)) {
327 continue;
328 }
329 }
330
331 if let InboundMessage::Result(r) = msg.as_ref() {
332 guard.disarm();
333 let t = TurnResult::from(r);
334 if let Some(v) = t.total_cost_usd { span.record("cost_usd", v); }
335 if let Some(v) = t.input_tokens { span.record("input_tokens", v); }
336 if let Some(v) = t.output_tokens { span.record("output_tokens", v); }
337 if let Some(v) = t.ttft_ms { span.record("ttft_ms", v); }
338 if !r.is_success() { span.record("error", r.subtype.as_str()); }
339 }
340 let done = matches!(msg.as_ref(), InboundMessage::Result(_));
341 for ev in to_events(&msg, partial) {
342 yield ev;
343 }
344 if done {
345 break;
346 }
347 }
348 };
349
350 Ok(Box::pin(stream))
351 }
352
353 pub fn watch(&self) -> AgentStream {
359 let mut rx = self.session.subscribe();
360 let partial = self.session.include_partial();
361 Box::pin(async_stream::stream! {
362 while let Some(msg) = rx.recv().await {
363 for ev in to_events(&msg, partial) {
364 yield ev;
365 }
366 }
367 })
368 }
369}
370
371struct CancelOnDrop {
373 session: Session,
374 uuid: String,
375 armed: bool,
376}
377
378impl CancelOnDrop {
379 fn disarm(&mut self) {
380 self.armed = false;
381 }
382}
383
384impl Drop for CancelOnDrop {
385 fn drop(&mut self) {
386 if !self.armed || !self.session.is_alive() {
387 return;
388 }
389 let Ok(rt) = tokio::runtime::Handle::try_current() else {
390 tracing::warn!("turn stream dropped outside a Tokio runtime; the turn keeps running");
391 return;
392 };
393 let session = self.session.clone();
394 let uuid = std::mem::take(&mut self.uuid);
395 rt.spawn(async move {
396 if let Err(e) = session.cancel_prompt(&uuid).await {
397 tracing::debug!(error = %e, "cancelling a dropped turn failed");
398 }
399 });
400 }
401}
402
403fn to_events(msg: &InboundMessage, partial: bool) -> Vec<AgentEvent> {
408 match msg {
409 InboundMessage::Assistant(a) => {
410 let sub = a.parent_tool_use_id.is_some();
411 let events = a.message.content.iter().filter_map(|block| match block {
412 AssistantBlock::Text { text } if sub || !partial => Some(AgentEvent::Text(text.clone())),
413 AssistantBlock::Thinking { thinking } if sub || !partial => {
414 Some(AgentEvent::Thinking(thinking.clone()))
415 }
416 AssistantBlock::RedactedThinking { data } => Some(AgentEvent::RedactedThinking(data.clone())),
417 AssistantBlock::ToolUse { id, name, input } => Some(AgentEvent::ToolUse {
418 id: id.clone(),
419 name: name.clone(),
420 input: input.clone(),
421 server: false,
422 }),
423 AssistantBlock::ServerToolUse { id, name, input } => Some(AgentEvent::ToolUse {
424 id: id.clone(),
425 name: name.clone(),
426 input: input.clone(),
427 server: true,
428 }),
429 AssistantBlock::WebSearchToolResult { tool_use_id, content } => Some(AgentEvent::ToolResult {
430 tool_use_id: tool_use_id.clone(),
431 content: content.clone(),
432 is_error: false,
433 structured: None,
434 }),
435 _ => None,
436 });
437 in_thread(a.parent_tool_use_id.as_deref(), events.collect())
438 }
439
440 InboundMessage::User(u) => in_thread(u.parent_tool_use_id.as_deref(), tool_results(u)),
441
442 InboundMessage::StreamEvent(se) if se.parent_tool_use_id.is_none() => {
443 let delta = se.event.get("delta");
444 let text = delta.and_then(|d| d.get("text")).and_then(|t| t.as_str());
445 let thinking = delta.and_then(|d| d.get("thinking")).and_then(|t| t.as_str());
446 text.map(|t| AgentEvent::Text(t.to_string()))
447 .into_iter()
448 .chain(thinking.map(|t| AgentEvent::Thinking(t.to_string())))
449 .collect()
450 }
451
452 InboundMessage::System(s) => match s.subtype.as_str() {
453 "background_tasks_changed" => {
454 let tasks = s.extra.get("tasks").cloned().unwrap_or_default();
455 match serde_json::from_value::<Vec<BackgroundTask>>(tasks) {
456 Ok(tasks) => vec![AgentEvent::BackgroundTasks(tasks)],
457 Err(e) => {
458 tracing::debug!(error = %e, "undecodable background_tasks_changed");
459 vec![]
460 }
461 }
462 }
463 "model_fallback" => {
464 let field = |k: &str| s.extra.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string();
465 vec![AgentEvent::ModelFallback {
466 from: field("original_model"),
467 to: field("fallback_model"),
468 trigger: field("trigger"),
469 }]
470 }
471 "compact_boundary" => {
472 let meta = s.extra.get("compact_metadata");
473 let num = |k: &str| meta.and_then(|m| m.get(k)).and_then(serde_json::Value::as_u64);
474 vec![AgentEvent::Compacted {
475 trigger: meta.and_then(|m| m.get("trigger")).and_then(|v| v.as_str()).unwrap_or("").to_string(),
476 pre_tokens: num("pre_tokens"),
477 post_tokens: num("post_tokens"),
478 }]
479 }
480 other => vec![AgentEvent::System {
481 subtype: other.to_string(),
482 data: serde_json::to_value(s).unwrap_or_else(|e| {
483 tracing::warn!(error = %e, "could not serialize a system frame");
484 serde_json::Value::Null
485 }),
486 }],
487 },
488
489 InboundMessage::Other(data) => vec![AgentEvent::Other {
490 kind: data.get("type").and_then(|t| t.as_str()).unwrap_or("").to_string(),
491 data: data.clone(),
492 }],
493
494 InboundMessage::Result(r) if r.is_success() => vec![AgentEvent::Done(TurnResult::from(r))],
495 InboundMessage::Result(r) => vec![AgentEvent::Error(TurnError::from(r))],
496
497 _ => vec![],
498 }
499}
500
501fn tool_results(u: &InboundUserMessage) -> Vec<AgentEvent> {
504 let results = u.tool_results();
505 let structured = if results.len() == 1 { u.tool_use_result.clone() } else { None };
506 results
507 .into_iter()
508 .map(|r| AgentEvent::ToolResult {
509 tool_use_id: r.tool_use_id,
510 content: r.content,
511 is_error: r.is_error,
512 structured: structured.clone(),
513 })
514 .collect()
515}
516
517fn is_cancelled(frame: &serde_json::Value, uuid: &str) -> bool {
519 let field = |k: &str| frame.get(k).and_then(|v| v.as_str());
520 field("type") == Some("command_lifecycle")
521 && field("state") == Some("cancelled")
522 && field("command_uuid").is_some_and(|u| u.eq_ignore_ascii_case(uuid))
523}
524
525fn in_thread(parent: Option<&str>, events: Vec<AgentEvent>) -> Vec<AgentEvent> {
527 match parent {
528 None => events,
529 Some(p) => events
530 .into_iter()
531 .map(|event| AgentEvent::Subagent { parent_tool_use_id: p.to_string(), event: Box::new(event) })
532 .collect(),
533 }
534}