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
//! # Gmail Integration
//!
//! Gmail Pub/Sub listener and email operations.
//!
//! ## Usage
//!
//! ```rust,ignore
//! use driven::integrations::gmail::{GmailClient, GmailConfig};
//!
//! let config = GmailConfig::from_file("~/.dx/config/gmail.sr")?;
//! let client = GmailClient::new(&config).await?;
//!
//! // Watch for new emails
//! client.watch(&["INBOX"], |email| {
//!     println!("New email: {}", email.subject);
//! }).await?;
//! ```

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

/// Gmail configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GmailConfig {
    /// Whether Gmail integration is enabled
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// OAuth2 client ID
    #[serde(default)]
    pub client_id: String,
    /// OAuth2 client secret
    #[serde(default)]
    pub client_secret: String,
    /// OAuth2 refresh token
    #[serde(default)]
    pub refresh_token: String,
    /// Pub/Sub topic for push notifications
    pub pubsub_topic: Option<String>,
    /// Email filters
    #[serde(default)]
    pub filters: Vec<GmailFilter>,
}

fn default_true() -> bool {
    true
}

impl Default for GmailConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            client_id: String::new(),
            client_secret: String::new(),
            refresh_token: String::new(),
            pubsub_topic: None,
            filters: Vec::new(),
        }
    }
}

impl GmailConfig {
    /// 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.client_id.is_empty() || self.client_id.starts_with('$') {
            self.client_id = std::env::var("GMAIL_CLIENT_ID").unwrap_or_default();
        }
        if self.client_secret.is_empty() || self.client_secret.starts_with('$') {
            self.client_secret = std::env::var("GMAIL_CLIENT_SECRET").unwrap_or_default();
        }
        if self.refresh_token.is_empty() || self.refresh_token.starts_with('$') {
            self.refresh_token = std::env::var("GMAIL_REFRESH_TOKEN").unwrap_or_default();
        }
    }
}

/// Gmail filter for incoming emails
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GmailFilter {
    /// Filter name
    pub name: String,
    /// From address pattern
    pub from: Option<String>,
    /// Subject pattern
    pub subject: Option<String>,
    /// Label to match
    pub label: Option<String>,
    /// Action to perform
    pub action: GmailAction,
    /// Whether filter is enabled
    #[serde(default = "default_true")]
    pub enabled: bool,
}

/// Gmail filter action
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GmailAction {
    /// Forward to another email
    Forward { to: String },
    /// Run a command
    Command { cmd: String },
    /// Trigger a webhook
    Webhook { url: String },
    /// Archive the email
    Archive,
    /// Mark as read
    MarkRead,
}

/// Gmail message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GmailMessage {
    /// Message ID
    pub id: String,
    /// Thread ID
    pub thread_id: String,
    /// Subject
    pub subject: String,
    /// From address
    pub from: String,
    /// To addresses
    pub to: Vec<String>,
    /// CC addresses
    pub cc: Vec<String>,
    /// Date
    pub date: String,
    /// Snippet (preview)
    pub snippet: String,
    /// Labels
    pub labels: Vec<String>,
    /// Body (plain text)
    pub body_plain: Option<String>,
    /// Body (HTML)
    pub body_html: Option<String>,
    /// Attachments
    pub attachments: Vec<GmailAttachment>,
}

/// Gmail attachment
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GmailAttachment {
    /// Attachment ID
    pub id: String,
    /// Filename
    pub filename: String,
    /// MIME type
    pub mime_type: String,
    /// Size in bytes
    pub size: u64,
}

/// Gmail label
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GmailLabel {
    /// Label ID
    pub id: String,
    /// Label name
    pub name: String,
    /// Label type (system/user)
    pub label_type: String,
}

/// Gmail client
pub struct GmailClient {
    config: GmailConfig,
    access_token: Option<String>,
    base_url: String,
}

impl GmailClient {
    /// API base URL
    const API_BASE: &'static str = "https://gmail.googleapis.com/gmail/v1";
    /// OAuth token URL
    const TOKEN_URL: &'static str = "https://oauth2.googleapis.com/token";

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

        let mut client = Self {
            config,
            access_token: None,
            base_url: Self::API_BASE.to_string(),
        };

        // Get initial access token
        if client.is_configured() {
            client.refresh_access_token().await?;
        }

        Ok(client)
    }

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

    /// Refresh access token
    async fn refresh_access_token(&mut self) -> Result<()> {
        let client = reqwest::Client::new();

        let mut params = HashMap::new();
        params.insert("client_id", self.config.client_id.as_str());
        params.insert("client_secret", self.config.client_secret.as_str());
        params.insert("refresh_token", self.config.refresh_token.as_str());
        params.insert("grant_type", "refresh_token");

        let response = client
            .post(Self::TOKEN_URL)
            .form(&params)
            .send()
            .await
            .map_err(|e| DrivenError::Network(e.to_string()))?;

        if !response.status().is_success() {
            return Err(DrivenError::Api("Failed to refresh token".into()));
        }

        #[derive(Deserialize)]
        struct TokenResponse {
            access_token: String,
        }

        let tokens: TokenResponse = response
            .json()
            .await
            .map_err(|e| DrivenError::Parse(e.to_string()))?;

        self.access_token = Some(tokens.access_token);
        Ok(())
    }

    /// List messages
    pub async fn list_messages(&self, query: Option<&str>, max_results: u32) -> Result<Vec<GmailMessage>> {
        let token = self.access_token.as_ref()
            .ok_or_else(|| DrivenError::Config("Not authenticated".into()))?;

        let mut url = format!(
            "{}/users/me/messages?maxResults={}",
            self.base_url, max_results
        );

        if let Some(q) = query {
            url.push_str(&format!("&q={}", urlencoding::encode(q)));
        }

        let client = reqwest::Client::new();
        let response = client
            .get(&url)
            .header("Authorization", format!("Bearer {}", token))
            .send()
            .await
            .map_err(|e| DrivenError::Network(e.to_string()))?;

        if !response.status().is_success() {
            return Err(DrivenError::Api("Failed to list messages".into()));
        }

        #[derive(Deserialize)]
        struct ListResponse {
            messages: Option<Vec<MessageId>>,
        }

        #[derive(Deserialize)]
        struct MessageId {
            id: String,
        }

        let list: ListResponse = response
            .json()
            .await
            .map_err(|e| DrivenError::Parse(e.to_string()))?;

        let mut messages = Vec::new();
        if let Some(msg_ids) = list.messages {
            for msg_id in msg_ids.into_iter().take(max_results as usize) {
                if let Ok(msg) = self.get_message(&msg_id.id).await {
                    messages.push(msg);
                }
            }
        }

        Ok(messages)
    }

    /// Get a specific message
    pub async fn get_message(&self, id: &str) -> Result<GmailMessage> {
        let token = self.access_token.as_ref()
            .ok_or_else(|| DrivenError::Config("Not authenticated".into()))?;

        let url = format!(
            "{}/users/me/messages/{}?format=full",
            self.base_url, id
        );

        let client = reqwest::Client::new();
        let response = client
            .get(&url)
            .header("Authorization", format!("Bearer {}", token))
            .send()
            .await
            .map_err(|e| DrivenError::Network(e.to_string()))?;

        if !response.status().is_success() {
            return Err(DrivenError::Api("Failed to get message".into()));
        }

        let raw: serde_json::Value = response
            .json()
            .await
            .map_err(|e| DrivenError::Parse(e.to_string()))?;

        self.parse_message(raw)
    }

    /// Send an email
    pub async fn send(&self, to: &[&str], subject: &str, body: &str) -> Result<String> {
        let token = self.access_token.as_ref()
            .ok_or_else(|| DrivenError::Config("Not authenticated".into()))?;

        // Build RFC 2822 message
        let message = format!(
            "To: {}\r\nSubject: {}\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n{}",
            to.join(", "),
            subject,
            body
        );

        let encoded = base64::encode_config(message.as_bytes(), base64::URL_SAFE_NO_PAD);

        let url = format!("{}/users/me/messages/send", self.base_url);

        let client = reqwest::Client::new();
        let response = client
            .post(&url)
            .header("Authorization", format!("Bearer {}", token))
            .json(&serde_json::json!({ "raw": encoded }))
            .send()
            .await
            .map_err(|e| DrivenError::Network(e.to_string()))?;

        if !response.status().is_success() {
            return Err(DrivenError::Api("Failed to send message".into()));
        }

        #[derive(Deserialize)]
        struct SendResponse {
            id: String,
        }

        let result: SendResponse = response
            .json()
            .await
            .map_err(|e| DrivenError::Parse(e.to_string()))?;

        Ok(result.id)
    }

    /// Archive a message
    pub async fn archive(&self, id: &str) -> Result<()> {
        self.modify_labels(id, &[], &["INBOX"]).await
    }

    /// Mark message as read
    pub async fn mark_read(&self, id: &str) -> Result<()> {
        self.modify_labels(id, &[], &["UNREAD"]).await
    }

    /// Mark message as unread
    pub async fn mark_unread(&self, id: &str) -> Result<()> {
        self.modify_labels(id, &["UNREAD"], &[]).await
    }

    /// Modify message labels
    pub async fn modify_labels(&self, id: &str, add: &[&str], remove: &[&str]) -> Result<()> {
        let token = self.access_token.as_ref()
            .ok_or_else(|| DrivenError::Config("Not authenticated".into()))?;

        let url = format!("{}/users/me/messages/{}/modify", self.base_url, id);

        let client = reqwest::Client::new();
        let response = client
            .post(&url)
            .header("Authorization", format!("Bearer {}", token))
            .json(&serde_json::json!({
                "addLabelIds": add,
                "removeLabelIds": remove
            }))
            .send()
            .await
            .map_err(|e| DrivenError::Network(e.to_string()))?;

        if !response.status().is_success() {
            return Err(DrivenError::Api("Failed to modify labels".into()));
        }

        Ok(())
    }

    /// List labels
    pub async fn list_labels(&self) -> Result<Vec<GmailLabel>> {
        let token = self.access_token.as_ref()
            .ok_or_else(|| DrivenError::Config("Not authenticated".into()))?;

        let url = format!("{}/users/me/labels", self.base_url);

        let client = reqwest::Client::new();
        let response = client
            .get(&url)
            .header("Authorization", format!("Bearer {}", token))
            .send()
            .await
            .map_err(|e| DrivenError::Network(e.to_string()))?;

        if !response.status().is_success() {
            return Err(DrivenError::Api("Failed to list labels".into()));
        }

        #[derive(Deserialize)]
        struct LabelsResponse {
            labels: Vec<LabelItem>,
        }

        #[derive(Deserialize)]
        struct LabelItem {
            id: String,
            name: String,
            #[serde(rename = "type")]
            label_type: Option<String>,
        }

        let result: LabelsResponse = response
            .json()
            .await
            .map_err(|e| DrivenError::Parse(e.to_string()))?;

        Ok(result
            .labels
            .into_iter()
            .map(|l| GmailLabel {
                id: l.id,
                name: l.name,
                label_type: l.label_type.unwrap_or_else(|| "user".to_string()),
            })
            .collect())
    }

    /// Setup push notifications via Pub/Sub
    pub async fn watch(&self, labels: &[&str]) -> Result<WatchResponse> {
        let token = self.access_token.as_ref()
            .ok_or_else(|| DrivenError::Config("Not authenticated".into()))?;

        let topic = self.config.pubsub_topic.as_ref()
            .ok_or_else(|| DrivenError::Config("Pub/Sub topic not configured".into()))?;

        let url = format!("{}/users/me/watch", self.base_url);

        let client = reqwest::Client::new();
        let response = client
            .post(&url)
            .header("Authorization", format!("Bearer {}", token))
            .json(&serde_json::json!({
                "topicName": topic,
                "labelIds": labels
            }))
            .send()
            .await
            .map_err(|e| DrivenError::Network(e.to_string()))?;

        if !response.status().is_success() {
            return Err(DrivenError::Api("Failed to setup watch".into()));
        }

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

    /// Parse raw message response
    fn parse_message(&self, raw: serde_json::Value) -> Result<GmailMessage> {
        let id = raw["id"].as_str().unwrap_or_default().to_string();
        let thread_id = raw["threadId"].as_str().unwrap_or_default().to_string();
        let snippet = raw["snippet"].as_str().unwrap_or_default().to_string();

        let labels: Vec<String> = raw["labelIds"]
            .as_array()
            .map(|arr| arr.iter().filter_map(|v| v.as_str().map(String::from)).collect())
            .unwrap_or_default();

        // Parse headers
        let headers = raw["payload"]["headers"].as_array();
        let mut subject = String::new();
        let mut from = String::new();
        let mut to = Vec::new();
        let mut cc = Vec::new();
        let mut date = String::new();

        if let Some(hdrs) = headers {
            for h in hdrs {
                let name = h["name"].as_str().unwrap_or_default().to_lowercase();
                let value = h["value"].as_str().unwrap_or_default();
                match name.as_str() {
                    "subject" => subject = value.to_string(),
                    "from" => from = value.to_string(),
                    "to" => to = value.split(',').map(|s| s.trim().to_string()).collect(),
                    "cc" => cc = value.split(',').map(|s| s.trim().to_string()).collect(),
                    "date" => date = value.to_string(),
                    _ => {}
                }
            }
        }

        Ok(GmailMessage {
            id,
            thread_id,
            subject,
            from,
            to,
            cc,
            date,
            snippet,
            labels,
            body_plain: None,
            body_html: None,
            attachments: Vec::new(),
        })
    }
}

/// Watch response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WatchResponse {
    /// History ID
    #[serde(rename = "historyId")]
    pub history_id: String,
    /// Expiration time
    pub expiration: String,
}

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

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