molten-herald 0.1.0

Automated viral tweet generation and scheduling for developer releases 📢
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
//! Configuration management for herald

use crate::error::{HeraldError, Result};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// Main configuration for herald
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    /// Twitter/X API credentials
    #[serde(default)]
    pub twitter: TwitterConfig,

    /// LLM configuration for tweet generation
    #[serde(default)]
    pub llm: LlmConfig,

    /// Default settings for tweet generation
    #[serde(default)]
    pub defaults: TweetDefaults,

    /// Scheduling configuration
    #[serde(default)]
    pub schedule: ScheduleConfig,

    /// Projects to monitor
    #[serde(default)]
    pub projects: Vec<ProjectConfig>,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            twitter: TwitterConfig::default(),
            llm: LlmConfig::default(),
            defaults: TweetDefaults::default(),
            schedule: ScheduleConfig::default(),
            projects: Vec::new(),
        }
    }
}

/// Twitter/X API configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TwitterConfig {
    /// API Key (Consumer Key)
    #[serde(default)]
    pub api_key: String,

    /// API Secret (Consumer Secret)
    #[serde(default)]
    pub api_secret: String,

    /// Access Token
    #[serde(default)]
    pub access_token: String,

    /// Access Token Secret
    #[serde(default)]
    pub access_token_secret: String,

    /// Bearer token for v2 API
    #[serde(default)]
    pub bearer_token: String,
}

impl TwitterConfig {
    /// Check if credentials are configured
    pub fn is_configured(&self) -> bool {
        !self.api_key.is_empty()
            && !self.api_secret.is_empty()
            && !self.access_token.is_empty()
            && !self.access_token_secret.is_empty()
    }

    /// Load from environment variables
    pub fn from_env() -> Self {
        Self {
            api_key: std::env::var("TWITTER_API_KEY").unwrap_or_default(),
            api_secret: std::env::var("TWITTER_API_SECRET").unwrap_or_default(),
            access_token: std::env::var("TWITTER_ACCESS_TOKEN").unwrap_or_default(),
            access_token_secret: std::env::var("TWITTER_ACCESS_TOKEN_SECRET").unwrap_or_default(),
            bearer_token: std::env::var("TWITTER_BEARER_TOKEN").unwrap_or_default(),
        }
    }
}

/// LLM configuration for generating tweets
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LlmConfig {
    /// LLM provider (openai, anthropic, ollama)
    #[serde(default = "default_provider")]
    pub provider: String,

    /// API key for the LLM provider
    #[serde(default)]
    pub api_key: String,

    /// Model to use
    #[serde(default = "default_model")]
    pub model: String,

    /// API base URL (for self-hosted or alternative endpoints)
    #[serde(default)]
    pub base_url: Option<String>,

    /// Temperature for generation (0.0 - 1.0)
    #[serde(default = "default_temperature")]
    pub temperature: f32,

    /// Max tokens to generate
    #[serde(default = "default_max_tokens")]
    pub max_tokens: usize,
}

fn default_provider() -> String {
    "anthropic".to_string()
}

fn default_model() -> String {
    "claude-sonnet-4-20250514".to_string()
}

fn default_temperature() -> f32 {
    0.8
}

fn default_max_tokens() -> usize {
    500
}

impl Default for LlmConfig {
    fn default() -> Self {
        Self {
            provider: default_provider(),
            api_key: std::env::var("ANTHROPIC_API_KEY")
                .or_else(|_| std::env::var("OPENAI_API_KEY"))
                .unwrap_or_default(),
            model: default_model(),
            base_url: None,
            temperature: default_temperature(),
            max_tokens: default_max_tokens(),
        }
    }
}

/// Default settings for generated tweets
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TweetDefaults {
    /// Include emojis
    #[serde(default = "default_true")]
    pub emojis: bool,

    /// Include hashtags
    #[serde(default)]
    pub hashtags: bool,

    /// Tone (casual, professional, hype, technical)
    #[serde(default = "default_tone")]
    pub tone: String,

    /// Maximum tweet length
    #[serde(default = "default_max_length")]
    pub max_length: usize,

    /// Always include link
    #[serde(default = "default_true")]
    pub include_link: bool,

    /// Default author handle
    #[serde(default)]
    pub author_handle: Option<String>,
}

fn default_true() -> bool {
    true
}

fn default_tone() -> String {
    "casual".to_string()
}

fn default_max_length() -> usize {
    280
}

impl Default for TweetDefaults {
    fn default() -> Self {
        Self {
            emojis: true,
            hashtags: false,
            tone: default_tone(),
            max_length: default_max_length(),
            include_link: true,
            author_handle: None,
        }
    }
}

/// Scheduling configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScheduleConfig {
    /// Minimum hours between tweets
    #[serde(default = "default_min_hours")]
    pub min_hours_between: u32,

    /// Preferred posting times (24h format, e.g., ["09:00", "14:00", "18:00"])
    #[serde(default = "default_posting_times")]
    pub preferred_times: Vec<String>,

    /// Timezone for scheduling
    #[serde(default = "default_timezone")]
    pub timezone: String,

    /// Maximum tweets per day
    #[serde(default = "default_max_per_day")]
    pub max_per_day: u32,

    /// Queue file path
    #[serde(default)]
    pub queue_file: Option<PathBuf>,
}

fn default_min_hours() -> u32 {
    4
}

fn default_posting_times() -> Vec<String> {
    vec![
        "09:00".to_string(),
        "12:00".to_string(),
        "15:00".to_string(),
        "18:00".to_string(),
    ]
}

fn default_timezone() -> String {
    "America/New_York".to_string()
}

fn default_max_per_day() -> u32 {
    5
}

impl Default for ScheduleConfig {
    fn default() -> Self {
        Self {
            min_hours_between: default_min_hours(),
            preferred_times: default_posting_times(),
            timezone: default_timezone(),
            max_per_day: default_max_per_day(),
            queue_file: None,
        }
    }
}

/// Project configuration for monitoring
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectConfig {
    /// Project name
    pub name: String,

    /// Local path to the repository
    #[serde(default)]
    pub path: Option<PathBuf>,

    /// GitHub repository (owner/repo)
    #[serde(default)]
    pub github: Option<String>,

    /// Crates.io package name
    #[serde(default)]
    pub crates_io: Option<String>,

    /// NPM package name
    #[serde(default)]
    pub npm: Option<String>,

    /// Custom description for context
    #[serde(default)]
    pub description: Option<String>,

    /// Events to announce
    #[serde(default = "default_events")]
    pub events: Vec<EventType>,
}

fn default_events() -> Vec<EventType> {
    vec![EventType::Release, EventType::MajorFeature]
}

/// Types of events to announce
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum EventType {
    /// New release/version tag
    Release,
    /// New commits to main
    Commit,
    /// Merged pull request
    PullRequest,
    /// Major feature (detected from commit messages)
    MajorFeature,
    /// Bug fix
    BugFix,
    /// Documentation update
    Docs,
    /// Breaking change
    Breaking,
    /// Security fix
    Security,
    /// Performance improvement
    Performance,
    /// Custom event
    Custom(String),
}

impl Config {
    /// Load configuration from default location
    pub fn load() -> Result<Self> {
        let config_path = Self::default_path()?;
        if config_path.exists() {
            Self::load_from(&config_path)
        } else {
            Ok(Self::default())
        }
    }

    /// Load configuration from a specific path
    pub fn load_from(path: &PathBuf) -> Result<Self> {
        let content = std::fs::read_to_string(path)?;
        toml::from_str(&content).map_err(|e| HeraldError::Config(e.to_string()))
    }

    /// Save configuration to default location
    pub fn save(&self) -> Result<()> {
        let config_path = Self::default_path()?;
        self.save_to(&config_path)
    }

    /// Save configuration to a specific path
    pub fn save_to(&self, path: &PathBuf) -> Result<()> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let content = toml::to_string_pretty(self).map_err(|e| HeraldError::Config(e.to_string()))?;
        std::fs::write(path, content)?;
        Ok(())
    }

    /// Get default configuration path
    pub fn default_path() -> Result<PathBuf> {
        let proj_dirs = directories::ProjectDirs::from("io", "moltenlabs", "herald")
            .ok_or_else(|| HeraldError::Config("Could not determine config directory".to_string()))?;
        Ok(proj_dirs.config_dir().join("config.toml"))
    }

    /// Create example configuration
    pub fn example() -> Self {
        Self {
            twitter: TwitterConfig::default(),
            llm: LlmConfig::default(),
            defaults: TweetDefaults {
                emojis: true,
                hashtags: false,
                tone: "casual".to_string(),
                max_length: 280,
                include_link: true,
                author_handle: Some("@mikifranz".to_string()),
            },
            schedule: ScheduleConfig::default(),
            projects: vec![
                ProjectConfig {
                    name: "warhorn".to_string(),
                    path: None,
                    github: Some("moltenlabs/warhorn".to_string()),
                    crates_io: Some("warhorn".to_string()),
                    npm: None,
                    description: Some("Protocol types for AI agent communication".to_string()),
                    events: vec![EventType::Release, EventType::MajorFeature],
                },
            ],
        }
    }
}

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

    #[test]
    fn test_default_config() {
        let config = Config::default();
        assert!(config.defaults.emojis);
        assert!(!config.defaults.hashtags);
        assert_eq!(config.defaults.max_length, 280);
    }

    #[test]
    fn test_twitter_config_from_env() {
        // Just test the structure, not actual env vars
        let config = TwitterConfig::default();
        assert!(!config.is_configured());
    }

    #[test]
    fn test_config_serialization() {
        let config = Config::example();
        let toml_str = toml::to_string_pretty(&config).unwrap();
        let parsed: Config = toml::from_str(&toml_str).unwrap();
        assert_eq!(parsed.projects.len(), 1);
        assert_eq!(parsed.projects[0].name, "warhorn");
    }

    #[test]
    fn test_event_types() {
        let events = vec![
            EventType::Release,
            EventType::Commit,
            EventType::Custom("launch".to_string()),
        ];
        let json = serde_json::to_string(&events).unwrap();
        let parsed: Vec<EventType> = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.len(), 3);
    }
}