agent-trace-contract 0.3.0

Transport-neutral contracts for Agent Infra trace APIs
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
//! HTTP API contract for the Trace Infra service.
//!
//! # Why trace is its own service and not part of History Infra
//!
//! Conversation messages and trace events look similar on the wire and behave
//! nothing alike:
//!
//! | | Conversation | Trace |
//! | --- | --- | --- |
//! | Replayed into a model prompt | yes | **never** |
//! | Losing one record | loses user work | acceptable |
//! | Volume | one per turn | many per turn |
//! | Retention | durable | short |
//!
//! Sharing one store would force the stricter guarantee onto high-volume
//! diagnostic data, and — worse — put events one filtering mistake away from
//! being replayed as conversation. Separate services keep that impossible by
//! construction.
//!
//! # Layering
//!
//! ```text
//! agent-trace-contract   paths + DTOs + redaction   (this crate)
//! agent-trace-runtime    store implementation
//! agent-trace-server     router + auth + bin
//! ```
//!
//! See [`api.md`](../api.md) for the full HTTP reference.

use serde::{Deserialize, Serialize};
use serde_json::Value;

use agent_registry_contract::{AgentId, ResourceRelations};

pub const SERVICE_NAME: &str = "agent-trace-infra";
pub const DEFAULT_PORT: u16 = 5140;
pub const AUDIENCE: &str = "agent-trace-infra";

/// Optional static service token. When unset, the server runs in open mode.
pub const SERVICE_TOKEN_ENV: &str = "AGENT_TRACE_INFRA_SERVICE_TOKEN";

pub const HEALTH_PATH: &str = "/health";
pub const EVENTS_APPEND_PATH: &str = "/internal/v1/trace-infra/events/batch";
pub const EVENTS_SEARCH_PATH: &str = "/internal/v1/trace-infra/events/search";

// ── Langfuse project administration ───────────────────────────────────
pub const LANGFUSE_PROJECTS_PATH: &str = "/internal/v1/trace-infra/langfuse-projects";
pub const LANGFUSE_PROJECT_PATH: &str = "/internal/v1/trace-infra/langfuse-projects/{projectId}";
pub const ADMIN_LANGFUSE_PROJECTS_PATH: &str = "/admin/api/langfuse-projects";
pub const MAX_LANGFUSE_PROJECT_PAGE_SIZE: u32 = 200;
pub const RUNTIME_BINDING_PATH: &str = "/internal/v1/trace-infra/runtime-bindings/{runtimeId}";
pub const RUNTIME_BINDING_INITIALIZE_PATH: &str =
    "/internal/v1/trace-infra/runtime-bindings/{runtimeId}/initialize";
pub const RUNTIME_BINDINGS_RESOLVE_PATH: &str = "/internal/v1/trace-infra/runtime-bindings:resolve";
pub const MAX_RUNTIME_BINDING_RESOLVE_SIZE: usize = 200;
pub const ADMIN_LANGFUSE_CONFIG_PATH: &str = "/internal/v1/trace-infra/langfuse-config";
pub const ADMIN_CLICKHOUSE_CONFIG_PATH: &str = "/internal/v1/trace-infra/clickhouse-config";
pub const ADMIN_GATEWAY_LANGFUSE_CONFIG_PATH: &str = "/admin/api/langfuse-config";
pub const ADMIN_GATEWAY_CLICKHOUSE_CONFIG_PATH: &str = "/admin/api/clickhouse-config";

/// Allocate a Langfuse project and project-level API key to Infra resources.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct CreateLangfuseProjectRequest {
    pub name: String,
    pub owner_email: String,
    #[serde(default)]
    pub relations: ResourceRelations,
}

/// Query the project-to-resource relationships maintained by Trace Infra.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct ListLangfuseProjectsRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub related_agent_id: Option<AgentId>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub related_runtime_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub related_user_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cursor: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

/// Persisted Langfuse project assignment. Project secrets are intentionally
/// absent from lookup/list responses.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LangfuseProject {
    pub id: String,
    pub name: String,
    pub owner_email: String,
    pub public_key: String,
    pub base_url: String,
    #[serde(default)]
    pub relations: ResourceRelations,
    pub created_at_ms: u64,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct InitializeRuntimeBindingRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project_name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_id: Option<AgentId>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub owner_email: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RuntimeLangfuseBinding {
    pub runtime_id: String,
    pub project_name: String,
    pub langfuse_project_id: String,
    pub public_key: String,
    pub status: String,
}

/// Resolve many Runtime assignments without using HTTP 404 as collection control flow.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct ResolveRuntimeBindingsRequest {
    pub runtime_ids: Vec<String>,
}

/// Bound and unbound Runtime identities preserve the normalized request order.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResolveRuntimeBindingsResponse {
    pub bindings: Vec<RuntimeLangfuseBinding>,
    pub unbound_runtime_ids: Vec<String>,
}

/// Redacted platform Langfuse organization credentials. Secrets are never serialized.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LangfuseAdminConfig {
    #[serde(default)]
    pub base_url: String,
    pub public_key_configured: bool,
    pub secret_key_configured: bool,
    pub managed: bool,
}

/// Redacted platform ClickHouse connection. Secrets are never serialized.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClickHouseAdminConfig {
    #[serde(default)]
    pub host: String,
    #[serde(default)]
    pub port: String,
    #[serde(default)]
    pub database: String,
    #[serde(default)]
    pub user: String,
    pub password_configured: bool,
    pub managed: bool,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct UpdateLangfuseAdminConfigRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base_url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub public_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub secret_key: Option<String>,
    #[serde(default)]
    pub clear_public_key: bool,
    #[serde(default)]
    pub clear_secret_key: bool,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct UpdateClickHouseAdminConfigRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub host: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub port: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub database: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub password: Option<String>,
    #[serde(default)]
    pub clear_password: bool,
}

/// Creation response. The secret can be recovered only through an idempotent
/// replay of the same create request; ordinary project queries redact it.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProvisionedLangfuseProject {
    pub project: LangfuseProject,
    pub secret_key: String,
}

impl std::fmt::Debug for ProvisionedLangfuseProject {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("ProvisionedLangfuseProject")
            .field("project", &self.project)
            .field("secret_key", &"[REDACTED]")
            .finish()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LangfuseProjectPage {
    pub items: Vec<LangfuseProject>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
}

// ── Langfuse token-usage metrics ───────────────────────────────────────
pub const METRICS_TOKEN_USAGE_PATH: &str = "/internal/v1/trace-infra/metrics/token-usage";
pub const METRICS_MODEL_BREAKDOWN_PATH: &str = "/internal/v1/trace-infra/metrics/model-breakdown";
pub const METRICS_PROJECT_SUMMARY_PATH: &str = "/internal/v1/trace-infra/metrics/project-summary";
pub const METRICS_LATENCY_PATH: &str = "/internal/v1/trace-infra/metrics/latency";
pub const METRICS_ERROR_RATE_PATH: &str = "/internal/v1/trace-infra/metrics/error-rate";
pub const METRICS_CACHE_HIT_RATE_PATH: &str = "/internal/v1/trace-infra/metrics/cache-hit-rate";
pub const METRICS_COST_BREAKDOWN_PATH: &str = "/internal/v1/trace-infra/metrics/cost-breakdown";
pub const METRICS_MODEL_TREND_PATH: &str = "/internal/v1/trace-infra/metrics/model-trend";
pub const METRICS_TOKEN_DISTRIBUTION_PATH: &str =
    "/internal/v1/trace-infra/metrics/token-distribution";
pub const METRICS_ACTIVITY_PATH: &str = "/internal/v1/trace-infra/metrics/activity";
pub const METRICS_PRICING_TIER_PATH: &str = "/internal/v1/trace-infra/metrics/pricing-tier";
pub const MAX_METRICS_LOOKBACK_DAYS: u32 = 3_650;

/// Identifies what a trace event belongs to.
///
/// `run_id` is what makes a trace useful: it groups every event emitted by one
/// turn, so a single execution can be reconstructed without guessing from
/// timestamps.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TraceScope {
    pub conversation_id: String,
    /// Stable Runtime Identity used by control-plane consumers to browse traces.
    /// Older producers may omit it; conversation/run lookup remains compatible.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runtime_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub run_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_space_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runtime_type: Option<String>,
}

impl TraceScope {
    pub fn run(conversation_id: impl Into<String>, run_id: impl Into<String>) -> Self {
        Self {
            conversation_id: conversation_id.into(),
            run_id: Some(run_id.into()),
            ..Default::default()
        }
    }
}

/// One runtime trace event.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RuntimeEventRecord {
    /// Caller supplied id. Enables idempotent append, so a retry after a lost
    /// response cannot duplicate a turn's trace.
    pub id: String,
    pub scope: TraceScope,
    /// Coarse kind, e.g. `turn_started`, `tool_call`, `guard_rail`, `turn_finished`.
    pub event_type: String,
    #[serde(default)]
    pub payload: Value,
    /// Monotonic order within a run. Ties break by `created_at_ms`.
    #[serde(default)]
    pub sequence: i64,
    #[serde(default)]
    pub created_at_ms: i64,
    #[serde(default, skip_serializing_if = "Value::is_null")]
    pub metadata: Value,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AppendEventsRequest {
    pub events: Vec<RuntimeEventRecord>,
}

/// Result of an append. `skipped` counts ids that already existed, so a caller
/// can tell a fresh write from a deduplicated retry.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AppendResponse {
    pub appended: usize,
    pub skipped: usize,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SearchEventsRequest {
    pub scope: TraceScope,
    /// When set, only events of this type are returned.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub event_type: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
}

/// Events in chronological order, oldest first.
///
/// The order is part of the contract: a client that has to re-sort is a client
/// that will eventually get it wrong.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EventsResponse {
    pub items: Vec<RuntimeEventRecord>,
}

/// Upper bound the server enforces on any page size.
/// A full retained run can be read in one bounded request by Evaluate.
pub const MAX_PAGE_SIZE: usize = 10_000;

/// Default page size when a request omits `limit`.
pub const DEFAULT_PAGE_SIZE: usize = 100;

/// Error body shared by every non-2xx response.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiError {
    pub status: u16,
    pub message: String,
}

// ── Langfuse token-usage metrics DTOs ──────────────────────────────────

/// Which ClickHouse table to query.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MetricsDataSource {
    /// Legacy `observations` + `traces` table (v3 path).
    #[serde(rename = "v3")]
    V3,
    /// New `events_core` / `events_full` table (v4 path).
    #[serde(rename = "v4")]
    V4,
    /// Auto-detect: use v4 for dates >= cutover, v3 for dates < cutover.
    #[serde(rename = "auto")]
    #[default]
    Auto,
}

/// Request body for all metrics queries.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MetricsQuery {
    /// Project IDs to filter on (defaults to all configured projects).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project_ids: Option<Vec<String>>,
    /// Number of days to look back (defaults to 30).
    #[serde(default = "default_days")]
    pub days: u32,
    /// Which data source to query.
    #[serde(default)]
    pub data_source: MetricsDataSource,
    /// Cutover date for v4 migration (ISO date string, e.g. "2026-09-01").
    /// Only used when `data_source` is `auto`.
    #[serde(default = "default_v4_cutover")]
    pub v4_cutover_date: String,
}

impl Default for MetricsQuery {
    fn default() -> Self {
        Self {
            project_ids: None,
            days: default_days(),
            data_source: MetricsDataSource::default(),
            v4_cutover_date: default_v4_cutover(),
        }
    }
}

fn default_v4_cutover() -> String {
    "2026-09-01 00:00:00".to_string()
}

const fn default_days() -> u32 {
    30
}

/// A single data point in a token-usage timeseries.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenUsagePoint {
    pub day: String,
    pub total_input_tokens: u64,
    pub total_output_tokens: u64,
    pub total_tokens: u64,
    pub observation_count: u64,
    pub generation_count: u64,
    pub total_cost: Option<f64>,
}

/// Top-level response for the token-usage timeseries endpoint.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenUsageResponse {
    pub project_id: String,
    pub points: Vec<TokenUsagePoint>,
}

/// A single model breakdown row.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelBreakdownEntry {
    pub project_id: String,
    pub model_name: String,
    pub observation_count: u64,
    pub total_input_tokens: u64,
    pub total_output_tokens: u64,
    pub total_tokens: u64,
    pub total_cost: Option<f64>,
    pub pricing_tier: Option<String>,
}

/// Project-level summary stats.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProjectSummary {
    pub project_id: String,
    pub total_tokens: u64,
    pub total_input_tokens: u64,
    pub total_output_tokens: u64,
    pub observation_count: u64,
    pub generation_count: u64,
    pub total_cost: Option<f64>,
    pub unique_models: u64,
    pub unique_traces: u64,
}

/// A single latency data point (daily bucket).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LatencyPoint {
    pub day: String,
    pub project_id: String,
    pub model_name: Option<String>,
    pub observation_count: u64,
    /// Average duration (end_time - start_time) in seconds.
    pub avg_duration_seconds: Option<f64>,
    /// P50 duration in seconds.
    pub p50_duration_seconds: Option<f64>,
    /// P95 duration in seconds.
    pub p95_duration_seconds: Option<f64>,
    /// P99 duration in seconds.
    pub p99_duration_seconds: Option<f64>,
    /// Average time-to-first-token (completion_start_time - start_time) in seconds.
    pub avg_ttft_seconds: Option<f64>,
}

/// Latency response grouped by project.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LatencyResponse {
    pub project_id: String,
    pub points: Vec<LatencyPoint>,
}

/// A single error-rate data point (daily bucket).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorRatePoint {
    pub day: String,
    pub project_id: String,
    pub total_observations: u64,
    pub error_count: u64,
    /// error_count / total_observations.
    pub error_rate: f64,
    pub model_name: Option<String>,
}

/// Error rate response grouped by project.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorRateResponse {
    pub project_id: String,
    pub points: Vec<ErrorRatePoint>,
}

// ── Cache hit rate (P0) ────────────────────────────────────────────────

/// Cache hit rate data point.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CacheHitRatePoint {
    pub project_id: String,
    pub model_name: Option<String>,
    pub total_input_tokens: u64,
    pub cached_tokens: u64,
    /// Observed cached / input pairs only; absent cache counts are not misses.
    pub cache_hit_pct: f64,
    /// Observations carrying any usage fields, not the total number of model calls.
    #[serde(default)]
    pub observation_count: u64,
    /// Observations with a valid cache/input pair and a positive denominator.
    #[serde(default)]
    pub cache_measured_count: u64,
}

/// Cache hit rate response (flat list).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CacheHitRateResponse {
    pub items: Vec<CacheHitRatePoint>,
}

// ── Cost breakdown (P1) ────────────────────────────────────────────────

/// Cost breakdown data point (input/output/total).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CostBreakdownPoint {
    pub project_id: String,
    pub model_name: Option<String>,
    pub total_input_cost: Option<f64>,
    pub total_output_cost: Option<f64>,
    pub total_cost: Option<f64>,
    pub observation_count: u64,
}

/// Cost breakdown response (flat list).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CostBreakdownResponse {
    pub items: Vec<CostBreakdownPoint>,
}

// ── Model trend (P1) ───────────────────────────────────────────────────

/// Model usage trend point (daily).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelTrendPoint {
    pub day: String,
    pub project_id: String,
    pub model_name: Option<String>,
    pub call_count: u64,
    pub total_tokens: u64,
    pub total_cost: Option<f64>,
}

/// Model trend response grouped by project.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelTrendResponse {
    pub project_id: String,
    pub points: Vec<ModelTrendPoint>,
}

// ── Token distribution (P2) ────────────────────────────────────────────

/// Token distribution statistics (by model).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenDistributionPoint {
    pub project_id: String,
    pub model_name: Option<String>,
    pub observation_count: u64,
    pub avg_tokens: Option<f64>,
    pub p50_tokens: Option<f64>,
    pub p95_tokens: Option<f64>,
    pub p99_tokens: Option<f64>,
    pub max_tokens: Option<u64>,
}

/// Token distribution response (flat list).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenDistributionResponse {
    pub items: Vec<TokenDistributionPoint>,
}

// ── Activity (P2) ──────────────────────────────────────────────────────

/// Activity data point (daily).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActivityPoint {
    pub day: String,
    pub project_id: String,
    pub active_traces: u64,
    pub observation_count: u64,
}

/// Activity response grouped by project.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActivityResponse {
    pub project_id: String,
    pub points: Vec<ActivityPoint>,
}

// ── Pricing tier analysis (P2) ─────────────────────────────────────────

/// Pricing tier analysis data point.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PricingTierPoint {
    pub project_id: String,
    pub pricing_tier: Option<String>,
    pub model_name: Option<String>,
    pub observation_count: u64,
    pub total_tokens: u64,
    pub total_cost: Option<f64>,
}

/// Pricing tier response (flat list).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PricingTierResponse {
    pub items: Vec<PricingTierPoint>,
}

/// Placeholder written over any value that looks like a credential.
pub const REDACTED: &str = "<redacted>";

/// Mask credential-shaped fields anywhere in a trace payload.
///
/// # Why this lives in the contract
///
/// Trace payloads carry tool arguments and model requests, which are exactly
/// where an API key or bearer token ends up. Traces are also the data most
/// likely to be shipped to a log aggregator and kept, so an unredacted secret
/// there outlives the request that leaked it.
///
/// Redaction is therefore part of the wire contract rather than a courtesy each
/// caller might forget: both the client and the server apply it, so a payload
/// cannot be stored unmasked even if a caller skips the step.
pub fn redact_payload(value: &mut Value) {
    match value {
        Value::Object(fields) => {
            for (key, field) in fields.iter_mut() {
                if is_sensitive_key(key) {
                    *field = Value::String(REDACTED.to_string());
                } else {
                    redact_payload(field);
                }
            }
        }
        Value::Array(items) => items.iter_mut().for_each(redact_payload),
        _ => {}
    }
}

/// True when a field name looks like it holds a credential.
///
/// Matching is done on a normalised key (lowercased, separators removed) so
/// `api_key`, `apiKey`, and `API-KEY` are all caught by one rule.
fn is_sensitive_key(key: &str) -> bool {
    let normalised = key
        .chars()
        .filter(|character| character.is_ascii_alphanumeric())
        .flat_map(|character| character.to_lowercase())
        .collect::<String>();

    const EXACT: &[&str] = &[
        "apikey",
        "authorization",
        "gatewaytoken",
        "password",
        "secret",
        "token",
    ];
    if EXACT.contains(&normalised.as_str()) {
        return true;
    }

    // Compound names such as `accessToken`, `clientSecret`, `serviceApiKey`.
    ["apikey", "secret", "token", "password"]
        .iter()
        .any(|needle| normalised.ends_with(needle))
}

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

    #[test]
    fn scope_serialises_camel_case_and_omits_absent_provenance() {
        let value = serde_json::to_value(TraceScope::run("conv-1", "run-1")).expect("serialize");
        assert_eq!(value, json!({"conversationId": "conv-1", "runId": "run-1"}));
    }

    #[test]
    fn redaction_masks_credential_fields_at_any_depth() {
        let mut payload = json!({
            "model": "test-model",
            "api_key": "sensitive-api-value",
            "headers": {"Authorization": "sensitive-authorization-value"},
            "calls": [
                {"accessToken": "sensitive-access-value"},
                {"clientSecret": "sensitive-client-value"}
            ],
            "nested": {"deep": {"apiKey": "sensitive-nested-value"}}
        });

        redact_payload(&mut payload);

        assert_eq!(payload["model"], "test-model", "non-secrets must survive");
        assert_eq!(payload["api_key"], REDACTED);
        assert_eq!(payload["headers"]["Authorization"], REDACTED);
        assert_eq!(payload["calls"][0]["accessToken"], REDACTED);
        assert_eq!(payload["calls"][1]["clientSecret"], REDACTED);
        assert_eq!(payload["nested"]["deep"]["apiKey"], REDACTED);
    }

    #[test]
    fn redaction_does_not_mask_lookalike_field_names() {
        // These read like secrets but carry no credential; masking them would
        // quietly destroy useful trace data.
        let mut payload = json!({
            "tokenCount": 42,
            "secretsManagerArn": "arn:aws:secretsmanager:...",
            "passwordPolicy": {"minLength": 12}
        });

        redact_payload(&mut payload);

        assert_eq!(payload["tokenCount"], 42);
        assert_eq!(
            payload["secretsManagerArn"], "arn:aws:secretsmanager:...",
            "a name that merely contains 'secret' is not a secret"
        );
        assert_eq!(payload["passwordPolicy"]["minLength"], 12);
    }

    #[test]
    fn an_event_round_trips_through_json() {
        let record = RuntimeEventRecord {
            id: "e-1".into(),
            scope: TraceScope::run("conv-1", "run-1"),
            event_type: "tool_call".into(),
            payload: json!({"name": "execute_cmd"}),
            sequence: 3,
            created_at_ms: 1_700_000_000_000,
            metadata: Value::Null,
        };
        let encoded = serde_json::to_value(&record).expect("serialize");
        assert_eq!(encoded["eventType"], "tool_call");
        assert_eq!(encoded["createdAtMs"], 1_700_000_000_000_i64);
        let decoded: RuntimeEventRecord = serde_json::from_value(encoded).expect("deserialize");
        assert_eq!(decoded, record);
    }
}