1#[cfg(feature = "json")]
68use std::collections::HashMap;
69use std::fmt;
70use std::str::FromStr;
71
72use serde::{Deserialize, Serialize};
73
74#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(rename_all = "kebab-case")]
77pub enum SandboxMode {
78 ReadOnly,
80 #[default]
82 WorkspaceWrite,
83 DangerFullAccess,
85}
86
87impl SandboxMode {
88 pub(crate) fn as_arg(self) -> &'static str {
89 match self {
90 Self::ReadOnly => "read-only",
91 Self::WorkspaceWrite => "workspace-write",
92 Self::DangerFullAccess => "danger-full-access",
93 }
94 }
95}
96
97#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
104#[serde(rename_all = "kebab-case")]
105pub enum ApprovalPolicy {
106 Untrusted,
108 #[default]
110 OnRequest,
111 Never,
113}
114
115impl ApprovalPolicy {
116 pub(crate) fn as_arg(self) -> &'static str {
117 match self {
118 Self::Untrusted => "untrusted",
119 Self::OnRequest => "on-request",
120 Self::Never => "never",
121 }
122 }
123}
124
125#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
140#[serde(rename_all = "kebab-case")]
141pub enum ApprovalPolicyConfig {
142 Untrusted,
144 OnFailure,
149 #[default]
151 OnRequest,
152 Granular,
157 Never,
159}
160
161impl ApprovalPolicyConfig {
162 pub(crate) fn as_config_value(self) -> &'static str {
163 match self {
164 Self::Untrusted => "untrusted",
165 Self::OnFailure => "on-failure",
166 Self::OnRequest => "on-request",
167 Self::Granular => "granular",
168 Self::Never => "never",
169 }
170 }
171}
172
173impl From<ApprovalPolicy> for ApprovalPolicyConfig {
174 fn from(policy: ApprovalPolicy) -> Self {
175 match policy {
176 ApprovalPolicy::Untrusted => Self::Untrusted,
177 ApprovalPolicy::OnRequest => Self::OnRequest,
178 ApprovalPolicy::Never => Self::Never,
179 }
180 }
181}
182
183impl TryFrom<ApprovalPolicyConfig> for ApprovalPolicy {
184 type Error = ApprovalPolicyConfig;
185
186 fn try_from(config: ApprovalPolicyConfig) -> std::result::Result<Self, Self::Error> {
193 match config {
194 ApprovalPolicyConfig::Untrusted => Ok(Self::Untrusted),
195 ApprovalPolicyConfig::OnRequest => Ok(Self::OnRequest),
196 ApprovalPolicyConfig::Never => Ok(Self::Never),
197 other => Err(other),
198 }
199 }
200}
201
202#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
211#[serde(rename_all = "kebab-case")]
212pub enum WebSearchMode {
213 #[default]
215 Disabled,
216 Cached,
218 Indexed,
220 Live,
222}
223
224impl WebSearchMode {
225 pub(crate) fn as_config_value(self) -> &'static str {
226 match self {
227 Self::Disabled => "disabled",
228 Self::Cached => "cached",
229 Self::Indexed => "indexed",
230 Self::Live => "live",
231 }
232 }
233}
234
235#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
237#[serde(rename_all = "lowercase")]
238pub enum Color {
239 Always,
241 Never,
243 #[default]
245 Auto,
246}
247
248impl Color {
249 pub(crate) fn as_arg(self) -> &'static str {
250 match self {
251 Self::Always => "always",
252 Self::Never => "never",
253 Self::Auto => "auto",
254 }
255 }
256}
257
258#[cfg(feature = "json")]
263#[derive(Debug, Clone, Deserialize, Serialize)]
264pub struct JsonLineEvent {
265 #[serde(rename = "type", default)]
266 pub event_type: String,
267 #[serde(flatten)]
268 pub extra: HashMap<String, serde_json::Value>,
269}
270
271#[cfg(feature = "json")]
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280#[non_exhaustive]
281pub enum TurnFailureKind {
282 RolloutBudgetExhausted,
284 ApiRequestRejected,
291 Other,
293}
294
295#[cfg(feature = "json")]
307#[derive(Debug, Clone, PartialEq, Eq, Default)]
308#[non_exhaustive]
309pub struct ApiFailure {
310 pub error_type: Option<String>,
312 pub code: Option<String>,
314 pub status: Option<u64>,
316}
317
318#[cfg(feature = "json")]
319impl ApiFailure {
320 #[must_use]
325 pub fn rejected_request(&self) -> bool {
326 if self.error_type.as_deref() == Some("invalid_request_error") {
327 return true;
328 }
329 self.status
330 .is_some_and(|status| (400..500).contains(&status) && status != 429)
331 }
332}
333
334#[cfg(feature = "json")]
335impl JsonLineEvent {
336 #[must_use]
338 pub fn session_id(&self) -> Option<&str> {
339 self.extra.get("session_id").and_then(|v| v.as_str())
340 }
341
342 #[must_use]
344 pub fn thread_id(&self) -> Option<&str> {
345 self.extra.get("thread_id").and_then(|v| v.as_str())
346 }
347
348 #[must_use]
350 pub fn is_turn_completed(&self) -> bool {
351 self.event_type == "turn.completed"
352 }
353
354 #[must_use]
356 pub fn is_turn_failed(&self) -> bool {
357 self.event_type == "turn.failed"
358 }
359
360 #[must_use]
364 pub fn turn_failure_message(&self) -> Option<&str> {
365 if !self.is_turn_failed() {
366 return None;
367 }
368 self.extra
369 .get("error")
370 .and_then(|error| error.get("message"))
371 .and_then(serde_json::Value::as_str)
372 }
373
374 #[must_use]
380 pub fn turn_failure_api_error(&self) -> Option<ApiFailure> {
381 let message = self.turn_failure_message()?;
382 let document: serde_json::Value = serde_json::from_str(message).ok()?;
383 let error = document.get("error")?;
384 let failure = ApiFailure {
385 error_type: error
386 .get("type")
387 .and_then(serde_json::Value::as_str)
388 .map(str::to_owned),
389 code: error
390 .get("code")
391 .and_then(serde_json::Value::as_str)
392 .map(str::to_owned),
393 status: document.get("status").and_then(serde_json::Value::as_u64),
394 };
395 (failure != ApiFailure::default()).then_some(failure)
396 }
397
398 #[must_use]
400 pub fn turn_failure_kind(&self) -> Option<TurnFailureKind> {
401 self.is_turn_failed().then(|| {
402 if self
403 .turn_failure_message()
404 .is_some_and(|message| message.contains("shared rollout token budget exhausted"))
405 {
406 TurnFailureKind::RolloutBudgetExhausted
407 } else if self
408 .turn_failure_api_error()
409 .is_some_and(|error| error.rejected_request())
410 {
411 TurnFailureKind::ApiRequestRejected
412 } else {
413 TurnFailureKind::Other
414 }
415 })
416 }
417
418 #[must_use]
423 pub fn usage(&self) -> Option<TokenUsage> {
424 self.extra.get("usage").map(TokenUsage::from_json)
425 }
426
427 #[must_use]
438 pub fn agent_message_text(&self) -> Option<String> {
439 if self.event_type != "item.completed" {
440 return None;
441 }
442 let item = self.extra.get("item")?;
443 let kind = item
444 .get("item_type")
445 .or_else(|| item.get("type"))
446 .and_then(|v| v.as_str())?;
447 if kind != "agent_message" {
448 return None;
449 }
450
451 if let Some(text) = item.get("text").and_then(|v| v.as_str())
452 && !text.is_empty()
453 {
454 return Some(text.to_string());
455 }
456
457 let blocks = item.get("content").and_then(|v| v.as_array())?;
458 let text: String = blocks
459 .iter()
460 .filter_map(|b| b.get("text").and_then(|t| t.as_str()))
461 .collect::<Vec<_>>()
462 .join("");
463 if text.is_empty() { None } else { Some(text) }
464 }
465
466 #[must_use]
468 pub fn role(&self) -> Option<&str> {
469 self.extra.get("role").and_then(|v| v.as_str())
470 }
471
472 #[must_use]
477 pub fn content_text(&self) -> Option<String> {
478 let blocks = self.extra.get("content").and_then(|v| v.as_array())?;
479 let text: String = blocks
480 .iter()
481 .filter(|b| b.get("type").and_then(|t| t.as_str()) == Some("text"))
482 .filter_map(|b| b.get("text").and_then(|t| t.as_str()))
483 .collect::<Vec<_>>()
484 .join("");
485 if text.is_empty() { None } else { Some(text) }
486 }
487
488 #[must_use]
497 pub fn item_type(&self) -> Option<&str> {
498 let item = self.extra.get("item")?;
499 item.get("type").or_else(|| item.get("item_type"))?.as_str()
500 }
501
502 #[must_use]
508 pub fn command_execution(&self) -> Option<CommandExecution> {
509 if self.item_type()? != "command_execution" {
510 return None;
511 }
512 let item = self.extra.get("item")?;
513 let string = |key: &str| item.get(key).and_then(|v| v.as_str()).map(str::to_string);
514 Some(CommandExecution {
515 command: string("command"),
516 status: string("status"),
517 exit_code: item
518 .get("exit_code")
519 .and_then(serde_json::Value::as_i64)
520 .and_then(|code| i32::try_from(code).ok()),
521 aggregated_output: string("aggregated_output"),
522 })
523 }
524}
525
526#[cfg(feature = "json")]
534#[derive(Debug, Clone)]
535pub struct QueryResult {
536 pub result: String,
542 pub session_id: Option<String>,
548 pub thread_id: Option<String>,
553 pub usage: Option<TokenUsage>,
558 pub events: Vec<JsonLineEvent>,
563}
564
565#[cfg(feature = "json")]
566impl QueryResult {
567 #[must_use]
573 pub fn from_events(events: Vec<JsonLineEvent>) -> Self {
574 let usage = events
575 .iter()
576 .rev()
577 .find(|e| e.is_turn_completed())
578 .and_then(JsonLineEvent::usage);
579 let result = events
580 .iter()
581 .filter_map(JsonLineEvent::agent_message_text)
582 .collect::<Vec<_>>()
583 .join("");
584 let session_id = events
585 .iter()
586 .find_map(JsonLineEvent::session_id)
587 .map(str::to_string);
588 let thread_id = events
589 .iter()
590 .find_map(JsonLineEvent::thread_id)
591 .map(str::to_string);
592 Self {
593 result,
594 session_id,
595 thread_id,
596 usage,
597 events,
598 }
599 }
600
601 #[must_use]
607 pub fn final_message(&self) -> Option<String> {
608 crate::structured::final_message(&self.events)
609 }
610
611 pub fn decode_structured<T: serde::de::DeserializeOwned>(
618 &self,
619 ) -> std::result::Result<T, crate::structured::StructuredOutputError> {
620 crate::structured::decode(&self.events)
621 }
622}
623
624#[cfg(feature = "json")]
629#[derive(Debug, Clone, Default, PartialEq, Eq)]
630#[non_exhaustive]
631pub struct CommandExecution {
632 pub command: Option<String>,
634 pub status: Option<String>,
636 pub exit_code: Option<i32>,
638 pub aggregated_output: Option<String>,
640}
641
642#[cfg(feature = "json")]
653#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
654pub struct TokenUsage {
655 pub input_tokens: Option<u64>,
657 pub cached_input_tokens: Option<u64>,
659 pub cache_write_input_tokens: Option<u64>,
661 pub output_tokens: Option<u64>,
663 pub reasoning_output_tokens: Option<u64>,
665 pub total_tokens: Option<u64>,
667}
668
669#[cfg(feature = "json")]
670impl TokenUsage {
671 fn from_json(value: &serde_json::Value) -> Self {
672 let field = |name: &str| value.get(name).and_then(serde_json::Value::as_u64);
673 Self {
674 input_tokens: field("input_tokens"),
675 cached_input_tokens: field("cached_input_tokens"),
676 cache_write_input_tokens: field("cache_write_input_tokens"),
677 output_tokens: field("output_tokens"),
678 reasoning_output_tokens: field("reasoning_output_tokens"),
679 total_tokens: field("total_tokens"),
680 }
681 }
682
683 #[must_use]
689 pub fn total(&self) -> Option<u64> {
690 if let Some(total) = self.total_tokens {
691 return Some(total);
692 }
693 match (self.input_tokens, self.output_tokens) {
694 (None, None) => None,
695 (input, output) => Some(input.unwrap_or(0) + output.unwrap_or(0)),
696 }
697 }
698}
699
700#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
704pub struct CliVersion {
705 pub major: u32,
706 pub minor: u32,
707 pub patch: u32,
708}
709
710impl CliVersion {
711 #[must_use]
712 pub fn new(major: u32, minor: u32, patch: u32) -> Self {
713 Self {
714 major,
715 minor,
716 patch,
717 }
718 }
719
720 pub fn parse_version_output(output: &str) -> Result<Self, VersionParseError> {
721 output
722 .split_whitespace()
723 .find_map(|token| token.parse().ok())
724 .ok_or_else(|| VersionParseError(output.trim().to_string()))
725 }
726
727 #[must_use]
728 pub fn satisfies_minimum(&self, minimum: &CliVersion) -> bool {
729 self >= minimum
730 }
731
732 #[must_use]
744 pub fn status_within(&self, min: &CliVersion, max: &CliVersion) -> CliVersionStatus {
745 if self < min {
746 CliVersionStatus::OlderThanMinimum {
747 found: *self,
748 minimum: *min,
749 }
750 } else if self > max {
751 CliVersionStatus::NewerUntested {
752 found: *self,
753 tested_max: *max,
754 }
755 } else {
756 CliVersionStatus::Tested
757 }
758 }
759}
760
761#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
772#[serde(tag = "status", rename_all = "snake_case")]
773pub enum CliVersionStatus {
774 Tested,
776 NewerUntested {
780 found: CliVersion,
782 tested_max: CliVersion,
784 },
785 OlderThanMinimum {
791 found: CliVersion,
793 minimum: CliVersion,
795 },
796}
797
798impl CliVersionStatus {
799 #[must_use]
804 pub fn is_tested(self) -> bool {
805 matches!(self, Self::Tested)
806 }
807}
808
809impl PartialOrd for CliVersion {
810 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
811 Some(self.cmp(other))
812 }
813}
814
815impl Ord for CliVersion {
816 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
817 self.major
818 .cmp(&other.major)
819 .then(self.minor.cmp(&other.minor))
820 .then(self.patch.cmp(&other.patch))
821 }
822}
823
824impl fmt::Display for CliVersion {
825 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
826 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
827 }
828}
829
830impl FromStr for CliVersion {
831 type Err = VersionParseError;
832
833 fn from_str(s: &str) -> Result<Self, Self::Err> {
834 let parts: Vec<&str> = s.split('.').collect();
835 if parts.len() != 3 {
836 return Err(VersionParseError(s.to_string()));
837 }
838
839 Ok(Self {
840 major: parts[0]
841 .parse()
842 .map_err(|_| VersionParseError(s.to_string()))?,
843 minor: parts[1]
844 .parse()
845 .map_err(|_| VersionParseError(s.to_string()))?,
846 patch: parts[2]
847 .parse()
848 .map_err(|_| VersionParseError(s.to_string()))?,
849 })
850 }
851}
852
853#[derive(Debug, Clone, thiserror::Error)]
854#[error("invalid version string: {0:?}")]
855pub struct VersionParseError(pub String);
856
857#[cfg(test)]
858mod tests {
859 use super::*;
860
861 #[test]
862 fn parses_codex_version_output() {
863 let version = CliVersion::parse_version_output("codex-cli 0.145.0").unwrap();
864 assert_eq!(version, CliVersion::new(0, 145, 0));
865 }
866
867 #[test]
868 fn parses_plain_version_output() {
869 let version = CliVersion::parse_version_output("0.145.0").unwrap();
870 assert_eq!(version, CliVersion::new(0, 145, 0));
871 }
872
873 #[cfg(feature = "json")]
874 #[test]
875 fn json_line_event_session_and_thread_id() {
876 let event: JsonLineEvent = serde_json::from_str(
877 r#"{"type":"message.created","session_id":"sess_abc","thread_id":"thread_123"}"#,
878 )
879 .unwrap();
880 assert_eq!(event.session_id(), Some("sess_abc"));
881 assert_eq!(event.thread_id(), Some("thread_123"));
882 }
883
884 #[cfg(feature = "json")]
885 #[test]
886 fn json_line_event_turn_terminal_types() {
887 let completed: JsonLineEvent =
888 serde_json::from_str(r#"{"type":"turn.completed"}"#).unwrap();
889 assert!(completed.is_turn_completed());
890 assert!(!completed.is_turn_failed());
891
892 let failed: JsonLineEvent = serde_json::from_str(r#"{"type":"turn.failed"}"#).unwrap();
893 assert!(failed.is_turn_failed());
894 assert!(!failed.is_turn_completed());
895
896 let bogus: JsonLineEvent = serde_json::from_str(r#"{"type":"completed"}"#).unwrap();
898 assert!(!bogus.is_turn_completed());
899 }
900
901 #[cfg(feature = "json")]
904 #[test]
905 fn classifies_captured_rollout_budget_terminal_without_inventing_usage() {
906 let failed: JsonLineEvent = serde_json::from_str(
907 r#"{"type":"turn.failed","error":{"message":"shared rollout token budget exhausted"}}"#,
908 )
909 .unwrap();
910
911 assert_eq!(
912 failed.turn_failure_kind(),
913 Some(TurnFailureKind::RolloutBudgetExhausted)
914 );
915 assert_eq!(failed.usage(), None);
916
917 let other: JsonLineEvent = serde_json::from_str(
918 r#"{"type":"turn.failed","error":{"message":"tool policy rejected"}}"#,
919 )
920 .unwrap();
921 assert_eq!(other.turn_failure_kind(), Some(TurnFailureKind::Other));
922
923 let missing_message: JsonLineEvent =
924 serde_json::from_str(r#"{"type":"turn.failed"}"#).unwrap();
925 assert_eq!(
926 missing_message.turn_failure_kind(),
927 Some(TurnFailureKind::Other)
928 );
929
930 let nonterminal: JsonLineEvent =
931 serde_json::from_str(r#"{"type":"turn.started"}"#).unwrap();
932 assert_eq!(nonterminal.turn_failure_kind(), None);
933 }
934
935 #[cfg(feature = "json")]
939 #[test]
940 fn classifies_an_api_request_rejection() {
941 let missing_type: JsonLineEvent = serde_json::from_str(
942 r#"{"type":"turn.failed","error":{"message":"{\n \"type\": \"error\",\n \"error\": {\n \"type\": \"invalid_request_error\",\n \"code\": \"invalid_json_schema\",\n \"message\": \"Invalid schema for response_format 'codex_output_schema': In context=('properties', 'ok'), schema must have a 'type' key.\",\n \"param\": \"text.format.schema\"\n },\n \"status\": 400\n}"}}"#,
943 )
944 .unwrap();
945 assert_eq!(
946 missing_type.turn_failure_kind(),
947 Some(TurnFailureKind::ApiRequestRejected)
948 );
949 let error = missing_type.turn_failure_api_error().unwrap();
950 assert_eq!(error.code.as_deref(), Some("invalid_json_schema"));
951 assert_eq!(error.error_type.as_deref(), Some("invalid_request_error"));
952 assert_eq!(error.status, Some(400));
953 assert!(error.rejected_request());
954
955 let root_any_of: JsonLineEvent = serde_json::from_str(
956 r#"{"type":"turn.failed","error":{"message":"{\n \"type\": \"error\",\n \"error\": {\n \"type\": \"invalid_request_error\",\n \"code\": \"invalid_json_schema\",\n \"message\": \"Invalid schema for response_format 'codex_output_schema': schema must be a JSON Schema of 'type: \\\"object\\\"', got 'type: \\\"None\\\"'.\",\n \"param\": \"text.format.schema\"\n },\n \"status\": 400\n}"}}"#,
957 )
958 .unwrap();
959 assert_eq!(
960 root_any_of.turn_failure_kind(),
961 Some(TurnFailureKind::ApiRequestRejected)
962 );
963 assert_eq!(
964 root_any_of
965 .turn_failure_api_error()
966 .and_then(|error| error.code),
967 Some("invalid_json_schema".to_string())
968 );
969 }
970
971 #[cfg(feature = "json")]
974 #[test]
975 fn a_prose_failure_message_carries_no_api_error() {
976 let budget: JsonLineEvent = serde_json::from_str(
977 r#"{"type":"turn.failed","error":{"message":"shared rollout token budget exhausted"}}"#,
978 )
979 .unwrap();
980 assert_eq!(budget.turn_failure_api_error(), None);
981 assert_eq!(
982 budget.turn_failure_kind(),
983 Some(TurnFailureKind::RolloutBudgetExhausted)
984 );
985
986 let other: JsonLineEvent = serde_json::from_str(
987 r#"{"type":"turn.failed","error":{"message":"tool policy rejected"}}"#,
988 )
989 .unwrap();
990 assert_eq!(other.turn_failure_api_error(), None);
991 assert_eq!(other.turn_failure_kind(), Some(TurnFailureKind::Other));
992 }
993
994 #[cfg(feature = "json")]
998 #[test]
999 fn server_and_throttling_failures_are_not_request_rejections() {
1000 for (status, error_type) in [(500u64, "server_error"), (429, "rate_limit_error")] {
1001 let message = format!(
1002 r#"{{"type":"error","error":{{"type":"{error_type}","code":"x"}},"status":{status}}}"#
1003 );
1004 let event = JsonLineEvent {
1005 event_type: "turn.failed".to_string(),
1006 extra: HashMap::from([(
1007 "error".to_string(),
1008 serde_json::json!({ "message": message }),
1009 )]),
1010 };
1011 assert!(!event.turn_failure_api_error().unwrap().rejected_request());
1012 assert_eq!(event.turn_failure_kind(), Some(TurnFailureKind::Other));
1013 }
1014 }
1015
1016 #[cfg(feature = "json")]
1017 #[test]
1018 fn json_line_event_usage() {
1019 let event: JsonLineEvent = serde_json::from_str(
1020 r#"{"type":"turn.completed","usage":{"input_tokens":120,"output_tokens":45,"total_tokens":165}}"#,
1021 )
1022 .unwrap();
1023 let usage = event.usage().unwrap();
1024 assert_eq!(usage.input_tokens, Some(120));
1025 assert_eq!(usage.output_tokens, Some(45));
1026 assert_eq!(usage.total_tokens, Some(165));
1027 assert_eq!(usage.cache_write_input_tokens, None);
1029 assert_eq!(usage.total(), Some(165));
1030 }
1031
1032 #[cfg(feature = "json")]
1033 #[test]
1034 fn token_usage_total_falls_back_to_input_plus_output() {
1035 let usage = TokenUsage {
1036 input_tokens: Some(10),
1037 output_tokens: Some(5),
1038 ..TokenUsage::default()
1039 };
1040 assert_eq!(usage.total(), Some(15));
1041 }
1042
1043 #[cfg(feature = "json")]
1046 #[test]
1047 fn token_usage_total_is_none_when_nothing_reported() {
1048 assert_eq!(TokenUsage::default().total(), None);
1049 }
1050
1051 #[cfg(feature = "json")]
1053 #[test]
1054 fn agent_message_text_from_item_completed() {
1055 let event: JsonLineEvent = serde_json::from_str(
1056 r#"{"type":"item.completed","item":{"id":"item_0","type":"agent_message","text":"hello"}}"#,
1057 )
1058 .unwrap();
1059 assert_eq!(event.agent_message_text().as_deref(), Some("hello"));
1060 }
1061
1062 #[cfg(feature = "json")]
1067 #[test]
1068 fn agent_message_text_tolerates_layout_variants() {
1069 let item_type_key: JsonLineEvent = serde_json::from_str(
1070 r#"{"type":"item.completed","item":{"item_type":"agent_message","text":"a"}}"#,
1071 )
1072 .unwrap();
1073 assert_eq!(item_type_key.agent_message_text().as_deref(), Some("a"));
1074
1075 let content_blocks: JsonLineEvent = serde_json::from_str(
1076 r#"{"type":"item.completed","item":{"item_type":"agent_message","content":[{"text":"b"},{"text":"c"}]}}"#,
1077 )
1078 .unwrap();
1079 assert_eq!(content_blocks.agent_message_text().as_deref(), Some("bc"));
1080 }
1081
1082 #[cfg(feature = "json")]
1083 #[test]
1084 fn agent_message_text_ignores_other_items_and_events() {
1085 let other_item: JsonLineEvent = serde_json::from_str(
1087 r#"{"type":"item.completed","item":{"id":"item_0","type":"command_execution","command":"git diff","exit_code":0}}"#,
1088 )
1089 .unwrap();
1090 assert_eq!(other_item.agent_message_text(), None);
1091
1092 let other_event: JsonLineEvent = serde_json::from_str(
1093 r#"{"type":"item.started","item":{"id":"item_0","type":"agent_message","text":"x"}}"#,
1094 )
1095 .unwrap();
1096 assert_eq!(other_event.agent_message_text(), None);
1097 }
1098
1099 #[cfg(feature = "json")]
1100 #[test]
1101 fn json_line_event_role() {
1102 let event: JsonLineEvent =
1103 serde_json::from_str(r#"{"type":"message.created","role":"assistant"}"#).unwrap();
1104 assert_eq!(event.role(), Some("assistant"));
1105 }
1106
1107 #[cfg(feature = "json")]
1108 #[test]
1109 fn json_line_event_content_text() {
1110 let event: JsonLineEvent = serde_json::from_str(
1111 r#"{"type":"message.delta","content":[{"type":"text","text":"Hello "},{"type":"text","text":"world"}]}"#,
1112 )
1113 .unwrap();
1114 assert_eq!(event.content_text(), Some("Hello world".to_string()));
1115 }
1116
1117 #[cfg(feature = "json")]
1118 #[test]
1119 fn json_line_event_content_text_skips_non_text_blocks() {
1120 let event: JsonLineEvent = serde_json::from_str(
1121 r#"{"type":"message.delta","content":[{"type":"image","url":"x"},{"type":"text","text":"only this"}]}"#,
1122 )
1123 .unwrap();
1124 assert_eq!(event.content_text(), Some("only this".to_string()));
1125 }
1126
1127 #[cfg(feature = "json")]
1128 #[test]
1129 fn json_line_event_content_text_none_when_empty() {
1130 let event: JsonLineEvent =
1131 serde_json::from_str(r#"{"type":"message.delta","content":[]}"#).unwrap();
1132 assert_eq!(event.content_text(), None);
1133 }
1134
1135 #[cfg(feature = "json")]
1136 #[test]
1137 fn json_line_event_content_text_none_when_missing() {
1138 let event: JsonLineEvent = serde_json::from_str(r#"{"type":"message.delta"}"#).unwrap();
1139 assert_eq!(event.content_text(), None);
1140 }
1141
1142 #[cfg(feature = "json")]
1143 #[test]
1144 fn query_result_from_events() {
1145 let events: Vec<JsonLineEvent> = [
1146 r#"{"type":"thread.started","thread_id":"thread_1"}"#,
1147 r#"{"type":"item.completed","item":{"item_type":"agent_message","text":"the answer"}}"#,
1148 r#"{"type":"turn.completed","usage":{"input_tokens":7,"output_tokens":3,"total_tokens":10}}"#,
1149 ]
1150 .iter()
1151 .map(|l| serde_json::from_str(l).unwrap())
1152 .collect();
1153
1154 let result = QueryResult::from_events(events);
1155 assert_eq!(result.result, "the answer");
1156 assert_eq!(result.thread_id.as_deref(), Some("thread_1"));
1157 assert_eq!(result.usage.unwrap().total(), Some(10));
1158 assert_eq!(result.events.len(), 3);
1159 }
1160
1161 #[cfg(feature = "json")]
1162 #[test]
1163 fn query_result_concatenates_multiple_agent_messages() {
1164 let events: Vec<JsonLineEvent> = [
1165 r#"{"type":"item.completed","item":{"item_type":"agent_message","text":"one "}}"#,
1166 r#"{"type":"item.completed","item":{"item_type":"agent_message","text":"two"}}"#,
1167 r#"{"type":"turn.completed","usage":{"total_tokens":4}}"#,
1168 ]
1169 .iter()
1170 .map(|l| serde_json::from_str(l).unwrap())
1171 .collect();
1172
1173 assert_eq!(QueryResult::from_events(events).result, "one two");
1174 }
1175
1176 #[cfg(feature = "json")]
1179 #[test]
1180 fn query_result_from_a_failed_turn() {
1181 let events: Vec<JsonLineEvent> = [
1182 r#"{"type":"thread.started","thread_id":"thread_2"}"#,
1183 r#"{"type":"turn.failed","error":{"message":"usage limit"}}"#,
1184 ]
1185 .iter()
1186 .map(|l| serde_json::from_str(l).unwrap())
1187 .collect();
1188
1189 let result = QueryResult::from_events(events);
1190 assert_eq!(result.result, "");
1191 assert_eq!(result.usage, None);
1192 assert_eq!(result.thread_id.as_deref(), Some("thread_2"));
1193 }
1194
1195 #[cfg(feature = "json")]
1197 #[test]
1198 fn item_type_reads_the_discriminator() {
1199 let message: JsonLineEvent = serde_json::from_str(
1200 r#"{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"hi"}}"#,
1201 )
1202 .unwrap();
1203 assert_eq!(message.item_type(), Some("agent_message"));
1204
1205 let command: JsonLineEvent = serde_json::from_str(
1206 r#"{"type":"item.started","item":{"id":"item_0","type":"command_execution","command":"git diff"}}"#,
1207 )
1208 .unwrap();
1209 assert_eq!(command.item_type(), Some("command_execution"));
1210
1211 let turn: JsonLineEvent = serde_json::from_str(r#"{"type":"turn.completed"}"#).unwrap();
1212 assert_eq!(turn.item_type(), None);
1213 }
1214
1215 #[cfg(feature = "json")]
1218 #[test]
1219 fn command_execution_reads_a_finished_command() {
1220 let event: JsonLineEvent = serde_json::from_str(
1221 r#"{"type":"item.completed","item":{"id":"item_0","type":"command_execution","command":"git diff","aggregated_output":"","exit_code":0,"status":"completed"}}"#,
1222 )
1223 .unwrap();
1224
1225 let command = event.command_execution().unwrap();
1226 assert_eq!(command.command.as_deref(), Some("git diff"));
1227 assert_eq!(command.exit_code, Some(0));
1228 assert_eq!(command.status.as_deref(), Some("completed"));
1229 }
1230
1231 #[cfg(feature = "json")]
1233 #[test]
1234 fn command_execution_tolerates_a_command_still_running() {
1235 let event: JsonLineEvent = serde_json::from_str(
1236 r#"{"type":"item.started","item":{"id":"item_0","type":"command_execution","command":"git diff"}}"#,
1237 )
1238 .unwrap();
1239
1240 let command = event.command_execution().unwrap();
1241 assert_eq!(command.command.as_deref(), Some("git diff"));
1242 assert_eq!(command.exit_code, None);
1243 assert_eq!(command.status, None);
1244 }
1245
1246 #[cfg(feature = "json")]
1247 #[test]
1248 fn command_execution_is_none_for_other_items() {
1249 let event: JsonLineEvent = serde_json::from_str(
1250 r#"{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"hi"}}"#,
1251 )
1252 .unwrap();
1253 assert!(event.command_execution().is_none());
1254 }
1255}