tokmesh-core 0.1.2

Core library for tokmesh — session parsing, scanning, aggregation, pricing
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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
//! Session parsers for different AI coding assistant formats
//!
//! Each client has its own parser that converts to a unified message format.

pub mod amp;
pub mod antigravity;
pub mod antigravity_cli;
pub mod claudecode;
pub mod cline;
pub mod codebuddy;
pub mod codebuff;
pub mod codex;
pub mod commandcode;
pub mod copilot;
pub mod copilot_desktop;
pub mod copilot_vscode;
pub mod crush;
pub mod cursor;
pub mod devin;
pub mod droid;
pub mod gemini;
pub mod gjc;
pub mod goose;
pub mod grok;
pub mod hermes;
pub mod jcode;
pub mod junie;
pub mod kilo;
pub mod kilocode;
pub mod kimi;
pub mod kiro;
pub mod micode;
pub mod mux;
pub mod openclaw;
pub mod opencode;
pub mod opencodereview;
pub mod pi;
pub mod qwen;
pub mod roocode;
pub mod synthetic;
pub(crate) mod tencent_buddy;
pub mod trae;
pub(crate) mod utils;
pub mod warp;
pub mod workbuddy;
pub mod zcode;
pub mod zed;

use crate::TokenBreakdown;

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CostSource {
    #[default]
    Unknown,
    ProviderReported,
    Estimated,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct UnifiedMessage {
    pub client: String,
    pub model_id: String,
    pub provider_id: String,
    pub session_id: String,
    pub workspace_key: Option<String>,
    pub workspace_label: Option<String>,
    pub timestamp: i64,
    pub date: String,
    pub tokens: TokenBreakdown,
    pub cost: f64,
    #[serde(default)]
    pub cost_source: CostSource,
    #[serde(default)]
    pub duration_ms: Option<i64>,
    #[serde(default = "default_message_count")]
    pub message_count: i32,
    pub agent: Option<String>,
    pub dedup_key: Option<String>,
    /// Human-readable session title/name when the source client stores one
    /// (e.g. OpenCode's `session.title` column). `None` for clients that
    /// don't record a title; the Sessions tab falls back to showing just
    /// the session ID in that case.
    #[serde(default)]
    pub session_title: Option<String>,
    /// True if this message is the first assistant response after a user turn.
    /// Used to count user interaction turns (as opposed to API message count).
    #[serde(default)]
    pub is_turn_start: bool,
}

const fn default_message_count() -> i32 {
    1
}

pub fn normalize_agent_name(agent: &str) -> String {
    let cleaned = strip_zero_width_chars(agent);
    let trimmed = cleaned.trim();
    let stripped = strip_agent_prefix(trimmed);
    let canonical = canonicalize_agent_name(stripped);
    let agent_lower = canonical.to_lowercase();

    if agent_lower.contains("plan") {
        if agent_lower.contains("omo") || agent_lower.contains("sisyphus") {
            return "Planner-Sisyphus".to_string();
        }
        return titlecase_agent(&canonical);
    }

    if agent_lower == "omo" || agent_lower == "sisyphus" {
        return "Sisyphus".to_string();
    }

    if agent_lower == "orchestrator-sisyphus" {
        return "Atlas".to_string();
    }

    titlecase_agent(&canonical)
}

pub fn normalize_opencode_agent_name(agent: &str) -> String {
    let cleaned = strip_zero_width_chars(agent);
    let trimmed = cleaned.trim();
    let stripped = strip_agent_prefix(trimmed);
    let canonical = canonicalize_agent_name(stripped);
    let agent_lower = canonical.to_lowercase();

    if let Some(normalized) = normalize_oh_my_opencode_agent_name(&agent_lower) {
        return normalized;
    }

    normalize_agent_name(&canonical)
}

pub fn normalize_copilot_agent_name(agent: &str) -> String {
    // Hardcoded brand name for the default native agent
    if agent.eq_ignore_ascii_case("github.copilot.default") {
        return "GitHub Copilot".to_string();
    }

    // Native github.copilot.* agents: strip prefix, titlecase remainder
    const GITHUB_COPILOT_PREFIX: &str = "github.copilot.";
    if agent
        .get(..GITHUB_COPILOT_PREFIX.len())
        .is_some_and(|head| head.eq_ignore_ascii_case(GITHUB_COPILOT_PREFIX))
    {
        let remainder = &agent[GITHUB_COPILOT_PREFIX.len()..];
        let hyphenated = remainder.replace('.', "-");
        return titlecase_agent(&hyphenated);
    }

    // Plugin:team:slug format — titlecase each colon-separated part, join with ": "
    const PLUGIN_PREFIX: &str = "Plugin:";
    if agent
        .get(..PLUGIN_PREFIX.len())
        .is_some_and(|head| head.eq_ignore_ascii_case(PLUGIN_PREFIX))
    {
        let rest = &agent[PLUGIN_PREFIX.len()..];
        let parts: Vec<&str> = rest.splitn(2, ':').collect();
        if parts.len() == 2 {
            let team = titlecase_agent(parts[0]);
            let slug = titlecase_agent(parts[1]);
            return format!("{}: {}", team, slug);
        }
        return titlecase_agent(rest);
    }

    normalize_agent_name(agent)
}

fn normalize_oh_my_opencode_agent_name(agent_lower: &str) -> Option<String> {
    let normalized = match agent_lower {
        // Parenthesized format and dash format
        "sisyphus (ultraworker)"
        | "sisyphus - ultraworker"
        | "sisyphus ultraworker"
        | "sisyphus" => "Sisyphus",
        "hephaestus (deep agent)"
        | "hephaestus - deep agent"
        | "hephaestus deep agent"
        | "hephaestus" => "Hephaestus",
        "prometheus (plan builder)"
        | "prometheus - plan builder"
        | "prometheus plan builder"
        | "prometheus (planner)"
        | "prometheus" => "Prometheus",
        "atlas (plan executor)" | "atlas - plan executor" | "atlas plan executor" | "atlas" => {
            "Atlas"
        }
        "metis (plan consultant)"
        | "metis - plan consultant"
        | "metis plan consultant"
        | "metis" => "Metis",
        "momus (plan critic)"
        | "momus - plan critic"
        | "momus plan critic"
        | "momus (plan reviewer)"
        | "momus" => "Momus",
        "orchestrator-sisyphus" => "Atlas",
        "sisyphus-junior" => "Sisyphus-Junior",
        "planner-sisyphus" => "Planner-Sisyphus",
        _ => return None,
    };

    Some(normalized.to_string())
}

/// Strip zero-width Unicode characters that oh-my-openagent uses as
/// invisible sort-order prefixes (U+200B ZERO WIDTH SPACE, U+200C ZERO
/// WIDTH NON-JOINER, U+200D ZERO WIDTH JOINER, U+FEFF BOM/ZWNBSP).
fn strip_zero_width_chars(s: &str) -> String {
    if !s.contains(['\u{200B}', '\u{200C}', '\u{200D}', '\u{FEFF}']) {
        return s.to_string();
    }
    s.chars()
        .filter(|c| !matches!(c, '\u{200B}' | '\u{200C}' | '\u{200D}' | '\u{FEFF}'))
        .collect()
}

fn strip_agent_prefix(name: &str) -> &str {
    for prefix in &["astrape:", "oh-my-claudecode:", "oh-my-codex:"] {
        if name
            .get(..prefix.len())
            .is_some_and(|head| head.eq_ignore_ascii_case(prefix))
        {
            return &name[prefix.len()..];
        }
    }
    name
}

fn canonicalize_agent_name(name: &str) -> String {
    name.split_whitespace().collect::<Vec<_>>().join(" ")
}

fn titlecase_word(word: &str) -> String {
    match word.to_lowercase().as_str() {
        "ui" => "UI".to_string(),
        "ux" => "UX".to_string(),
        "api" => "API".to_string(),
        _ => {
            let mut chars = word.chars();
            match chars.next() {
                None => String::new(),
                Some(c) => {
                    let upper: String = c.to_uppercase().collect();
                    upper + &chars.collect::<String>()
                }
            }
        }
    }
}

fn titlecase_agent(name: &str) -> String {
    if name.is_empty() {
        return String::new();
    }
    name.split('-')
        .flat_map(|part| part.split_whitespace())
        .map(titlecase_word)
        .collect::<Vec<_>>()
        .join(" ")
}

impl UnifiedMessage {
    pub fn new(
        client: impl Into<String>,
        model_id: impl Into<String>,
        provider_id: impl Into<String>,
        session_id: impl Into<String>,
        timestamp: i64,
        tokens: TokenBreakdown,
        cost: f64,
    ) -> Self {
        Self::new_full(
            client,
            model_id,
            provider_id,
            session_id,
            timestamp,
            tokens,
            cost,
            None,
            None,
        )
    }

    #[allow(clippy::too_many_arguments)]
    pub fn new_with_agent(
        client: impl Into<String>,
        model_id: impl Into<String>,
        provider_id: impl Into<String>,
        session_id: impl Into<String>,
        timestamp: i64,
        tokens: TokenBreakdown,
        cost: f64,
        agent: Option<String>,
    ) -> Self {
        Self::new_full(
            client,
            model_id,
            provider_id,
            session_id,
            timestamp,
            tokens,
            cost,
            agent,
            None,
        )
    }

    #[allow(clippy::too_many_arguments)]
    pub fn new_with_dedup(
        client: impl Into<String>,
        model_id: impl Into<String>,
        provider_id: impl Into<String>,
        session_id: impl Into<String>,
        timestamp: i64,
        tokens: TokenBreakdown,
        cost: f64,
        dedup_key: Option<String>,
    ) -> Self {
        Self::new_full(
            client,
            model_id,
            provider_id,
            session_id,
            timestamp,
            tokens,
            cost,
            None,
            dedup_key,
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn new_full(
        client: impl Into<String>,
        model_id: impl Into<String>,
        provider_id: impl Into<String>,
        session_id: impl Into<String>,
        timestamp: i64,
        tokens: TokenBreakdown,
        cost: f64,
        agent: Option<String>,
        dedup_key: Option<String>,
    ) -> Self {
        let client = client.into();
        let model_id = model_id.into();
        let date = timestamp_to_date(timestamp);
        Self {
            client,
            model_id,
            provider_id: provider_id.into(),
            session_id: session_id.into(),
            workspace_key: None,
            workspace_label: None,
            timestamp,
            date,
            tokens,
            cost,
            cost_source: CostSource::Unknown,
            duration_ms: None,
            message_count: default_message_count(),
            agent,
            dedup_key,
            session_title: None,
            is_turn_start: false,
        }
    }

    pub fn set_workspace(
        &mut self,
        workspace_key: Option<String>,
        workspace_label: Option<String>,
    ) {
        self.workspace_key = workspace_key;
        self.workspace_label = workspace_label;
    }

    pub(crate) fn refresh_derived_fields(&mut self) {
        self.date = timestamp_to_date(self.timestamp);
    }

    pub(crate) fn set_timestamp(&mut self, timestamp: i64) {
        self.timestamp = timestamp;
        self.refresh_derived_fields();
    }

    pub fn mark_provider_reported_cost(&mut self) {
        self.cost_source = CostSource::ProviderReported;
    }

    pub(crate) fn mark_estimated_cost(&mut self) {
        self.cost_source = CostSource::Estimated;
    }

    pub(crate) fn has_authoritative_cost(&self) -> bool {
        self.cost_source == CostSource::ProviderReported
    }
}

pub fn normalize_workspace_key(raw: &str) -> Option<String> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return None;
    }

    let preserve_unc_prefix = trimmed.starts_with("\\\\") || trimmed.starts_with("//");
    let mut normalized = trimmed.replace('\\', "/");

    if preserve_unc_prefix {
        let body = normalized.trim_start_matches('/');
        let mut collapsed = body.to_string();
        while collapsed.contains("//") {
            collapsed = collapsed.replace("//", "/");
        }
        normalized = format!("//{}", collapsed);
    } else {
        while normalized.contains("//") {
            normalized = normalized.replace("//", "/");
        }
    }

    let minimum_len = if preserve_unc_prefix { 2 } else { 1 };
    if normalized.len() > minimum_len {
        normalized = normalized.trim_end_matches('/').to_string();
    }

    if normalized.is_empty() {
        None
    } else {
        Some(normalized)
    }
}

pub fn workspace_label_from_key(key: &str) -> Option<String> {
    key.rsplit('/')
        .find(|segment| !segment.is_empty())
        .map(|segment| segment.to_string())
}

/// Convert Unix milliseconds to a local YYYY-MM-DD date string.
fn timestamp_to_date(timestamp_ms: i64) -> String {
    // Prefer the process-wide pinned bucketing timezone when set (tokens.ci
    // travel-proof submit); otherwise fall back to the machine local zone.
    crate::bucket_tz::bucket_timezone().date_of_ms(timestamp_ms)
}

#[cfg(test)]
fn timestamp_to_date_with_timezone<Tz>(timestamp_ms: i64, timezone: &Tz) -> String
where
    Tz: chrono::TimeZone,
    Tz::Offset: std::fmt::Display,
{
    match timezone.timestamp_millis_opt(timestamp_ms) {
        chrono::LocalResult::Single(dt) => dt.format("%Y-%m-%d").to_string(),
        _ => String::new(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::FixedOffset;

    #[test]
    fn warp_cache_parser_preserves_requests_and_spend_without_tokens() {
        let file = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(
            file.path(),
            r#"{
  "version": 1,
  "syncedAt": "2026-05-29T12:00:00Z",
  "usage": {
    "requestsUsed": 42,
    "requestLimit": 100,
    "spendCents": 1234,
    "nextRefreshTime": "2026-06-01T00:00:00Z"
  },
  "workspaces": [
    {
      "id": "workspace-1",
      "name": "Personal",
      "requestsUsed": 12,
      "spendCents": 345
    }
  ]
}"#,
        )
        .unwrap();

        let messages = crate::sessions::warp::parse_warp_file(file.path());
        assert_eq!(messages.len(), 1);

        let workspace = messages
            .iter()
            .find(|message| message.session_id == "warp-aggregate-workspace-1")
            .unwrap();
        assert_eq!(workspace.client, "warp");
        assert_eq!(workspace.model_id, "aggregate-requests");
        assert_eq!(workspace.provider_id, "warp");
        assert_eq!(workspace.workspace_label.as_deref(), Some("Personal"));
        assert_eq!(workspace.message_count, 12);
        assert_eq!(workspace.tokens, TokenBreakdown::default());
        assert!((workspace.cost - 3.45).abs() < 1e-9);

        std::fs::write(
            file.path(),
            r#"{
  "version": 1,
  "syncedAt": "2026-05-29T12:00:00Z",
  "usage": {
    "requestsUsed": 42,
    "requestLimit": 100,
    "spendCents": 1234,
    "nextRefreshTime": "2026-06-01T00:00:00Z"
  },
  "workspaces": []
}"#,
        )
        .unwrap();

        let messages = crate::sessions::warp::parse_warp_file(file.path());
        assert_eq!(messages.len(), 1);
        let account = &messages[0];
        assert_eq!(account.session_id, "warp-aggregate-account");
        assert_eq!(account.message_count, 42);
        assert_eq!(account.tokens, TokenBreakdown::default());
        assert!((account.cost - 12.34).abs() < 1e-9);
    }

    #[test]
    fn test_timestamp_to_date_with_positive_offset() {
        let kst = FixedOffset::east_opt(9 * 60 * 60).unwrap();
        let ts = 1772512200000_i64; // 2026-03-03T04:30:00Z
        let date = timestamp_to_date_with_timezone(ts, &kst);
        assert_eq!(date, "2026-03-03");
    }

    #[test]
    fn test_timestamp_to_date_with_negative_offset() {
        let pst = FixedOffset::west_opt(8 * 60 * 60).unwrap();
        let ts = 1772512200000_i64; // 2026-03-03T04:30:00Z
        let date = timestamp_to_date_with_timezone(ts, &pst);
        assert_eq!(date, "2026-03-02");
    }

    #[test]
    fn test_timestamp_to_date_invalid_timestamp() {
        let utc = FixedOffset::east_opt(0).unwrap();
        let date = timestamp_to_date_with_timezone(i64::MAX, &utc);
        assert_eq!(date, "");
    }

    #[test]
    fn test_unified_message_creation() {
        let tokens = TokenBreakdown {
            input: 100,
            output: 50,
            cache_read: 0,
            cache_write: 0,
            reasoning: 0,
        };

        let msg = UnifiedMessage::new(
            "opencode",
            "claude-3-5-sonnet",
            "anthropic",
            "test-session-id",
            1733011200000,
            tokens,
            0.05,
        );

        assert_eq!(msg.client, "opencode");
        assert_eq!(msg.model_id, "claude-3-5-sonnet");
        assert_eq!(msg.session_id, "test-session-id");
        assert_eq!(msg.date, timestamp_to_date(1733011200000));
        assert_eq!(msg.cost, 0.05);
        assert_eq!(msg.agent, None);
        assert_eq!(msg.workspace_key, None);
        assert_eq!(msg.workspace_label, None);
    }

    #[test]
    fn test_normalize_workspace_key_normalizes_slashes_and_trailing_separator() {
        assert_eq!(
            normalize_workspace_key(r"C:\Users\alice\repo\"),
            Some("C:/Users/alice/repo".to_string())
        );
        assert_eq!(
            normalize_workspace_key("/Users/alice//repo/"),
            Some("/Users/alice/repo".to_string())
        );
    }

    #[test]
    fn test_normalize_workspace_key_preserves_unc_prefix() {
        assert_eq!(
            normalize_workspace_key(r"\\server\share\repo\"),
            Some("//server/share/repo".to_string())
        );
        assert_eq!(
            normalize_workspace_key("//server//share///repo/"),
            Some("//server/share/repo".to_string())
        );
    }

    #[test]
    fn test_workspace_label_from_key_uses_last_path_segment() {
        assert_eq!(
            workspace_label_from_key("/Users/alice/my-repo"),
            Some("my-repo".to_string())
        );
        assert_eq!(
            workspace_label_from_key("encoded-project-key"),
            Some("encoded-project-key".to_string())
        );
    }

    #[test]
    fn test_normalize_agent_name() {
        assert_eq!(normalize_agent_name("OmO"), "Sisyphus");
        assert_eq!(normalize_agent_name("Sisyphus"), "Sisyphus");
        assert_eq!(normalize_agent_name("omo"), "Sisyphus");
        assert_eq!(normalize_agent_name("sisyphus"), "Sisyphus");
        assert_eq!(
            normalize_agent_name("Sisyphus (Ultraworker)"),
            "Sisyphus (Ultraworker)"
        );

        assert_eq!(
            normalize_opencode_agent_name("Sisyphus (Ultraworker)"),
            "Sisyphus"
        );
        assert_eq!(normalize_opencode_agent_name("hephaestus"), "Hephaestus");
        assert_eq!(normalize_opencode_agent_name("prometheus"), "Prometheus");
        assert_eq!(normalize_opencode_agent_name("atlas"), "Atlas");
        assert_eq!(normalize_opencode_agent_name("metis"), "Metis");
        assert_eq!(normalize_opencode_agent_name("momus"), "Momus");
        assert_eq!(
            normalize_opencode_agent_name("sisyphus-junior"),
            "Sisyphus-Junior"
        );
        assert_eq!(
            normalize_opencode_agent_name("planner-sisyphus"),
            "Planner-Sisyphus"
        );

        assert_eq!(
            normalize_opencode_agent_name("Hephaestus (Deep Agent)"),
            "Hephaestus"
        );
        assert_eq!(
            normalize_opencode_agent_name("Prometheus (Plan Builder)"),
            "Prometheus"
        );
        assert_eq!(
            normalize_opencode_agent_name("Prometheus (Planner)"),
            "Prometheus"
        );
        assert_eq!(
            normalize_opencode_agent_name("Atlas (Plan Executor)"),
            "Atlas"
        );
        assert_eq!(
            normalize_opencode_agent_name("Metis (Plan Consultant)"),
            "Metis"
        );
        assert_eq!(
            normalize_opencode_agent_name("Momus (Plan Critic)"),
            "Momus"
        );
        assert_eq!(
            normalize_opencode_agent_name("Momus (Plan Reviewer)"),
            "Momus"
        );

        assert_eq!(normalize_agent_name("OmO-Plan"), "Planner-Sisyphus");
        assert_eq!(normalize_agent_name("Planner-Sisyphus"), "Planner-Sisyphus");
        assert_eq!(normalize_agent_name("omo-plan"), "Planner-Sisyphus");

        assert_eq!(normalize_agent_name("orchestrator-sisyphus"), "Atlas");
        assert_eq!(
            normalize_opencode_agent_name("orchestrator-sisyphus"),
            "Atlas"
        );
        assert_eq!(normalize_agent_name("explore"), "Explore");
        assert_eq!(normalize_agent_name("CustomAgent"), "CustomAgent");

        assert_eq!(normalize_agent_name("executor"), "Executor");
        assert_eq!(
            normalize_agent_name("task-orchestrator"),
            "Task Orchestrator"
        );
        assert_eq!(normalize_agent_name("git-committer"), "Git Committer");
        assert_eq!(
            normalize_agent_name("frontend-ui-ux-engineer"),
            "Frontend UI UX Engineer"
        );
        assert_eq!(
            normalize_agent_name("astrape:executor-high"),
            "Executor High"
        );
        assert_eq!(
            normalize_agent_name("oh-my-claudecode:code-reviewer"),
            "Code Reviewer"
        );
    }

    #[test]
    fn test_normalize_copilot_agent_name() {
        assert_eq!(
            normalize_copilot_agent_name("github.copilot.default"),
            "GitHub Copilot"
        );
        assert_eq!(
            normalize_copilot_agent_name("GITHUB.COPILOT.DEFAULT"),
            "GitHub Copilot"
        );
        assert_eq!(normalize_copilot_agent_name("github.copilot.chat"), "Chat");
        assert_eq!(
            normalize_copilot_agent_name("Plugin:software-engineering-team:se-ux-ui-designer"),
            "Software Engineering Team: Se UX UI Designer"
        );
        assert_eq!(
            normalize_copilot_agent_name("plugin:my-team:my-agent"),
            "My Team: My Agent"
        );
        assert_eq!(
            normalize_copilot_agent_name("Plugin:code-review-team:api-reviewer"),
            "Code Review Team: API Reviewer"
        );
        assert_eq!(
            normalize_copilot_agent_name("some-custom-agent"),
            "Some Custom Agent"
        );
        assert_eq!(normalize_agent_name("oh-my-codex:librarian"), "Librarian");
        assert_eq!(normalize_agent_name("astrape:executor"), "Executor");
        assert_eq!(normalize_agent_name("plan-reviewer"), "Plan Reviewer");
        assert_eq!(normalize_agent_name("astrape:planner"), "Planner");

        assert_eq!(
            normalize_opencode_agent_name("astrape:sisyphus"),
            "Sisyphus"
        );
        assert_eq!(
            normalize_opencode_agent_name("oh-my-claudecode:executor"),
            "Executor"
        );

        // New dash format (oh-my-openagent current)
        assert_eq!(
            normalize_opencode_agent_name("Sisyphus - Ultraworker"),
            "Sisyphus"
        );
        assert_eq!(
            normalize_opencode_agent_name("Hephaestus - Deep Agent"),
            "Hephaestus"
        );
        assert_eq!(
            normalize_opencode_agent_name("Prometheus - Plan Builder"),
            "Prometheus"
        );
        assert_eq!(
            normalize_opencode_agent_name("Atlas - Plan Executor"),
            "Atlas"
        );
        assert_eq!(
            normalize_opencode_agent_name("Metis - Plan Consultant"),
            "Metis"
        );
        assert_eq!(
            normalize_opencode_agent_name("Momus - Plan Critic"),
            "Momus"
        );

        // ZWSP-prefixed names (oh-my-openagent sort-order prefixes)
        assert_eq!(
            normalize_opencode_agent_name("\u{200B}Sisyphus - Ultraworker"),
            "Sisyphus"
        );
        assert_eq!(
            normalize_opencode_agent_name("\u{200B}\u{200B}\u{200B}Prometheus - Plan Builder"),
            "Prometheus"
        );
        assert_eq!(
            normalize_opencode_agent_name("\u{200B}\u{200B}\u{200B}\u{200B}Atlas - Plan Executor"),
            "Atlas"
        );
        assert_eq!(
            normalize_opencode_agent_name("\u{FEFF}Momus - Plan Critic"),
            "Momus"
        );
        assert_eq!(
            normalize_opencode_agent_name("\u{200B}sisyphus-junior"),
            "Sisyphus-Junior"
        );
        assert_eq!(
            normalize_opencode_agent_name("\u{200B}sisyphus"),
            "Sisyphus"
        );
        assert_eq!(
            normalize_opencode_agent_name("\u{200B}  Sisyphus   -   Ultraworker  "),
            "Sisyphus"
        );
        assert_eq!(
            normalize_opencode_agent_name("\u{200B}\u{200B}\u{200B}   Prometheus    Plan Builder"),
            "Prometheus"
        );
    }

    #[test]
    fn test_strip_zero_width_chars() {
        assert_eq!(strip_zero_width_chars("hello"), "hello");
        assert_eq!(strip_zero_width_chars("\u{200B}hello"), "hello");
        assert_eq!(
            strip_zero_width_chars("\u{200B}\u{200B}\u{200B}hello"),
            "hello"
        );
        assert_eq!(strip_zero_width_chars("\u{FEFF}hello"), "hello");
        assert_eq!(strip_zero_width_chars("\u{200C}hello\u{200D}"), "hello");
        assert_eq!(strip_zero_width_chars(""), "");
        assert_eq!(
            strip_zero_width_chars("no special chars"),
            "no special chars"
        );
    }
}