xmaster 1.6.0

Enterprise-grade X/Twitter CLI — post, reply, like, retweet, DM, search, and more
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
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
use clap::{Parser, Subcommand};

#[derive(Parser)]
#[command(
    name = "xmaster",
    version,
    about = "Enterprise-grade X/Twitter CLI — post, reply, like, retweet, DM, search, and more",
    long_about = "Built by 199 Biotechnologies for AI agents and humans.\n\nAgent-friendly: auto-JSON when piped, semantic exit codes, structured errors."
)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Commands,

    /// Output as JSON (auto-enabled when piped)
    #[arg(long, global = true)]
    pub json: bool,
}

#[derive(Subcommand)]
pub enum Commands {
    /// Post a tweet (text, media, reply, quote, poll)
    Post {
        /// Tweet text
        text: String,
        /// Reply to a tweet ID
        #[arg(long)]
        reply_to: Option<String>,
        /// Quote a tweet ID
        #[arg(long)]
        quote: Option<String>,
        /// Media file paths to attach
        #[arg(long, num_args = 1..=4)]
        media: Vec<String>,
        /// Poll options (comma-separated)
        #[arg(long)]
        poll: Option<String>,
        /// Poll duration in minutes (default 1440 = 24h)
        #[arg(long, default_value = "1440")]
        poll_duration: u64,
    },

    /// Delete a tweet
    Delete {
        /// Tweet ID to delete
        id: String,
    },

    /// Read a post — full text, author, date, metrics, media URLs in one call
    Read {
        /// Tweet ID or URL
        id: String,
    },

    /// Like a tweet
    Like {
        /// Tweet ID or URL
        id: String,
    },

    /// Unlike a tweet
    Unlike {
        /// Tweet ID or URL
        id: String,
    },

    /// Retweet a tweet
    Retweet {
        /// Tweet ID or URL
        id: String,
    },

    /// Undo a retweet
    Unretweet {
        /// Tweet ID or URL
        id: String,
    },

    /// Bookmark a tweet
    Bookmark {
        /// Tweet ID or URL
        id: String,
    },

    /// Remove a bookmark
    Unbookmark {
        /// Tweet ID or URL
        id: String,
    },

    /// Follow a user
    Follow {
        /// Username (without @)
        username: String,
    },

    /// Unfollow a user
    Unfollow {
        /// Username (without @)
        username: String,
    },

    /// Direct messages
    Dm {
        #[command(subcommand)]
        action: DmCommands,
    },

    /// View timeline
    Timeline {
        /// Username (omit for home timeline)
        #[arg(long)]
        user: Option<String>,
        /// Number of tweets
        #[arg(long, short, alias = "limit", default_value = "10")]
        count: usize,
        /// Only show posts after this time (e.g. "12h", "7d", or ISO 8601)
        #[arg(long)]
        since: Option<String>,
        /// Only show posts before this time (e.g. "12h", "7d", or ISO 8601)
        #[arg(long)]
        before: Option<String>,
        /// Sort by: impressions, likes, retweets, date (default: date)
        #[arg(long)]
        sort: Option<String>,
    },

    /// View your mentions
    Mentions {
        /// Number of mentions
        #[arg(long, short, alias = "limit", default_value = "10")]
        count: usize,
        /// Only show mentions after this tweet ID
        #[arg(long)]
        since_id: Option<String>,
    },

    /// Search tweets (X API v2)
    Search {
        /// Search query
        query: String,
        /// Search mode
        #[arg(long, default_value = "recent")]
        mode: String,
        /// Number of results
        #[arg(long, short, alias = "limit", default_value = "10")]
        count: usize,
        /// Only show posts after this time (e.g. "12h", "7d", or ISO 8601)
        #[arg(long)]
        since: Option<String>,
        /// Only show posts before this time (e.g. "12h", "7d", or ISO 8601)
        #[arg(long)]
        before: Option<String>,
    },

    /// AI-powered search (xAI/Grok)
    SearchAi {
        /// Search query
        query: String,
        /// Number of results
        #[arg(long, short, alias = "limit", default_value = "10")]
        count: usize,
        /// Filter by date (from)
        #[arg(long)]
        from_date: Option<String>,
        /// Filter by date (to)
        #[arg(long)]
        to_date: Option<String>,
    },

    /// Get trending topics
    Trending {
        /// Region filter
        #[arg(long)]
        region: Option<String>,
        /// Category filter
        #[arg(long)]
        category: Option<String>,
        /// Use personalized trends (requires X Premium)
        #[arg(long)]
        personalized: bool,
    },

    /// Get user info
    User {
        /// Username (without @)
        username: String,
    },

    /// Get authenticated user info
    Me,

    /// Manage bookmarks (sync, search, export, digest)
    Bookmarks {
        #[command(subcommand)]
        action: BookmarkCommands,
    },

    /// List followers
    Followers {
        /// Username (without @)
        username: String,
        /// Number of results
        #[arg(long, short, alias = "limit", default_value = "20")]
        count: usize,
    },

    /// List following
    Following {
        /// Username (without @)
        username: String,
        /// Number of results
        #[arg(long, short, alias = "limit", default_value = "20")]
        count: usize,
    },

    /// Manage configuration
    Config {
        #[command(subcommand)]
        action: ConfigCommands,
    },

    /// Show agent-readable capabilities
    AgentInfo,

    /// Post a multi-tweet thread
    Thread {
        /// Tweet texts (one per thread tweet)
        texts: Vec<String>,
        /// Media file paths to attach to the first tweet
        #[arg(long, num_args = 1..=4)]
        media: Vec<String>,
    },

    /// Reply to a tweet (shorthand for post --reply-to)
    Reply {
        /// Tweet ID or URL to reply to
        id: String,
        /// Reply text
        text: String,
        /// Media file paths
        #[arg(long, num_args = 1..=4)]
        media: Vec<String>,
    },

    /// Get tweet engagement metrics
    Metrics {
        /// Tweet ID(s) or URL(s)
        ids: Vec<String>,
    },

    /// Manage X lists
    Lists {
        #[command(subcommand)]
        action: ListCommands,
    },

    /// Hide a reply to your tweet
    HideReply {
        /// Tweet ID or URL
        id: String,
    },

    /// Unhide a reply to your tweet
    UnhideReply {
        /// Tweet ID or URL
        id: String,
    },

    /// Get replies to a tweet (uses conversation_id search)
    Replies {
        /// Tweet ID or URL
        id: String,
        /// Max replies to fetch
        #[arg(long, short, alias = "limit", default_value = "20")]
        count: usize,
    },

    /// List users who liked a tweet
    Likers {
        /// Tweet ID or URL
        id: String,
        /// Max users to fetch (1-100)
        #[arg(long, short, alias = "limit", default_value = "50")]
        count: usize,
    },

    /// List users who retweeted a tweet
    Retweeters {
        /// Tweet ID or URL
        id: String,
        /// Max users to fetch (1-100)
        #[arg(long, short, alias = "limit", default_value = "50")]
        count: usize,
    },

    /// List quote tweets of a tweet (persisted into discovered_posts)
    Quotes {
        /// Tweet ID or URL
        id: String,
        /// Max quotes to fetch (10-100)
        #[arg(long, short, alias = "limit", default_value = "50")]
        count: usize,
    },

    /// Batch-lookup multiple users by username in a single call
    Users {
        /// Usernames (without @)
        usernames: Vec<String>,
    },

    /// Show recent tweet volume for a search query over time
    Volume {
        /// Search query
        query: String,
        /// Time granularity: minute, hour, day
        #[arg(long, default_value = "hour")]
        granularity: String,
    },

    /// Show who amplifies your content (users who repost your tweets)
    Amplifiers {
        /// Max reposts to scan (10-100)
        #[arg(long, short, alias = "limit", default_value = "50")]
        count: usize,
    },

    /// Show API rate limit status
    RateLimits,

    /// Block a user
    Block {
        /// Username (without @)
        username: String,
    },

    /// Unblock a user
    Unblock {
        /// Username (without @)
        username: String,
    },

    /// Mute a user
    Mute {
        /// Username (without @)
        username: String,
    },

    /// Unmute a user
    Unmute {
        /// Username (without @)
        username: String,
    },

    /// Analyze a tweet before posting (pre-flight check)
    Analyze {
        /// Tweet text to analyze
        text: String,
        /// Optimization goal (replies, impressions)
        #[arg(long)]
        goal: Option<String>,
    },

    /// Browse your discovered posts library for content inspiration
    Inspire {
        /// Filter by topic (searches post text)
        #[arg(long)]
        topic: Option<String>,
        /// Filter by author username
        #[arg(long)]
        author: Option<String>,
        /// Minimum like count
        #[arg(long)]
        min_likes: Option<i64>,
        /// Number of results
        #[arg(long, alias = "limit", default_value = "20")]
        count: usize,
    },

    /// Track metric snapshots for recent posts
    Track {
        #[command(subcommand)]
        action: TrackCommands,
    },

    /// Performance reports
    Report {
        #[command(subcommand)]
        action: ReportCommands,
    },

    /// Timing and posting suggestions
    Suggest {
        #[command(subcommand)]
        action: SuggestCommands,
    },

    /// Schedule posts for later
    Schedule {
        #[command(subcommand)]
        action: ScheduleCommands,
    },

    /// Engagement intelligence
    Engage {
        #[command(subcommand)]
        action: EngageCommands,
    },

    /// Install or update the xmaster agent skill for all AI platforms
    Skill {
        #[command(subcommand)]
        action: SkillCommands,
    },

    /// Self-update from GitHub releases
    Update {
        /// Check for updates without installing
        #[arg(long)]
        check: bool,
    },

    /// Open the xmaster GitHub repo to star it
    Star,
}

#[derive(Subcommand)]
pub enum SkillCommands {
    /// Install skill to all detected agent platforms (Claude, Codex, Gemini, etc.)
    Install,
    /// Update skill to latest version bundled in this binary
    Update,
    /// Show where the skill is installed
    Status,
}

#[derive(Subcommand)]
pub enum EngageCommands {
    /// Find high-ROI reply targets in your niche
    Recommend {
        /// Topic to discover targets (uses AI search)
        #[arg(long)]
        topic: Option<String>,
        /// Minimum follower count for targets
        #[arg(long, default_value = "1000")]
        min_followers: u32,
        /// Number of recommendations
        #[arg(long, short, alias = "limit", default_value = "5")]
        count: usize,
    },
    /// Manage your niche watchlist (accounts you track but don't follow)
    Watchlist {
        #[command(subcommand)]
        action: WatchlistCommands,
    },
    /// Find fresh posts from big accounts to reply to NOW.
    ///
    /// Accepts multiple topics positionally AND as comma-separated lists
    /// (they are merged + deduped). If no topics are passed, falls back to
    /// `niche.topics` from config, enabling zero-arg multi-topic fanout
    /// in a single call. Results are unioned across all topics and ranked
    /// together, so the agent never needs to loop per-topic.
    ///
    /// Examples:
    ///   xmaster engage feed "AI science"
    ///   xmaster engage feed "AI science" "biotech longevity" "gene therapy"
    ///   xmaster engage feed "AI,biotech,gene therapy"
    ///   xmaster engage feed                       # uses niche.topics
    Feed {
        /// Zero or more topics/niches to scan. Comma-separated values are
        /// split and merged with positional entries.
        topics: Vec<String>,
        /// Minimum follower count for authors
        #[arg(long, default_value = "5000")]
        min_followers: u64,
        /// Maximum age in minutes (default: 60)
        #[arg(long, default_value = "60")]
        max_age_mins: u64,
        /// Number of posts to return (unified across all topics)
        #[arg(long, short, alias = "limit", default_value = "10")]
        count: usize,
    },
    /// Rank accounts you've already replied to by downstream reply performance.
    ///
    /// Aggregates your sent replies from the last N days, groups by target
    /// username, and computes avg impressions, avg profile clicks, reply-back
    /// rate, and a composite score. Use this to find which accounts reward
    /// your reply effort with the most reach — then prioritize re-engaging.
    HotTargets {
        /// Look back this many days
        #[arg(long, default_value = "7")]
        days: i64,
        /// Minimum avg impressions across samples (HAVING filter)
        #[arg(long, default_value = "100")]
        min_imps: i64,
        /// Minimum avg profile clicks across samples (HAVING filter)
        #[arg(long, default_value = "0")]
        min_profile_clicks: i64,
        /// Minimum reply count per target (HAVING filter)
        #[arg(long, default_value = "1")]
        min_samples: i64,
        /// Number of results
        #[arg(long, short, alias = "limit", default_value = "10")]
        count: usize,
        /// Sort order: score | avg-impressions | avg-profile-clicks | reply-back-rate
        #[arg(long, default_value = "score")]
        sort: String,
    },
}

#[derive(Subcommand)]
pub enum WatchlistCommands {
    /// Add an account to your watchlist
    Add {
        /// Username (without @)
        username: String,
        /// Topic/niche tag
        #[arg(long)]
        topic: Option<String>,
    },
    /// List watched accounts
    List,
    /// Remove an account from your watchlist
    Remove {
        /// Username (without @)
        username: String,
    },
}

#[derive(Subcommand)]
pub enum ScheduleCommands {
    /// Schedule a new post
    Add {
        /// Tweet text
        content: String,
        /// When to post: ISO datetime "2026-03-24 09:00" or "auto" for best time
        #[arg(long)]
        at: String,
        /// Reply to tweet ID
        #[arg(long)]
        reply_to: Option<String>,
        /// Quote tweet ID
        #[arg(long)]
        quote: Option<String>,
        /// Media file paths
        #[arg(long, num_args = 1..=4)]
        media: Vec<String>,
    },
    /// List scheduled posts
    List {
        /// Filter by status: pending, sent, failed, cancelled
        #[arg(long)]
        status: Option<String>,
    },
    /// Cancel a scheduled post
    Cancel {
        /// Schedule ID
        id: String,
    },
    /// Reschedule a post
    Reschedule {
        /// Schedule ID
        id: String,
        /// New time: ISO datetime or "auto"
        #[arg(long)]
        at: String,
    },
    /// Fire all due scheduled posts (run via cron/launchd)
    Fire,
    /// Set up launchd for automatic scheduling (macOS)
    Setup,
}

#[derive(Subcommand)]
pub enum TrackCommands {
    /// Snapshot metrics for all recent posts (run via cron)
    Run,
    /// Show tracking status for recent posts
    Status,
    /// Snapshot follower count and detect new/lost followers
    Followers,
    /// Show follower growth history
    Growth {
        /// Number of days of history [default: 30]
        #[arg(long, short, default_value = "30")]
        days: i64,
    },
}

#[derive(Subcommand)]
pub enum ReportCommands {
    /// Daily performance report
    Daily,
    /// Weekly performance report
    Weekly,
}

#[derive(Subcommand)]
pub enum SuggestCommands {
    /// Show best posting times from your history
    BestTime,
    /// Check if it's safe to post now (cannibalization guard)
    NextPost,
}

#[derive(Subcommand)]
pub enum ListCommands {
    /// Create a new list
    Create {
        /// List name
        name: String,
        /// List description
        #[arg(long)]
        description: Option<String>,
    },
    /// Delete a list
    Delete {
        /// List ID
        id: String,
    },
    /// Add a user to a list
    Add {
        /// List ID
        list_id: String,
        /// Username (without @)
        username: String,
    },
    /// Remove a user from a list
    Remove {
        /// List ID
        list_id: String,
        /// Username (without @)
        username: String,
    },
    /// View list timeline
    Timeline {
        /// List ID
        list_id: String,
        /// Number of tweets
        #[arg(long, short, alias = "limit", default_value = "10")]
        count: usize,
    },
    /// List the members of a list
    Members {
        /// List ID
        list_id: String,
        /// Number of members to fetch (1-100)
        #[arg(long, short, alias = "limit", default_value = "50")]
        count: usize,
    },
    /// List your owned lists
    Mine {
        /// Number of results
        #[arg(long, short, alias = "limit", default_value = "20")]
        count: usize,
    },
}

#[derive(Subcommand)]
pub enum DmCommands {
    /// Send a direct message
    Send {
        /// Username (without @)
        username: String,
        /// Message text
        text: String,
    },
    /// View DM inbox
    Inbox {
        /// Number of conversations
        #[arg(long, short, alias = "limit", default_value = "10")]
        count: usize,
    },
    /// View a DM thread
    Thread {
        /// Conversation ID
        id: String,
        /// Number of messages
        #[arg(long, short, alias = "limit", default_value = "20")]
        count: usize,
    },
}

#[derive(Subcommand)]
pub enum ConfigCommands {
    /// Show current configuration (keys masked)
    Show,
    /// Get a single configuration value (raw, no masking for non-secret keys)
    Get {
        /// Key path (e.g., style.voice, account.premium)
        key: String,
    },
    /// Set a configuration value
    Set {
        /// Key path (e.g., keys.api_key)
        key: String,
        /// Value to set
        value: String,
    },
    /// Validate configured credentials
    Check,
    /// Step-by-step setup guide for X API and xAI keys
    Guide,
    /// Authorize OAuth 2.0 (required for bookmarks)
    Auth,
    /// Auto-capture X web cookies from your browser (enables reply fallback)
    WebLogin,
}

#[derive(Subcommand)]
pub enum BookmarkCommands {
    /// List recent bookmarks
    List {
        #[arg(long, short, alias = "limit", default_value = "10")]
        count: usize,
        /// Show only unread
        #[arg(long)]
        unread: bool,
    },
    /// Sync bookmarks from X to local database (preserves deleted tweets)
    Sync {
        /// Number of bookmarks to fetch from X
        #[arg(long, short, alias = "limit", default_value = "100")]
        count: usize,
    },
    /// Search saved bookmarks locally
    Search {
        /// Search query
        query: String,
    },
    /// Export bookmarks as markdown
    Export {
        /// Output file path
        #[arg(long, short)]
        output: Option<String>,
        /// Only export unread
        #[arg(long)]
        unread: bool,
    },
    /// Get bookmark digest (summary of recent saves)
    Digest {
        /// Number of days to cover
        #[arg(long, short, default_value = "7")]
        days: u32,
    },
    /// Show bookmark statistics
    Stats,
    /// List bookmark folders
    Folders,
    /// List bookmarks in a specific folder
    Folder {
        /// Folder ID
        id: String,
        /// Number of bookmarks to fetch
        #[arg(long, short, alias = "limit", default_value = "20")]
        count: usize,
    },
}

/// Parse a tweet ID from a URL or raw ID string.
/// Handles URLs like `.../status/12345/photo/1` by finding the segment after "status".
pub fn parse_tweet_id(input: &str) -> String {
    let input = input.trim();
    if input.contains("x.com/") || input.contains("twitter.com/") {
        let parts: Vec<&str> = input.split('/').filter(|s| !s.is_empty()).collect();
        // Find the segment immediately after "status"
        if let Some(pos) = parts.iter().position(|&p| p == "status") {
            if let Some(id_part) = parts.get(pos + 1) {
                let id = id_part.split('?').next().unwrap_or(id_part);
                if !id.is_empty() && id.chars().all(|c| c.is_ascii_digit()) {
                    return id.to_string();
                }
            }
        }
    }
    input.to_string()
}

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

    #[test]
    fn raw_id() {
        assert_eq!(parse_tweet_id("1234567890"), "1234567890");
    }

    #[test]
    fn x_url() {
        assert_eq!(
            parse_tweet_id("https://x.com/user/status/1234567890"),
            "1234567890"
        );
    }

    #[test]
    fn twitter_url() {
        assert_eq!(
            parse_tweet_id("https://twitter.com/user/status/1234567890"),
            "1234567890"
        );
    }

    #[test]
    fn url_with_query() {
        assert_eq!(
            parse_tweet_id("https://x.com/user/status/1234567890?s=20"),
            "1234567890"
        );
    }

    #[test]
    fn url_with_trailing_slash() {
        assert_eq!(
            parse_tweet_id("https://x.com/user/status/1234567890/"),
            "1234567890"
        );
    }

    #[test]
    fn url_with_multiple_query_params() {
        assert_eq!(
            parse_tweet_id("https://x.com/user/status/9876543210?s=20&t=abc"),
            "9876543210"
        );
    }

    #[test]
    fn whitespace_trimmed() {
        assert_eq!(parse_tweet_id("  1234567890  "), "1234567890");
    }

    #[test]
    fn url_with_photo_suffix() {
        assert_eq!(
            parse_tweet_id("https://x.com/user/status/1234567890/photo/1"),
            "1234567890"
        );
    }

    #[test]
    fn url_with_video_suffix() {
        assert_eq!(
            parse_tweet_id("https://x.com/user/status/9876543210/video/1"),
            "9876543210"
        );
    }
}