coralogix-cli 0.1.38

Coralogix CLI - the observability backbone for AI agents and engineering teams.
Documentation
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::api_client::CxClient;
use crate::error::Result;

// ── Base paths ─────────────────────────────────────────────────────────────────

const CHATS_BASE: &str = "/api/v2/olly/v2/chats";
const ARTIFACTS_BASE: &str = "/api/v2/olly/artifacts";
const INTERACTION_SOURCE_HEADER: (&str, &str) = ("interaction-source", "cli");

// ── Request types ──────────────────────────────────────────────────────────────

#[derive(Debug, Serialize)]
pub struct InputContentBlock {
    #[serde(rename = "type")]
    pub content_type: String,
    pub text: String,
}

impl InputContentBlock {
    pub fn text(text: &str) -> Self {
        Self {
            content_type: "input_text".to_string(),
            text: text.to_string(),
        }
    }
}

// ── Response types ─────────────────────────────────────────────────────────────
// Note: The Olly API uses snake_case for JSON fields (not camelCase like other CX APIs)

#[derive(Debug, Deserialize)]
pub struct SharedOptions {
    pub shared_type: Option<String>,
    pub shared_entity_ids: Option<Vec<String>>,
}

#[derive(Debug, Deserialize)]
pub struct Chat {
    pub id: String,
    #[serde(default)]
    pub title: String,
    pub user_id: Option<String>,
    pub created_at: Option<String>,
    #[serde(rename = "type")]
    pub chat_type: Option<String>,
    pub shared_options: Option<SharedOptions>,
    pub metadata: Option<Value>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct TextContentBlock {
    pub text: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct FileContentBlock {
    pub file_id: Option<String>,
    pub filename: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentBlock {
    Text(TextContentBlock),
    File(FileContentBlock),
    #[serde(other)]
    Unknown,
}

impl ContentBlock {
    pub fn as_text(&self) -> Option<&str> {
        match self {
            ContentBlock::Text(t) => Some(&t.text),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct Message {
    pub id: Option<String>,
    pub role: String,
    #[serde(default)]
    pub content: Vec<ContentBlock>,
}

impl Message {
    pub fn text_content(&self) -> String {
        self.content
            .iter()
            .filter_map(|c| c.as_text())
            .collect::<Vec<_>>()
            .join("\n")
    }
}

#[derive(Debug, Deserialize)]
pub struct Interaction {
    pub id: String,
    pub chat_id: String,
    pub status: String,
    pub created_at: Option<String>,
    pub interaction_mode: Option<String>,
    pub model_choice: Option<String>,
    #[serde(default)]
    pub data_sources: Vec<Value>,
    pub feedback: Option<String>,
    pub feedback_description: Option<String>,
    #[serde(default)]
    pub responses: Option<Vec<Message>>,
}

impl Interaction {
    pub fn is_completed(&self) -> bool {
        self.status.eq_ignore_ascii_case("completed")
    }

    pub fn is_error(&self) -> bool {
        self.status.eq_ignore_ascii_case("error")
    }

    pub fn is_stopped(&self) -> bool {
        self.status.eq_ignore_ascii_case("stopped")
    }

    pub fn is_timed_out(&self) -> bool {
        self.status.eq_ignore_ascii_case("timed_out")
    }

    pub fn is_terminal(&self) -> bool {
        self.is_completed() || self.is_error() || self.is_stopped() || self.is_timed_out()
    }

    pub fn assistant_text(&self) -> Option<String> {
        self.responses.as_ref().and_then(|msgs| {
            let text: Vec<String> = msgs
                .iter()
                .filter(|m| m.role == "assistant")
                .map(|m| m.text_content())
                .filter(|t| !t.is_empty())
                .collect();
            if text.is_empty() {
                None
            } else {
                Some(text.join("\n\n"))
            }
        })
    }
}

#[derive(Debug, Deserialize)]
pub struct ChatWithMessages {
    pub id: String,
    #[serde(default)]
    pub title: String,
    #[serde(default)]
    pub messages: Vec<Message>,
    #[serde(default)]
    pub interactions: Vec<Interaction>,
}

#[derive(Debug, Deserialize)]
pub struct Artifact {
    pub id: Option<String>,
    pub download_url: Option<String>,
    pub filename: Option<String>,
    pub content_type: Option<String>,
    pub size: Option<u64>,
}

/// One row of `GET /artifacts/`. The list response carries no download URL or
/// query params; those come from `get_artifact`.
#[derive(Debug, Deserialize)]
pub struct ArtifactListItem {
    pub id: Option<String>,
    pub created_at: Option<String>,
    #[serde(rename = "type")]
    pub artifact_type: Option<String>,
    pub chat_id: Option<String>,
    pub chat_title: Option<String>,
    pub chat_type: Option<String>,
    pub interaction_id: Option<String>,
}

/// Values the server accepts for the `artifact_type` filter.
pub const ARTIFACT_TYPES: [&str; 7] = [
    "coralogix_dataprime",
    "coralogix_metrics",
    "kubernetes_query_results",
    "alert_watch_data",
    "github_file_content",
    "sandbox_generated_file",
    "schema_health_suggestions",
];

/// Filters for `list_artifacts`. `start` and `end` are ISO 8601 timestamps.
#[derive(Debug, Default)]
pub struct ArtifactListFilters {
    pub chat_id: Option<String>,
    pub artifact_type: Option<String>,
    pub start: Option<String>,
    pub end: Option<String>,
    pub limit: Option<u32>,
    pub offset: Option<u32>,
}

// ── API client ─────────────────────────────────────────────────────────────────

/// Olly API client.
/// Uses standard Bearer token authentication like other Coralogix APIs.
pub struct OllyApi {
    client: CxClient,
}

impl OllyApi {
    /// Create an Olly API client from the configured shared HTTP client.
    pub fn from_client(client: CxClient) -> Self {
        Self { client }
    }

    // ── Chats ──────────────────────────────────────────────────────────────────

    pub async fn create_chat(&self) -> Result<Chat> {
        self.client
            .post_empty(&format!("{CHATS_BASE}/"), &[("chat_type", "ai_connector")])
            .await
    }

    /// List chats, most recently active first. `metadata` is a JSON object
    /// the API matches by containment before it applies `skip` and `limit`.
    pub async fn list_chats(
        &self,
        limit: u32,
        skip: u32,
        chat_type: Option<&str>,
        metadata: Option<&str>,
    ) -> Result<Vec<Value>> {
        let (limit, skip) = (limit.to_string(), skip.to_string());
        let mut params = vec![("limit", limit.as_str()), ("skip", skip.as_str())];
        if let Some(chat_type) = chat_type {
            params.push(("chat_type", chat_type));
        }
        if let Some(metadata) = metadata {
            params.push(("metadata", metadata));
        }
        self.client.get(&format!("{CHATS_BASE}/"), &params).await
    }

    /// The full chat as the API returns it. Parse it into
    /// [`ChatWithMessages`] to walk the conversation.
    pub async fn get_chat(&self, chat_id: &str) -> Result<Value> {
        let path = format!("{CHATS_BASE}/{chat_id}");
        self.client
            .get(&path, &[("response_format", "content_blocks")])
            .await
    }

    pub async fn rename_chat(&self, chat_id: &str, title: &str) -> Result<()> {
        let path = format!("{CHATS_BASE}/{chat_id}/title");
        let _: Value = self.client.patch(&path, &json!({ "title": title })).await?;
        Ok(())
    }

    /// Delete a chat with its interactions, artifacts and uploaded files.
    /// Only the owner can delete; the API answers 404 for anyone else.
    pub async fn delete_chat(&self, chat_id: &str) -> Result<()> {
        let _: Value = self
            .client
            .delete(&format!("{CHATS_BASE}/{chat_id}"))
            .await?;
        Ok(())
    }

    /// Change who can see a chat. `shared_type` is `private`,
    /// `specific_entities` or `entire_organization`; the API requires
    /// `shared_entity_ids` for `specific_entities` and rejects them otherwise.
    pub async fn share_chat(
        &self,
        chat_id: &str,
        shared_type: &str,
        entity_ids: &[String],
    ) -> Result<()> {
        let path = format!("{CHATS_BASE}/{chat_id}/shared");
        let mut body = json!({ "shared_type": shared_type });
        if !entity_ids.is_empty() {
            body["shared_entity_ids"] = json!(entity_ids);
        }
        let _: Value = self.client.patch(&path, &body).await?;
        Ok(())
    }

    /// Stop an answer that is still running. The API answers 400 when the
    /// interaction has already finished.
    pub async fn stop_interaction(&self, chat_id: &str, interaction_id: &str) -> Result<()> {
        let path = format!("{CHATS_BASE}/{chat_id}/stop");
        self.client
            .post_raw(&path, &json!({ "interaction_id": interaction_id }))
            .await?;
        Ok(())
    }

    pub async fn list_models(&self) -> Result<Vec<String>> {
        self.client.get(&format!("{CHATS_BASE}/models"), &[]).await
    }

    /// Send a message to an Olly chat.
    ///
    /// `agent_to_agent_mode` signals that the caller is an AI agent (not a
    /// human): when `true`, Olly acts as a sub-agent - shorter responses, no
    /// charts/tables, asks clarifying questions instead of guessing, and
    /// relies on the parent agent's broader context. Defaults to `false` in
    /// the CLI since `cx olly ask` is used directly by humans as well as by
    /// agents; LLM/agent callers should pass `--agent-to-agent-mode` to opt in.
    ///
    /// `timeout_seconds`: `Some` waits for the answer up to that long; `None`
    /// returns at once with an `in_progress` interaction.
    pub async fn send_message(
        &self,
        chat_id: &str,
        content: &str,
        model_choice: &str,
        timeout_seconds: Option<u32>,
        agent_to_agent_mode: bool,
    ) -> Result<Interaction> {
        let path = format!("{CHATS_BASE}/{chat_id}/interactions/");
        let mut body = json!({
            "content": [InputContentBlock::text(content)],
            "interaction_mode": "skill",
            "model_choice": model_choice,
            "should_block": timeout_seconds.is_some(),
            "agent_to_agent_mode": agent_to_agent_mode
        });
        if let Some(timeout) = timeout_seconds {
            body["timeout_seconds"] = json!(timeout);
        }
        self.client
            .post_with_headers(&path, None, &body, &[INTERACTION_SOURCE_HEADER])
            .await
    }

    pub async fn get_interaction(
        &self,
        chat_id: &str,
        interaction_id: &str,
    ) -> Result<Interaction> {
        let path = format!("{CHATS_BASE}/{chat_id}/interactions/{interaction_id}");
        self.client.get(&path, &[]).await
    }

    // ── Artifacts ──────────────────────────────────────────────────────────────

    /// List artifacts, newest first. Only the filters that are set are sent.
    pub async fn list_artifacts(
        &self,
        filters: &ArtifactListFilters,
    ) -> Result<Vec<ArtifactListItem>> {
        let path = format!("{ARTIFACTS_BASE}/");
        let limit = filters.limit.map(|n| n.to_string());
        let offset = filters.offset.map(|n| n.to_string());
        let params: Vec<(&str, &str)> = [
            ("chat_id", filters.chat_id.as_deref()),
            ("artifact_type", filters.artifact_type.as_deref()),
            ("start_time", filters.start.as_deref()),
            ("end_time", filters.end.as_deref()),
            ("limit", limit.as_deref()),
            ("offset", offset.as_deref()),
        ]
        .into_iter()
        .filter_map(|(name, value)| value.map(|v| (name, v)))
        .collect();
        self.client.get(&path, &params).await
    }

    pub async fn get_artifact(&self, artifact_id: &str) -> Result<Artifact> {
        let path = format!("{ARTIFACTS_BASE}/{artifact_id}");
        self.client.get(&path, &[]).await
    }
}

// ── Rules ──────────────────────────────────────────────────────────────────────

const USER_RULES_BASE: &str = "/api/v2/olly/user-rules";
const TEAM_RULES_BASE: &str = "/api/v2/olly/team-rules";

/// Whose rules a command acts on. Personal rules apply to the caller's own
/// chats; team rules apply to everyone on the team.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RuleScope {
    Personal,
    Team,
}

impl RuleScope {
    pub fn from_team_flag(team: bool) -> Self {
        if team {
            Self::Team
        } else {
            Self::Personal
        }
    }

    /// The word used for this scope in messages: `personal` or `team`.
    pub fn label(self) -> &'static str {
        match self {
            Self::Personal => "personal",
            Self::Team => "team",
        }
    }

    fn base(self) -> &'static str {
        match self {
            Self::Personal => USER_RULES_BASE,
            Self::Team => TEAM_RULES_BASE,
        }
    }
}

/// Rules are returned as the API sends them: `{id, rule, enabled, created_at}`.
impl OllyApi {
    /// Team rules that are disabled are listed only for callers with
    /// `olly-team-rules:Manage`.
    pub async fn list_rules(&self, scope: RuleScope) -> Result<Vec<Value>> {
        self.client.get(&format!("{}/", scope.base()), &[]).await
    }

    pub async fn get_rule(&self, scope: RuleScope, rule_id: &str) -> Result<Value> {
        let path = format!("{}/{rule_id}", scope.base());
        self.client.get(&path, &[]).await
    }

    /// The API checks the text for prompt injection and foul language and
    /// answers 422 with its reason when the check fails.
    pub async fn create_rule(&self, scope: RuleScope, rule: &str) -> Result<Value> {
        self.client
            .post(&format!("{}/", scope.base()), &json!({ "rule": rule }))
            .await
    }

    /// Change the text, the enabled state, or both. The API rejects a body
    /// with neither.
    pub async fn update_rule(
        &self,
        scope: RuleScope,
        rule_id: &str,
        rule: Option<&str>,
        enabled: Option<bool>,
    ) -> Result<Value> {
        let path = format!("{}/{rule_id}", scope.base());
        self.client
            .put(&path, &rule_update_body(rule, enabled))
            .await
    }

    pub async fn delete_rule(&self, scope: RuleScope, rule_id: &str) -> Result<()> {
        let path = format!("{}/{rule_id}", scope.base());
        let _: Value = self.client.delete(&path).await?;
        Ok(())
    }
}

/// Only the fields that were given, so an enable or disable never resends
/// (and never re-validates) the rule text.
fn rule_update_body(rule: Option<&str>, enabled: Option<bool>) -> Value {
    let mut body = json!({});
    if let Some(rule) = rule {
        body["rule"] = json!(rule);
    }
    if let Some(enabled) = enabled {
        body["enabled"] = json!(enabled);
    }
    body
}

#[cfg(test)]
mod rules_tests {
    use super::*;

    #[test]
    fn scope_follows_the_team_flag() {
        assert_eq!(RuleScope::from_team_flag(false), RuleScope::Personal);
        assert_eq!(RuleScope::from_team_flag(true), RuleScope::Team);
        assert_eq!(RuleScope::Personal.base(), "/api/v2/olly/user-rules");
        assert_eq!(RuleScope::Team.base(), "/api/v2/olly/team-rules");
    }

    #[test]
    fn update_body_holds_only_the_given_fields() {
        assert_eq!(
            rule_update_body(Some("Answer in English"), None),
            json!({"rule": "Answer in English"})
        );
        assert_eq!(
            rule_update_body(None, Some(false)),
            json!({"enabled": false})
        );
        assert_eq!(
            rule_update_body(Some("x"), Some(true)),
            json!({"rule": "x", "enabled": true})
        );
    }
}

// ── Tests ──────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn deserialize_chat_response() {
        let json = json!({
            "id": "chat-uuid-123",
            "title": "",
            "user_id": "user-456",
            "created_at": "2024-01-01T00:00:00Z",
            "shared_options": {
                "shared_type": "private",
                "shared_entity_ids": null
            },
            "type": "cli",
            "metadata": null
        });
        let chat: Chat = serde_json::from_value(json).unwrap();
        assert_eq!(chat.id, "chat-uuid-123");
        assert_eq!(chat.title, "");
        assert_eq!(chat.user_id.as_deref(), Some("user-456"));
        assert_eq!(chat.chat_type.as_deref(), Some("cli"));
    }

    #[test]
    fn deserialize_chat_minimal() {
        let json = json!({
            "id": "chat-123"
        });
        let chat: Chat = serde_json::from_value(json).unwrap();
        assert_eq!(chat.id, "chat-123");
        assert_eq!(chat.title, "");
    }

    #[test]
    fn deserialize_interaction_in_progress() {
        let json = json!({
            "id": "interaction-123",
            "chat_id": "chat-456",
            "created_at": "2024-01-01T00:00:00Z",
            "status": "IN_PROGRESS",
            "interaction_mode": "AGENTIC",
            "model_choice": "DEFAULT",
            "data_sources": [],
            "feedback": null,
            "feedback_description": null,
            "responses": null
        });
        let interaction: Interaction = serde_json::from_value(json).unwrap();
        assert_eq!(interaction.id, "interaction-123");
        assert_eq!(interaction.chat_id, "chat-456");
        assert_eq!(interaction.status, "IN_PROGRESS");
        assert!(!interaction.is_terminal());
        assert!(interaction.responses.is_none());
    }

    #[test]
    fn deserialize_interaction_completed() {
        let json = json!({
            "id": "interaction-123",
            "chat_id": "chat-456",
            "status": "COMPLETED",
            "responses": [
                {
                    "id": "msg-789",
                    "role": "assistant",
                    "content": [{"type": "text", "text": "Here are the alerts..."}]
                }
            ]
        });
        let interaction: Interaction = serde_json::from_value(json).unwrap();
        assert!(interaction.is_completed());
        assert!(interaction.is_terminal());
        assert_eq!(
            interaction.assistant_text().as_deref(),
            Some("Here are the alerts...")
        );
    }

    #[test]
    fn deserialize_interaction_error() {
        let json = json!({
            "id": "interaction-123",
            "chat_id": "chat-456",
            "status": "error",
            "responses": null
        });
        let interaction: Interaction = serde_json::from_value(json).unwrap();
        assert!(interaction.is_error());
        assert!(interaction.is_terminal());
    }

    #[test]
    fn deserialize_interaction_stopped() {
        let json = json!({
            "id": "interaction-123",
            "chat_id": "chat-456",
            "status": "stopped",
            "responses": null
        });
        let interaction: Interaction = serde_json::from_value(json).unwrap();
        assert!(interaction.is_stopped());
        assert!(interaction.is_terminal());
    }

    #[test]
    fn deserialize_interaction_timed_out_keeps_partial_answer() {
        let json = json!({
            "id": "interaction-123",
            "chat_id": "chat-456",
            "status": "timed_out",
            "responses": [
                {
                    "id": "msg-789",
                    "role": "assistant",
                    "content": [{"type": "text", "text": "So far I found..."}]
                }
            ]
        });
        let interaction: Interaction = serde_json::from_value(json).unwrap();
        assert!(interaction.is_timed_out());
        assert!(interaction.is_terminal());
        assert_eq!(
            interaction.assistant_text().as_deref(),
            Some("So far I found...")
        );
    }

    #[test]
    fn deserialize_message_with_text() {
        let json = json!({
            "id": "msg-123",
            "role": "assistant",
            "content": [
                {"type": "text", "text": "Hello!"},
                {"type": "text", "text": "How can I help?"}
            ]
        });
        let msg: Message = serde_json::from_value(json).unwrap();
        assert_eq!(msg.role, "assistant");
        assert_eq!(msg.text_content(), "Hello!\nHow can I help?");
    }

    #[test]
    fn deserialize_message_with_file() {
        let json = json!({
            "id": "msg-123",
            "role": "assistant",
            "content": [
                {"type": "text", "text": "Here's the chart:"},
                {"type": "file", "file_id": "file-456", "filename": "chart.png"}
            ]
        });
        let msg: Message = serde_json::from_value(json).unwrap();
        assert_eq!(msg.content.len(), 2);
        match &msg.content[1] {
            ContentBlock::File(f) => {
                assert_eq!(f.file_id.as_deref(), Some("file-456"));
                assert_eq!(f.filename.as_deref(), Some("chart.png"));
            }
            _ => panic!("Expected file content block"),
        }
    }

    #[test]
    fn deserialize_message_with_unknown_type() {
        let json = json!({
            "id": "msg-123",
            "role": "assistant",
            "content": [
                {"type": "text", "text": "Hello"},
                {"type": "some_new_type", "data": "whatever"}
            ]
        });
        let msg: Message = serde_json::from_value(json).unwrap();
        assert_eq!(msg.content.len(), 2);
        assert!(matches!(msg.content[1], ContentBlock::Unknown));
    }

    #[test]
    fn deserialize_chat_with_messages() {
        let json = json!({
            "id": "chat-123",
            "title": "My Chat",
            "messages": [
                {
                    "id": "msg-1",
                    "role": "user",
                    "content": [{"type": "text", "text": "Hello"}]
                },
                {
                    "id": "msg-2",
                    "role": "assistant",
                    "content": [{"type": "text", "text": "Hi there!"}]
                }
            ],
            "interactions": []
        });
        let chat: ChatWithMessages = serde_json::from_value(json).unwrap();
        assert_eq!(chat.id, "chat-123");
        assert_eq!(chat.title, "My Chat");
        assert_eq!(chat.messages.len(), 2);
    }

    #[test]
    fn deserialize_chat_get_response_as_returned_by_the_api() {
        let json = json!({
            "title": "Reply with 'OK'",
            "id": "chat-123",
            "entity_id": "user-1",
            "created_at": "2026-11-24T11:54:16.594717Z",
            "shared_options": {"shared_type": "private", "shared_entity_ids": null},
            "task_shared_options": null,
            "type": "ai_connector",
            "metadata": null,
            "execution_runtime": "default",
            "messages": [
                {"id": "m1", "role": "user", "content": [{"type": "text", "text": "Reply OK"}]},
                {"id": "m2", "role": "assistant", "content": [{"type": "text", "text": "OK"}]}
            ],
            "interactions": [{"id": "i1", "chat_id": "chat-123", "status": "COMPLETED"}]
        });
        let chat: ChatWithMessages = serde_json::from_value(json).unwrap();
        assert_eq!(chat.messages[0].role, "user");
        assert_eq!(chat.messages[1].text_content(), "OK");
        assert!(chat.interactions[0].is_completed());
    }

    #[test]
    fn deserialize_model_list() {
        let models: Vec<String> =
            serde_json::from_value(json!(["gpt-5.2", "claude-sonnet-4-5"])).unwrap();
        assert_eq!(models, ["gpt-5.2", "claude-sonnet-4-5"]);
    }

    #[test]
    fn deserialize_artifact() {
        let json = json!({
            "id": "artifact-123",
            "download_url": "https://storage.example.com/artifact-123?token=xyz",
            "filename": "chart.png",
            "content_type": "image/png",
            "size": 12345
        });
        let artifact: Artifact = serde_json::from_value(json).unwrap();
        assert_eq!(artifact.id.as_deref(), Some("artifact-123"));
        assert!(artifact.download_url.is_some());
        assert_eq!(artifact.filename.as_deref(), Some("chart.png"));
    }

    #[test]
    fn deserialize_artifact_minimal() {
        let json = json!({});
        let artifact: Artifact = serde_json::from_value(json).unwrap();
        assert!(artifact.id.is_none());
        assert!(artifact.download_url.is_none());
    }

    #[test]
    fn deserialize_artifact_list_item() {
        let json = json!({
            "id": "artifact-123",
            "created_at": "2026-01-02T03:04:05.000000Z",
            "is_user_managed": false,
            "chat_id": "chat-123",
            "type": "coralogix_metrics",
            "interaction_id": "interaction-123",
            "data_source_id": null,
            "chat_title": "Checkout latency",
            "chat_type": "api"
        });
        let item: ArtifactListItem = serde_json::from_value(json).unwrap();
        assert_eq!(item.id.as_deref(), Some("artifact-123"));
        assert_eq!(item.artifact_type.as_deref(), Some("coralogix_metrics"));
        assert_eq!(item.chat_id.as_deref(), Some("chat-123"));
        assert_eq!(item.chat_title.as_deref(), Some("Checkout latency"));
        assert_eq!(item.chat_type.as_deref(), Some("api"));
        assert_eq!(item.interaction_id.as_deref(), Some("interaction-123"));
        assert_eq!(
            item.created_at.as_deref(),
            Some("2026-01-02T03:04:05.000000Z")
        );
    }

    #[test]
    fn deserialize_artifact_list_item_minimal() {
        let item: ArtifactListItem = serde_json::from_value(json!({})).unwrap();
        assert!(item.id.is_none());
        assert!(item.artifact_type.is_none());
        assert!(item.chat_title.is_none());
    }

    #[test]
    fn input_content_block_serializes_correctly() {
        let block = InputContentBlock::text("Hello world");
        let json = serde_json::to_value(&block).unwrap();
        assert_eq!(json["type"], "input_text");
        assert_eq!(json["text"], "Hello world");
    }
}