tinytown 0.10.0

A simple, fast multi-agent orchestration system using Redis for message passing
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
/*
 * Copyright (c) 2024-Present, Jeremy Plichta
 * Licensed under the MIT License
 */

//! Global configuration stored in ~/.tt/config.toml

use std::path::PathBuf;

use serde::{Deserialize, Serialize};

use crate::error::{Error, Result};

/// Global config file name
pub const GLOBAL_CONFIG_FILE: &str = "config.toml";

/// Global config directory
pub const GLOBAL_CONFIG_DIR: &str = ".tt";

/// Default Redis port (non-standard to avoid conflicts)
pub const DEFAULT_REDIS_PORT: u16 = 16379;

/// Global configuration that applies across all towns.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GlobalConfig {
    /// Default CLI to use when spawning agents (e.g., "claude", "auggie")
    #[serde(default = "default_cli")]
    pub default_cli: String,

    /// CLI to use for the interactive conductor (defaults to default_cli)
    #[serde(default)]
    pub conductor_cli: Option<String>,

    /// Custom CLI definitions (name -> command)
    #[serde(default)]
    pub agent_clis: std::collections::HashMap<String, String>,

    /// Central Redis configuration
    #[serde(default)]
    pub redis: GlobalRedisConfig,
}

/// Global Redis configuration for the central Redis instance.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GlobalRedisConfig {
    /// Redis host (default: 127.0.0.1)
    #[serde(default = "default_host")]
    pub host: String,

    /// Redis port (default: 16379 - non-standard to avoid conflicts)
    #[serde(default = "default_port")]
    pub port: u16,

    /// Redis password (auto-generated on first use if not set)
    #[serde(default)]
    pub password: Option<String>,

    /// Whether towns should use the central Redis by default
    #[serde(default = "default_true")]
    pub use_central: bool,
}

impl Default for GlobalRedisConfig {
    fn default() -> Self {
        Self {
            host: default_host(),
            port: default_port(),
            password: None,
            use_central: true,
        }
    }
}

fn default_cli() -> String {
    "claude".to_string()
}

fn default_host() -> String {
    "127.0.0.1".to_string()
}

fn default_port() -> u16 {
    DEFAULT_REDIS_PORT
}

fn default_true() -> bool {
    true
}

pub(crate) fn normalize_builtin_cli_reference(value: &str) -> Option<&'static str> {
    match value.trim() {
        "claude --print --dangerously-skip-permissions" => Some("claude"),
        "auggie --print" => Some("auggie"),
        "codex --dangerously-bypass-approvals-and-sandbox" => Some("codex"),
        "codex exec --dangerously-bypass-approvals-and-sandbox" => Some("codex"),
        "codex exec --dangerously-bypass-approvals-and-sandbox -m gpt-5.4-mini -c model_reasoning_effort=\"medium\"" => {
            Some("codex-mini")
        }
        "aider --yes --no-auto-commits --message" => Some("aider"),
        _ => None,
    }
}

fn normalize_cli_reference(value: &mut String) -> bool {
    let Some(normalized) = normalize_builtin_cli_reference(value) else {
        return false;
    };

    if value == normalized {
        return false;
    }

    *value = normalized.to_string();
    true
}

fn normalize_optional_cli_reference(value: &mut Option<String>) -> bool {
    let Some(current) = value.as_deref() else {
        return false;
    };
    let Some(normalized) = normalize_builtin_cli_reference(current) else {
        return false;
    };

    if current == normalized {
        return false;
    }

    *value = Some(normalized.to_string());
    true
}

impl Default for GlobalConfig {
    fn default() -> Self {
        Self {
            default_cli: default_cli(),
            conductor_cli: None,
            agent_clis: std::collections::HashMap::new(),
            redis: GlobalRedisConfig::default(),
        }
    }
}

impl GlobalConfig {
    /// Get the global config directory path (~/.tt)
    pub fn config_dir() -> Result<PathBuf> {
        dirs::home_dir()
            .map(|h| h.join(GLOBAL_CONFIG_DIR))
            .ok_or_else(|| {
                Error::Io(std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "Could not find home directory",
                ))
            })
    }

    /// Get the global config file path (~/.tt/config.toml)
    pub fn config_path() -> Result<PathBuf> {
        Ok(Self::config_dir()?.join(GLOBAL_CONFIG_FILE))
    }

    /// Load global config, creating default if it doesn't exist.
    pub fn load() -> Result<Self> {
        let config_path = Self::config_path()?;

        if !config_path.exists() {
            // Return default config if file doesn't exist
            return Ok(Self::default());
        }

        let content = std::fs::read_to_string(&config_path)?;
        let mut config: GlobalConfig = toml::from_str(&content)
            .map_err(|e| Error::Io(std::io::Error::other(format!("Invalid config.toml: {}", e))))?;
        config.normalize_cli_references();

        Ok(config)
    }

    /// Save global config to ~/.tt/config.toml
    pub fn save(&self) -> Result<()> {
        let config_dir = Self::config_dir()?;
        let config_path = Self::config_path()?;

        // Create ~/.tt if it doesn't exist
        std::fs::create_dir_all(&config_dir)?;

        let content = toml::to_string_pretty(self).map_err(|e| {
            Error::Io(std::io::Error::other(format!(
                "Failed to serialize config: {}",
                e
            )))
        })?;

        std::fs::write(&config_path, content)?;
        Ok(())
    }

    /// Get the path to the central Redis PID file (~/.tt/redis.pid)
    pub fn redis_pid_path() -> Result<PathBuf> {
        Ok(Self::config_dir()?.join("redis.pid"))
    }

    /// Check if the central Redis is running by checking the PID file.
    pub fn is_central_redis_running() -> bool {
        let pid_path = match Self::redis_pid_path() {
            Ok(p) => p,
            Err(_) => return false,
        };

        if !pid_path.exists() {
            return false;
        }

        // Read PID and check if process is running
        if let Ok(pid_str) = std::fs::read_to_string(&pid_path)
            && let Ok(pid) = pid_str.trim().parse::<i32>()
        {
            // Check if process is running (kill -0 doesn't send signal, just checks)
            unsafe {
                return libc::kill(pid, 0) == 0;
            }
        }

        false
    }

    /// Load and ensure global config exists with password set.
    /// This will create the config file if it doesn't exist and generate a password.
    pub fn load_or_init() -> Result<Self> {
        let config_path = Self::config_path()?;

        let mut config = if config_path.exists() {
            let content = std::fs::read_to_string(&config_path)?;
            toml::from_str(&content).map_err(|e| {
                Error::Io(std::io::Error::other(format!("Invalid config.toml: {}", e)))
            })?
        } else {
            Self::default()
        };

        let mut changed = config.normalize_cli_references();

        // Ensure password is set
        if config.ensure_redis_password() {
            // Password was generated, save config
            changed = true;
        }

        if changed {
            config.save()?;
        }

        Ok(config)
    }

    fn normalize_cli_references(&mut self) -> bool {
        let mut changed = normalize_cli_reference(&mut self.default_cli);
        changed |= normalize_optional_cli_reference(&mut self.conductor_cli);
        changed
    }

    /// Set a config value by key
    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
        match key {
            "default_cli" => {
                self.default_cli = value.to_string();
                Ok(())
            }
            "conductor_cli" => {
                self.conductor_cli = Some(value.to_string());
                Ok(())
            }
            "redis.host" => {
                self.redis.host = value.to_string();
                Ok(())
            }
            "redis.port" => {
                self.redis.port = value.parse().map_err(|_| {
                    Error::Io(std::io::Error::new(
                        std::io::ErrorKind::InvalidInput,
                        "Invalid port number",
                    ))
                })?;
                Ok(())
            }
            "redis.password" => {
                self.redis.password = Some(value.to_string());
                Ok(())
            }
            "redis.use_central" => {
                self.redis.use_central = value.parse().map_err(|_| {
                    Error::Io(std::io::Error::new(
                        std::io::ErrorKind::InvalidInput,
                        "Invalid boolean value",
                    ))
                })?;
                Ok(())
            }
            _ if key.starts_with("agent_clis.") => {
                let cli_name = key.strip_prefix("agent_clis.").unwrap();
                self.agent_clis
                    .insert(cli_name.to_string(), value.to_string());
                Ok(())
            }
            _ => Err(Error::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                format!("Unknown config key: {}", key),
            ))),
        }
    }

    /// Get a config value by key
    pub fn get(&self, key: &str) -> Option<String> {
        match key {
            "default_cli" => Some(self.default_cli.clone()),
            "conductor_cli" => Some(
                self.conductor_cli
                    .clone()
                    .unwrap_or_else(|| self.default_cli.clone()),
            ),
            "redis.host" => Some(self.redis.host.clone()),
            "redis.port" => Some(self.redis.port.to_string()),
            "redis.password" => self.redis.password.clone(),
            "redis.use_central" => Some(self.redis.use_central.to_string()),
            _ if key.starts_with("agent_clis.") => {
                let cli_name = key.strip_prefix("agent_clis.").unwrap();
                self.agent_clis.get(cli_name).cloned()
            }
            _ => None,
        }
    }

    /// Generate a cryptographically random password for Redis.
    #[must_use]
    pub fn generate_password() -> String {
        use std::collections::hash_map::RandomState;
        use std::hash::{BuildHasher, Hasher};
        use std::time::{SystemTime, UNIX_EPOCH};

        // Use multiple sources of entropy for better randomness
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();
        let pid = std::process::id();

        // Use RandomState which incorporates OS randomness
        let random_state = RandomState::new();
        let mut hasher = random_state.build_hasher();
        hasher.write_u128(timestamp);
        hasher.write_u32(pid);
        let hash1 = hasher.finish();

        // Generate a second hash with different seed and additional entropy
        let random_state2 = RandomState::new();
        let mut hasher2 = random_state2.build_hasher();
        hasher2.write_u64(hash1);
        // Use address of local variable for stack address entropy (varies each call)
        let stack_var: u64 = 0;
        hasher2.write_usize(&stack_var as *const _ as usize);
        let hash2 = hasher2.finish();

        // Combine hashes for a longer, more random password
        format!("tt_{:016x}{:016x}", hash1, hash2)
    }

    /// Ensure the Redis password is set, generating one if needed.
    /// Returns true if a new password was generated.
    pub fn ensure_redis_password(&mut self) -> bool {
        if self.redis.password.is_none() {
            self.redis.password = Some(Self::generate_password());
            true
        } else {
            false
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{GlobalConfig, GlobalRedisConfig, normalize_builtin_cli_reference};

    #[test]
    fn normalizes_legacy_builtin_cli_commands() {
        assert_eq!(
            normalize_builtin_cli_reference("codex --dangerously-bypass-approvals-and-sandbox"),
            Some("codex")
        );
        assert_eq!(
            normalize_builtin_cli_reference(
                "codex exec --dangerously-bypass-approvals-and-sandbox"
            ),
            Some("codex")
        );
        assert_eq!(
            normalize_builtin_cli_reference(
                "codex exec --dangerously-bypass-approvals-and-sandbox -m gpt-5.4-mini -c model_reasoning_effort=\"medium\""
            ),
            Some("codex-mini")
        );
    }

    #[test]
    fn global_config_normalizes_legacy_cli_references() {
        let mut config = GlobalConfig {
            default_cli: "codex --dangerously-bypass-approvals-and-sandbox".to_string(),
            conductor_cli: Some(
                "codex exec --dangerously-bypass-approvals-and-sandbox".to_string(),
            ),
            agent_clis: std::collections::HashMap::new(),
            redis: GlobalRedisConfig::default(),
        };

        assert!(config.normalize_cli_references());
        assert_eq!(config.default_cli, "codex");
        assert_eq!(config.conductor_cli.as_deref(), Some("codex"));
    }
}