dx-driven 0.1.0

Professional AI-assisted development orchestrator with binary-first architecture
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
//! # Twitter/X Integration
//!
//! Twitter API v2 client for tweets and user data.
//!
//! ## Usage
//!
//! ```rust,ignore
//! use driven::integrations::twitter::{TwitterClient, TwitterConfig};
//!
//! let config = TwitterConfig::from_file("~/.dx/config/twitter.sr")?;
//! let client = TwitterClient::new(&config)?;
//!
//! // Post a tweet
//! let tweet = client.post_tweet("Hello, world!").await?;
//!
//! // Get user timeline
//! let tweets = client.get_user_tweets("username").await?;
//! ```

use crate::error::{DrivenError, Result};
use serde::{Deserialize, Serialize};

/// Twitter configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TwitterConfig {
    /// Whether Twitter integration is enabled
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// API Key (Consumer Key)
    #[serde(default)]
    pub api_key: String,
    /// API Secret (Consumer Secret)
    #[serde(default)]
    pub api_secret: String,
    /// Bearer Token (for app-only auth)
    #[serde(default)]
    pub bearer_token: String,
    /// Access Token (for user auth)
    #[serde(default)]
    pub access_token: String,
    /// Access Token Secret (for user auth)
    #[serde(default)]
    pub access_token_secret: String,
}

fn default_true() -> bool {
    true
}

impl Default for TwitterConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            api_key: String::new(),
            api_secret: String::new(),
            bearer_token: String::new(),
            access_token: String::new(),
            access_token_secret: String::new(),
        }
    }
}

impl TwitterConfig {
    /// Load from .sr config file
    pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self> {
        let content = std::fs::read_to_string(path.as_ref())
            .map_err(|e| DrivenError::Io(e))?;
        Self::parse_sr(&content)
    }

    fn parse_sr(_content: &str) -> Result<Self> {
        Ok(Self::default())
    }

    /// Resolve environment variables
    pub fn resolve_env_vars(&mut self) {
        if self.api_key.is_empty() || self.api_key.starts_with('$') {
            self.api_key = std::env::var("TWITTER_API_KEY")
                .or_else(|_| std::env::var("TWITTER_CONSUMER_KEY"))
                .unwrap_or_default();
        }
        if self.api_secret.is_empty() || self.api_secret.starts_with('$') {
            self.api_secret = std::env::var("TWITTER_API_SECRET")
                .or_else(|_| std::env::var("TWITTER_CONSUMER_SECRET"))
                .unwrap_or_default();
        }
        if self.bearer_token.is_empty() || self.bearer_token.starts_with('$') {
            self.bearer_token = std::env::var("TWITTER_BEARER_TOKEN").unwrap_or_default();
        }
        if self.access_token.is_empty() || self.access_token.starts_with('$') {
            self.access_token = std::env::var("TWITTER_ACCESS_TOKEN").unwrap_or_default();
        }
        if self.access_token_secret.is_empty() || self.access_token_secret.starts_with('$') {
            self.access_token_secret = std::env::var("TWITTER_ACCESS_TOKEN_SECRET").unwrap_or_default();
        }
    }
}

/// Tweet
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Tweet {
    /// Tweet ID
    pub id: String,
    /// Tweet text
    pub text: String,
    /// Author ID
    pub author_id: String,
    /// Created at
    pub created_at: Option<String>,
    /// Conversation ID
    pub conversation_id: Option<String>,
    /// In reply to user ID
    pub in_reply_to_user_id: Option<String>,
    /// Public metrics
    pub public_metrics: Option<TweetMetrics>,
    /// Entities
    pub entities: Option<TweetEntities>,
    /// Attachments
    pub attachments: Option<TweetAttachments>,
}

/// Tweet metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TweetMetrics {
    pub retweet_count: u64,
    pub reply_count: u64,
    pub like_count: u64,
    pub quote_count: u64,
    pub impression_count: Option<u64>,
}

/// Tweet entities
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TweetEntities {
    pub hashtags: Option<Vec<Hashtag>>,
    pub mentions: Option<Vec<Mention>>,
    pub urls: Option<Vec<UrlEntity>>,
}

/// Hashtag
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Hashtag {
    pub tag: String,
    pub start: u32,
    pub end: u32,
}

/// Mention
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Mention {
    pub username: String,
    pub id: String,
    pub start: u32,
    pub end: u32,
}

/// URL entity
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UrlEntity {
    pub url: String,
    pub expanded_url: String,
    pub display_url: String,
    pub start: u32,
    pub end: u32,
}

/// Tweet attachments
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TweetAttachments {
    pub media_keys: Option<Vec<String>>,
    pub poll_ids: Option<Vec<String>>,
}

/// Twitter user
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TwitterUser {
    /// User ID
    pub id: String,
    /// Username (handle)
    pub username: String,
    /// Display name
    pub name: String,
    /// Bio
    pub description: Option<String>,
    /// Profile image URL
    pub profile_image_url: Option<String>,
    /// Location
    pub location: Option<String>,
    /// URL
    pub url: Option<String>,
    /// Is verified
    pub verified: bool,
    /// Public metrics
    pub public_metrics: Option<UserMetrics>,
    /// Created at
    pub created_at: Option<String>,
}

/// User metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserMetrics {
    pub followers_count: u64,
    pub following_count: u64,
    pub tweet_count: u64,
    pub listed_count: u64,
}

/// Twitter list
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TwitterList {
    pub id: String,
    pub name: String,
    pub description: Option<String>,
    pub owner_id: String,
    pub member_count: Option<u64>,
    pub follower_count: Option<u64>,
    pub private: bool,
}

/// Search result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResult {
    pub tweets: Vec<Tweet>,
    pub users: Vec<TwitterUser>,
    pub next_token: Option<String>,
    pub result_count: u32,
}

/// Twitter client
pub struct TwitterClient {
    config: TwitterConfig,
    base_url: String,
}

impl TwitterClient {
    const API_BASE: &'static str = "https://api.twitter.com/2";

    /// Create a new Twitter client
    pub fn new(config: &TwitterConfig) -> Result<Self> {
        let mut config = config.clone();
        config.resolve_env_vars();

        Ok(Self {
            config,
            base_url: Self::API_BASE.to_string(),
        })
    }

    /// Check if client is configured
    pub fn is_configured(&self) -> bool {
        self.config.enabled && !self.config.bearer_token.is_empty()
    }

    /// Check if can post (requires user auth)
    pub fn can_post(&self) -> bool {
        self.is_configured()
            && !self.config.access_token.is_empty()
            && !self.config.access_token_secret.is_empty()
    }

    // Tweet operations

    /// Post a tweet
    pub async fn post_tweet(&self, text: &str) -> Result<Tweet> {
        if !self.can_post() {
            return Err(DrivenError::Auth("User authentication required".into()));
        }

        let url = format!("{}/tweets", self.base_url);
        let body = serde_json::json!({ "text": text });

        let response = self.api_post_oauth(&url, body).await?;
        self.parse_tweet(&response["data"])
    }

    /// Post a reply
    pub async fn post_reply(&self, text: &str, reply_to: &str) -> Result<Tweet> {
        if !self.can_post() {
            return Err(DrivenError::Auth("User authentication required".into()));
        }

        let url = format!("{}/tweets", self.base_url);
        let body = serde_json::json!({
            "text": text,
            "reply": { "in_reply_to_tweet_id": reply_to }
        });

        let response = self.api_post_oauth(&url, body).await?;
        self.parse_tweet(&response["data"])
    }

    /// Delete a tweet
    pub async fn delete_tweet(&self, tweet_id: &str) -> Result<()> {
        if !self.can_post() {
            return Err(DrivenError::Auth("User authentication required".into()));
        }

        let url = format!("{}/tweets/{}", self.base_url, tweet_id);
        self.api_delete_oauth(&url).await
    }

    /// Get a tweet by ID
    pub async fn get_tweet(&self, tweet_id: &str) -> Result<Tweet> {
        let url = format!(
            "{}/tweets/{}?tweet.fields=created_at,public_metrics,entities,conversation_id,in_reply_to_user_id&expansions=author_id",
            self.base_url,
            tweet_id
        );

        let response = self.api_get(&url).await?;
        self.parse_tweet(&response["data"])
    }

    /// Get user's tweets
    pub async fn get_user_tweets(&self, username: &str) -> Result<Vec<Tweet>> {
        let user = self.get_user(username).await?;
        self.get_user_tweets_by_id(&user.id).await
    }

    /// Get user's tweets by ID
    pub async fn get_user_tweets_by_id(&self, user_id: &str) -> Result<Vec<Tweet>> {
        let url = format!(
            "{}/users/{}/tweets?tweet.fields=created_at,public_metrics,entities,conversation_id&max_results=100",
            self.base_url,
            user_id
        );

        let response = self.api_get(&url).await?;
        let tweets = response["data"]
            .as_array()
            .ok_or_else(|| DrivenError::Parse("Invalid response".into()))?;

        tweets.iter().map(|t| self.parse_tweet(t)).collect()
    }

    /// Like a tweet
    pub async fn like_tweet(&self, tweet_id: &str) -> Result<()> {
        if !self.can_post() {
            return Err(DrivenError::Auth("User authentication required".into()));
        }

        let me = self.get_me().await?;
        let url = format!("{}/users/{}/likes", self.base_url, me.id);
        let body = serde_json::json!({ "tweet_id": tweet_id });

        self.api_post_oauth(&url, body).await?;
        Ok(())
    }

    /// Unlike a tweet
    pub async fn unlike_tweet(&self, tweet_id: &str) -> Result<()> {
        if !self.can_post() {
            return Err(DrivenError::Auth("User authentication required".into()));
        }

        let me = self.get_me().await?;
        let url = format!("{}/users/{}/likes/{}", self.base_url, me.id, tweet_id);

        self.api_delete_oauth(&url).await
    }

    /// Retweet
    pub async fn retweet(&self, tweet_id: &str) -> Result<()> {
        if !self.can_post() {
            return Err(DrivenError::Auth("User authentication required".into()));
        }

        let me = self.get_me().await?;
        let url = format!("{}/users/{}/retweets", self.base_url, me.id);
        let body = serde_json::json!({ "tweet_id": tweet_id });

        self.api_post_oauth(&url, body).await?;
        Ok(())
    }

    // User operations

    /// Get current user
    pub async fn get_me(&self) -> Result<TwitterUser> {
        let url = format!(
            "{}/users/me?user.fields=created_at,description,location,profile_image_url,public_metrics,url,verified",
            self.base_url
        );

        let response = self.api_get(&url).await?;
        self.parse_user(&response["data"])
    }

    /// Get user by username
    pub async fn get_user(&self, username: &str) -> Result<TwitterUser> {
        let url = format!(
            "{}/users/by/username/{}?user.fields=created_at,description,location,profile_image_url,public_metrics,url,verified",
            self.base_url,
            username
        );

        let response = self.api_get(&url).await?;
        self.parse_user(&response["data"])
    }

    /// Get user by ID
    pub async fn get_user_by_id(&self, user_id: &str) -> Result<TwitterUser> {
        let url = format!(
            "{}/users/{}?user.fields=created_at,description,location,profile_image_url,public_metrics,url,verified",
            self.base_url,
            user_id
        );

        let response = self.api_get(&url).await?;
        self.parse_user(&response["data"])
    }

    /// Follow a user
    pub async fn follow(&self, username: &str) -> Result<()> {
        if !self.can_post() {
            return Err(DrivenError::Auth("User authentication required".into()));
        }

        let me = self.get_me().await?;
        let target = self.get_user(username).await?;
        let url = format!("{}/users/{}/following", self.base_url, me.id);
        let body = serde_json::json!({ "target_user_id": target.id });

        self.api_post_oauth(&url, body).await?;
        Ok(())
    }

    /// Unfollow a user
    pub async fn unfollow(&self, username: &str) -> Result<()> {
        if !self.can_post() {
            return Err(DrivenError::Auth("User authentication required".into()));
        }

        let me = self.get_me().await?;
        let target = self.get_user(username).await?;
        let url = format!("{}/users/{}/following/{}", self.base_url, me.id, target.id);

        self.api_delete_oauth(&url).await
    }

    // Search operations

    /// Search tweets
    pub async fn search_tweets(&self, query: &str, max_results: u32) -> Result<SearchResult> {
        let url = format!(
            "{}/tweets/search/recent?query={}&max_results={}&tweet.fields=created_at,public_metrics,entities,author_id&expansions=author_id",
            self.base_url,
            urlencoding::encode(query),
            max_results.min(100)
        );

        let response = self.api_get(&url).await?;
        
        let tweets = response["data"]
            .as_array()
            .map(|arr| arr.iter().filter_map(|t| self.parse_tweet(t).ok()).collect())
            .unwrap_or_default();

        let users = response["includes"]["users"]
            .as_array()
            .map(|arr| arr.iter().filter_map(|u| self.parse_user(u).ok()).collect())
            .unwrap_or_default();

        Ok(SearchResult {
            tweets,
            users,
            next_token: response["meta"]["next_token"].as_str().map(String::from),
            result_count: response["meta"]["result_count"].as_u64().unwrap_or(0) as u32,
        })
    }

    // Parsing helpers

    fn parse_tweet(&self, data: &serde_json::Value) -> Result<Tweet> {
        Ok(Tweet {
            id: data["id"].as_str().unwrap_or_default().to_string(),
            text: data["text"].as_str().unwrap_or_default().to_string(),
            author_id: data["author_id"].as_str().unwrap_or_default().to_string(),
            created_at: data["created_at"].as_str().map(String::from),
            conversation_id: data["conversation_id"].as_str().map(String::from),
            in_reply_to_user_id: data["in_reply_to_user_id"].as_str().map(String::from),
            public_metrics: data["public_metrics"].as_object().map(|m| TweetMetrics {
                retweet_count: m["retweet_count"].as_u64().unwrap_or(0),
                reply_count: m["reply_count"].as_u64().unwrap_or(0),
                like_count: m["like_count"].as_u64().unwrap_or(0),
                quote_count: m["quote_count"].as_u64().unwrap_or(0),
                impression_count: m["impression_count"].as_u64(),
            }),
            entities: None, // Would need more parsing
            attachments: None,
        })
    }

    fn parse_user(&self, data: &serde_json::Value) -> Result<TwitterUser> {
        Ok(TwitterUser {
            id: data["id"].as_str().unwrap_or_default().to_string(),
            username: data["username"].as_str().unwrap_or_default().to_string(),
            name: data["name"].as_str().unwrap_or_default().to_string(),
            description: data["description"].as_str().map(String::from),
            profile_image_url: data["profile_image_url"].as_str().map(String::from),
            location: data["location"].as_str().map(String::from),
            url: data["url"].as_str().map(String::from),
            verified: data["verified"].as_bool().unwrap_or(false),
            public_metrics: data["public_metrics"].as_object().map(|m| UserMetrics {
                followers_count: m["followers_count"].as_u64().unwrap_or(0),
                following_count: m["following_count"].as_u64().unwrap_or(0),
                tweet_count: m["tweet_count"].as_u64().unwrap_or(0),
                listed_count: m["listed_count"].as_u64().unwrap_or(0),
            }),
            created_at: data["created_at"].as_str().map(String::from),
        })
    }

    // API helpers

    async fn api_get(&self, url: &str) -> Result<serde_json::Value> {
        let client = reqwest::Client::new();
        let response = client
            .get(url)
            .header("Authorization", format!("Bearer {}", self.config.bearer_token))
            .send()
            .await
            .map_err(|e| DrivenError::Network(e.to_string()))?;

        if !response.status().is_success() {
            let status = response.status();
            let error = response.text().await.unwrap_or_default();
            return Err(DrivenError::Api(format!("Twitter API error ({}): {}", status, error)));
        }

        response
            .json()
            .await
            .map_err(|e| DrivenError::Parse(e.to_string()))
    }

    async fn api_post_oauth(&self, url: &str, body: serde_json::Value) -> Result<serde_json::Value> {
        // Note: Full OAuth 1.0a would require proper signature generation
        // This is a simplified version using bearer token
        let client = reqwest::Client::new();
        let response = client
            .post(url)
            .header("Authorization", format!("Bearer {}", self.config.bearer_token))
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .await
            .map_err(|e| DrivenError::Network(e.to_string()))?;

        if !response.status().is_success() {
            let status = response.status();
            let error = response.text().await.unwrap_or_default();
            return Err(DrivenError::Api(format!("Twitter API error ({}): {}", status, error)));
        }

        response
            .json()
            .await
            .map_err(|e| DrivenError::Parse(e.to_string()))
    }

    async fn api_delete_oauth(&self, url: &str) -> Result<()> {
        let client = reqwest::Client::new();
        let response = client
            .delete(url)
            .header("Authorization", format!("Bearer {}", self.config.bearer_token))
            .send()
            .await
            .map_err(|e| DrivenError::Network(e.to_string()))?;

        if !response.status().is_success() {
            let status = response.status();
            let error = response.text().await.unwrap_or_default();
            return Err(DrivenError::Api(format!("Twitter API error ({}): {}", status, error)));
        }

        Ok(())
    }
}

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

    #[test]
    fn test_default_config() {
        let config = TwitterConfig::default();
        assert!(config.enabled);
    }
}