coralogix-cli 0.1.14

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
//! `cx ai-center` — Coralogix AI Center (AI v3) configuration commands.
//!
//! Read/write access to the AI application inventory, configured evaluations/policies,
//! coverage, custom evaluations, and model pricing — the configuration that is *not*
//! in span telemetry. Telemetry (GenAI spans) is queried separately via `cx spans`.
//! See the `cx-ai-center` skill.

pub mod api;

use std::sync::Arc;

use anyhow::Result;
use colored::Colorize;
use serde_json::Value;
use toon_format::encode_default as toon_encode;

use crate::config::OutputFormat;
use crate::execution::{fan_out, report_errors_and_collect_successes, ExecutionTarget};
use crate::render;
use api::AiCenterApi;

// ── Shared helpers ──────────────────────────────────────────────────

fn read_from_file(path: &str) -> Result<Value> {
    let raw = if path == "-" {
        eprintln!("{}", "Reading JSON definition from stdin...".dimmed());
        use std::io::Read;
        let mut buf = String::new();
        std::io::stdin().read_to_string(&mut buf)?;
        buf
    } else {
        eprintln!(
            "{}",
            format!("Reading JSON definition from {path}...").dimmed()
        );
        std::fs::read_to_string(path)?
    };
    Ok(serde_json::from_str(&raw)?)
}

fn to_param_refs(params: &[(String, String)]) -> Vec<(&str, &str)> {
    params
        .iter()
        .map(|(k, v)| (k.as_str(), v.as_str()))
        .collect()
}

/// Render a list of JSON rows + a text table across the three output formats.
fn emit_table(
    all_json: &[Value],
    rows: Vec<Vec<String>>,
    headers: &[&str],
    include_profile: bool,
    output: OutputFormat,
    empty_msg: &str,
) -> Result<()> {
    match output {
        OutputFormat::Json => render::render_json(all_json)?,
        OutputFormat::Agents => {
            let toon =
                toon_encode(&all_json).map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {
            if rows.is_empty() {
                render::print_no_results(empty_msg);
                return Ok(());
            }
            render::render_table(headers, rows, include_profile);
        }
    }
    Ok(())
}

/// Render one JSON object per profile (get / coverage / pricing / write results).
fn emit_objects(
    all: &[Value],
    include_profile: bool,
    output: OutputFormat,
    empty_msg: &str,
) -> Result<()> {
    match output {
        OutputFormat::Json => render::render_json_auto(all)?,
        OutputFormat::Agents => {
            let toon =
                toon_encode(&all).map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {
            render::render_get_text(all, include_profile, empty_msg, None::<&dyn Fn(&Value)>)?;
        }
    }
    Ok(())
}

/// Read a string field off a raw item for a text-table column ("" if absent).
fn col<'a>(item: &'a Value, key: &str) -> &'a str {
    item.get(key).and_then(Value::as_str).unwrap_or_default()
}

/// Tag a raw item with its profile (multi-profile mode) and return it.
fn tag_item(mut item: Value, include_profile: bool, profile: &str) -> Value {
    if include_profile {
        if let Some(obj) = item.as_object_mut() {
            obj.insert("profile".into(), Value::String(profile.to_string()));
        }
    }
    item
}

/// Collect per-profile `Value` results, printing per-profile errors to stderr and
/// tagging each object with its profile in multi-profile mode.
fn collect_objects(
    per_profile: Vec<(String, Result<Value>)>,
    include_profile: bool,
) -> Result<Vec<Value>> {
    let mut all: Vec<Value> = Vec::new();
    for (profile, mut val) in report_errors_and_collect_successes(per_profile)? {
        if include_profile {
            render::tag_get_result(&mut val, &profile);
        }
        all.push(val);
    }
    Ok(all)
}

// ── Applications ────────────────────────────────────────────────────

pub async fn run_applications_list(
    targets: &[Arc<ExecutionTarget>],
    page_size: Option<u32>,
    page_offset: Option<u32>,
    evaluation_types: &[String],
    output: OutputFormat,
) -> Result<()> {
    eprintln!("{}", "Fetching AI applications...".dimmed());
    let include_profile = targets.len() > 1;

    let mut params: Vec<(String, String)> = Vec::new();
    if let Some(n) = page_size {
        params.push(("pageSize".into(), n.to_string()));
    }
    if let Some(n) = page_offset {
        params.push(("pageOffset".into(), n.to_string()));
    }
    for t in evaluation_types {
        params.push(("evaluationTypes".into(), t.clone()));
    }

    let per_profile = fan_out(targets, |t| {
        let params = params.clone();
        async move {
            let api = AiCenterApi::new(&t.client);
            Ok(api.list_applications(&to_param_refs(&params)).await?)
        }
    })
    .await;

    let mut all_json: Vec<Value> = Vec::new();
    let mut rows: Vec<Vec<String>> = Vec::new();
    for (profile, items) in report_errors_and_collect_successes(per_profile)? {
        for item in items {
            rows.push(vec![
                profile.clone(),
                col(&item, "id").to_string(),
                col(&item, "application").to_string(),
                col(&item, "subsystem").to_string(),
                render::bool_display(item.get("guardrailsIntegrated").and_then(Value::as_bool)),
            ]);
            all_json.push(tag_item(item, include_profile, &profile));
        }
    }

    emit_table(
        &all_json,
        rows,
        &["ID", "Application", "Subsystem", "Guarded"],
        include_profile,
        output,
        "No AI applications found.",
    )
}

pub async fn run_applications_get(
    targets: &[Arc<ExecutionTarget>],
    id: &str,
    output: OutputFormat,
) -> Result<()> {
    eprintln!("{}", format!("Fetching AI application {id}...").dimmed());
    let include_profile = targets.len() > 1;
    let id = id.to_string();

    let per_profile = fan_out(targets, |t| {
        let id = id.clone();
        async move {
            let api = AiCenterApi::new(&t.client);
            Ok(api.get_application(&id).await?)
        }
    })
    .await;

    let all = collect_objects(per_profile, include_profile)?;
    emit_objects(&all, include_profile, output, "AI application not found.")
}

// ── Evaluations ─────────────────────────────────────────────────────

#[allow(clippy::too_many_arguments)]
pub async fn run_evaluations_list(
    targets: &[Arc<ExecutionTarget>],
    application: Option<&str>,
    subsystem: Option<&str>,
    evaluation_type: Option<&str>,
    page_size: Option<u32>,
    page_offset: Option<u32>,
    output: OutputFormat,
) -> Result<()> {
    eprintln!("{}", "Fetching AI evaluations...".dimmed());
    let include_profile = targets.len() > 1;

    let mut params: Vec<(String, String)> = Vec::new();
    if let Some(v) = application {
        params.push(("application".into(), v.to_string()));
    }
    if let Some(v) = subsystem {
        params.push(("subsystem".into(), v.to_string()));
    }
    if let Some(v) = evaluation_type {
        params.push(("evaluationType".into(), v.to_string()));
    }
    if let Some(n) = page_size {
        params.push(("pageSize".into(), n.to_string()));
    }
    if let Some(n) = page_offset {
        params.push(("pageOffset".into(), n.to_string()));
    }

    let per_profile = fan_out(targets, |t| {
        let params = params.clone();
        async move {
            let api = AiCenterApi::new(&t.client);
            Ok(api.list_evaluations(&to_param_refs(&params)).await?)
        }
    })
    .await;

    let mut all_json: Vec<Value> = Vec::new();
    let mut rows: Vec<Vec<String>> = Vec::new();
    for (profile, items) in report_errors_and_collect_successes(per_profile)? {
        for item in items {
            rows.push(vec![
                profile.clone(),
                col(&item, "id").to_string(),
                col(&item, "application").to_string(),
                col(&item, "subsystem").to_string(),
                api::eval_config_type(&item),
                col(&item, "target").to_string(),
                render::bool_display(item.get("isEnabled").and_then(Value::as_bool)),
                item.get("threshold")
                    .and_then(Value::as_f64)
                    .map(|t| t.to_string())
                    .unwrap_or_default(),
            ]);
            all_json.push(tag_item(item, include_profile, &profile));
        }
    }

    emit_table(
        &all_json,
        rows,
        &[
            "ID",
            "Application",
            "Subsystem",
            "Type",
            "Target",
            "Enabled",
            "Threshold",
        ],
        include_profile,
        output,
        "No AI evaluations found.",
    )
}

pub async fn run_evaluations_get(
    targets: &[Arc<ExecutionTarget>],
    id: &str,
    output: OutputFormat,
) -> Result<()> {
    eprintln!("{}", format!("Fetching AI evaluation {id}...").dimmed());
    let include_profile = targets.len() > 1;
    let id = id.to_string();

    let per_profile = fan_out(targets, |t| {
        let id = id.clone();
        async move {
            let api = AiCenterApi::new(&t.client);
            Ok(api.get_evaluation(&id).await?)
        }
    })
    .await;

    let all = collect_objects(per_profile, include_profile)?;
    emit_objects(&all, include_profile, output, "AI evaluation not found.")
}

pub async fn run_evaluations_create(
    targets: &[Arc<ExecutionTarget>],
    from_file: &str,
    output: OutputFormat,
) -> Result<()> {
    let body = read_from_file(from_file)?;
    eprintln!("{}", "Creating AI evaluation...".dimmed());
    let include_profile = targets.len() > 1;

    let per_profile = fan_out(targets, |t| {
        let body = body.clone();
        async move {
            let api = AiCenterApi::new(&t.client);
            Ok(api.create_evaluation(&body).await?)
        }
    })
    .await;

    let all = collect_objects(per_profile, include_profile)?;
    eprintln!("{}", "Created AI evaluation.".green());
    emit_objects(&all, include_profile, output, "No result.")
}

pub async fn run_evaluations_update(
    targets: &[Arc<ExecutionTarget>],
    id: &str,
    from_file: &str,
    output: OutputFormat,
) -> Result<()> {
    let body = read_from_file(from_file)?;
    eprintln!("{}", format!("Updating AI evaluation {id}...").dimmed());
    let include_profile = targets.len() > 1;
    let id = id.to_string();

    let per_profile = fan_out(targets, |t| {
        let body = body.clone();
        let id = id.clone();
        async move {
            let api = AiCenterApi::new(&t.client);
            Ok(api.update_evaluation(&id, &body).await?)
        }
    })
    .await;

    let all = collect_objects(per_profile, include_profile)?;
    eprintln!("{}", "Updated AI evaluation.".green());
    emit_objects(&all, include_profile, output, "No result.")
}

pub async fn run_evaluations_delete(
    targets: &[Arc<ExecutionTarget>],
    id: &str,
    output: OutputFormat,
) -> Result<()> {
    eprintln!("{}", format!("Deleting AI evaluation {id}...").dimmed());
    let include_profile = targets.len() > 1;
    let id = id.to_string();

    let per_profile = fan_out(targets, |t| {
        let id = id.clone();
        async move {
            let api = AiCenterApi::new(&t.client);
            Ok(api.delete_evaluation(&id).await?)
        }
    })
    .await;

    let all = collect_objects(per_profile, include_profile)?;
    eprintln!("{}", "Deleted AI evaluation.".green());
    emit_objects(&all, include_profile, output, "No result.")
}

// ── Coverage (apps per evaluation type) ─────────────────────────────

pub async fn run_coverage(targets: &[Arc<ExecutionTarget>], output: OutputFormat) -> Result<()> {
    eprintln!("{}", "Fetching AI evaluation coverage...".dimmed());
    let include_profile = targets.len() > 1;

    let per_profile = fan_out(targets, |t| async move {
        let api = AiCenterApi::new(&t.client);
        Ok(api.count_apps_per_eval_type().await?)
    })
    .await;

    let all = collect_objects(per_profile, include_profile)?;
    emit_objects(&all, include_profile, output, "No coverage data.")
}

// ── Custom evaluations ──────────────────────────────────────────────

pub async fn run_custom_evaluations_list(
    targets: &[Arc<ExecutionTarget>],
    output: OutputFormat,
) -> Result<()> {
    eprintln!("{}", "Fetching custom evaluations...".dimmed());
    run_custom_evaluations_table(targets, None, output).await
}

pub async fn run_custom_evaluations_for_application(
    targets: &[Arc<ExecutionTarget>],
    application_id: &str,
    output: OutputFormat,
) -> Result<()> {
    eprintln!(
        "{}",
        format!("Fetching custom evaluations for application {application_id}...").dimmed()
    );
    run_custom_evaluations_table(targets, Some(application_id.to_string()), output).await
}

/// Shared list/table path for both custom-evaluation list variants.
async fn run_custom_evaluations_table(
    targets: &[Arc<ExecutionTarget>],
    application_id: Option<String>,
    output: OutputFormat,
) -> Result<()> {
    let include_profile = targets.len() > 1;

    let per_profile = fan_out(targets, |t| {
        let application_id = application_id.clone();
        async move {
            let api = AiCenterApi::new(&t.client);
            let resp = match application_id {
                Some(app_id) => api.list_custom_evaluations_for_application(&app_id).await?,
                None => api.list_custom_evaluations().await?,
            };
            Ok(resp)
        }
    })
    .await;

    let mut all_json: Vec<Value> = Vec::new();
    let mut rows: Vec<Vec<String>> = Vec::new();
    // Items are raw API objects: the text table reads a few columns, but
    // JSON/agents output keeps the full policy (config, instructions, etc.).
    for (profile, items) in report_errors_and_collect_successes(per_profile)? {
        for item in items {
            let app_count = item
                .get("applicationIds")
                .and_then(Value::as_array)
                .map(|a| a.len())
                .unwrap_or(0);
            rows.push(vec![
                profile.clone(),
                col(&item, "id").to_string(),
                col(&item, "name").to_string(),
                app_count.to_string(),
                col(&item, "description").chars().take(60).collect(),
            ]);
            all_json.push(tag_item(item, include_profile, &profile));
        }
    }

    emit_table(
        &all_json,
        rows,
        &["ID", "Name", "Apps", "Description"],
        include_profile,
        output,
        "No custom evaluations found.",
    )
}

pub async fn run_custom_evaluations_create(
    targets: &[Arc<ExecutionTarget>],
    from_file: &str,
    output: OutputFormat,
) -> Result<()> {
    let body = read_from_file(from_file)?;
    eprintln!("{}", "Creating custom evaluation...".dimmed());
    let include_profile = targets.len() > 1;

    let per_profile = fan_out(targets, |t| {
        let body = body.clone();
        async move {
            let api = AiCenterApi::new(&t.client);
            Ok(api.create_custom_evaluation(&body).await?)
        }
    })
    .await;

    let all = collect_objects(per_profile, include_profile)?;
    eprintln!("{}", "Created custom evaluation.".green());
    emit_objects(&all, include_profile, output, "No result.")
}

pub async fn run_custom_evaluations_update(
    targets: &[Arc<ExecutionTarget>],
    id: &str,
    from_file: &str,
    output: OutputFormat,
) -> Result<()> {
    let body = read_from_file(from_file)?;
    eprintln!("{}", format!("Updating custom evaluation {id}...").dimmed());
    let include_profile = targets.len() > 1;
    let id = id.to_string();

    let per_profile = fan_out(targets, |t| {
        let body = body.clone();
        let id = id.clone();
        async move {
            let api = AiCenterApi::new(&t.client);
            Ok(api.update_custom_evaluation(&id, &body).await?)
        }
    })
    .await;

    let all = collect_objects(per_profile, include_profile)?;
    eprintln!("{}", "Updated custom evaluation.".green());
    emit_objects(&all, include_profile, output, "No result.")
}

pub async fn run_add_policy(
    targets: &[Arc<ExecutionTarget>],
    evaluation_id: &str,
    application_id: &str,
    output: OutputFormat,
) -> Result<()> {
    eprintln!(
        "{}",
        format!("Attaching policy {evaluation_id} to application {application_id}...").dimmed()
    );
    let include_profile = targets.len() > 1;
    let evaluation_id = evaluation_id.to_string();
    let application_id = application_id.to_string();

    let per_profile = fan_out(targets, |t| {
        let evaluation_id = evaluation_id.clone();
        let application_id = application_id.clone();
        async move {
            let api = AiCenterApi::new(&t.client);
            Ok(api
                .add_policy_to_application(&evaluation_id, &application_id)
                .await?)
        }
    })
    .await;

    let all = collect_objects(per_profile, include_profile)?;
    eprintln!("{}", "Attached policy to application.".green());
    emit_objects(&all, include_profile, output, "No result.")
}

pub async fn run_remove_policy(
    targets: &[Arc<ExecutionTarget>],
    evaluation_id: &str,
    application_id: &str,
    output: OutputFormat,
) -> Result<()> {
    eprintln!(
        "{}",
        format!("Detaching policy {evaluation_id} from application {application_id}...").dimmed()
    );
    let include_profile = targets.len() > 1;
    let evaluation_id = evaluation_id.to_string();
    let application_id = application_id.to_string();

    let per_profile = fan_out(targets, |t| {
        let evaluation_id = evaluation_id.clone();
        let application_id = application_id.clone();
        async move {
            let api = AiCenterApi::new(&t.client);
            Ok(api
                .remove_policy_from_application(&evaluation_id, &application_id)
                .await?)
        }
    })
    .await;

    let all = collect_objects(per_profile, include_profile)?;
    eprintln!("{}", "Detached policy from application.".green());
    emit_objects(&all, include_profile, output, "No result.")
}

// ── Model pricing ───────────────────────────────────────────────────

pub async fn run_model_pricing_get(
    targets: &[Arc<ExecutionTarget>],
    output: OutputFormat,
) -> Result<()> {
    eprintln!("{}", "Fetching model pricing...".dimmed());
    let include_profile = targets.len() > 1;

    let per_profile = fan_out(targets, |t| async move {
        let api = AiCenterApi::new(&t.client);
        Ok(api.get_model_pricing().await?)
    })
    .await;

    let all = collect_objects(per_profile, include_profile)?;
    emit_objects(&all, include_profile, output, "No model pricing overrides.")
}

pub async fn run_model_pricing_set(
    targets: &[Arc<ExecutionTarget>],
    from_file: &str,
    output: OutputFormat,
) -> Result<()> {
    let prices = read_from_file(from_file)?;
    eprintln!("{}", "Setting model pricing...".dimmed());
    let include_profile = targets.len() > 1;

    let per_profile = fan_out(targets, |t| {
        let prices = prices.clone();
        async move {
            let api = AiCenterApi::new(&t.client);
            Ok(api.set_model_pricing(&prices).await?)
        }
    })
    .await;

    let all = collect_objects(per_profile, include_profile)?;
    eprintln!("{}", "Set model pricing.".green());
    emit_objects(&all, include_profile, output, "No result.")
}