relaycast 1.0.0

Rust SDK for RelayCast - multi-agent coordination platform
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
591
592
//! Credential storage and session bootstrapping for persistent agent identity.
//!
//! Provides file-based credential caching so agents can persist their identity
//! across restarts without re-registering each time.
//!
//! # Example
//!
//! ```rust,no_run
//! use relaycast::credentials::{CredentialStore, BootstrapConfig};
//! use relaycast::RelayCast;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let store = CredentialStore::new("/tmp/relaycast.json");
//!     let config = BootstrapConfig {
//!         preferred_name: Some("my-agent".into()),
//!         ..Default::default()
//!     };
//!
//!     let session = relaycast::credentials::bootstrap_session(
//!         &store,
//!         config,
//!     ).await?;
//!
//!     println!("Agent token: {}", session.token);
//!     Ok(())
//! }
//! ```

use std::fs;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::error::{RelayError, Result};
use crate::{CreateAgentRequest, RelayCast, RelayCastOptions};

/// Cached agent credentials persisted to disk.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentCredentials {
    /// The workspace ID this agent belongs to.
    pub workspace_id: String,
    /// The agent's unique ID.
    pub agent_id: String,
    /// The workspace API key (rk_live_...).
    pub api_key: String,
    /// The agent's registered name.
    pub agent_name: Option<String>,
    /// The agent's bearer token for API calls.
    pub agent_token: Option<String>,
    /// ISO 8601 timestamp of when credentials were last updated.
    pub updated_at: String,
}

/// A successfully bootstrapped agent session.
#[derive(Debug, Clone)]
pub struct AgentSession {
    /// The persisted credentials.
    pub credentials: AgentCredentials,
    /// The active bearer token for this session.
    pub token: String,
}

/// Behavior when the preferred agent name already exists.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum NameConflictStrategy {
    /// Rotate the existing agent token and keep the same name.
    #[default]
    RotateExisting,
    /// Retry registration once with a random name suffix.
    RetryWithSuffixOnce,
    /// Return a conflict error without rotating or retrying.
    Fail,
}

/// Configuration for session bootstrapping.
#[derive(Debug, Clone, Default)]
pub struct BootstrapConfig {
    /// Preferred agent name. If not set, the server assigns one.
    pub preferred_name: Option<String>,
    /// Agent type (e.g. "agent", "human", "system"). Defaults to "agent".
    pub agent_type: Option<String>,
    /// Custom base URL. Defaults to https://api.relaycast.dev.
    pub base_url: Option<String>,
    /// Workspace API key from environment or config.
    /// If not set, a new workspace is created.
    pub api_key: Option<String>,
    /// How to resolve name conflicts when preferred_name is already taken.
    pub conflict_strategy: NameConflictStrategy,
}

/// File-based credential store with atomic writes and Unix permissions.
pub struct CredentialStore {
    path: PathBuf,
}

impl CredentialStore {
    /// Create a new credential store at the given path.
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self { path: path.into() }
    }

    /// Get the file path for this store.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Load cached credentials from disk.
    /// Returns `None` if the file doesn't exist or can't be parsed.
    pub fn load(&self) -> Option<AgentCredentials> {
        let data = fs::read(&self.path).ok()?;
        serde_json::from_slice(&data).ok()
    }

    /// Save credentials to disk atomically.
    /// Creates parent directories if needed. Sets 0600 permissions on Unix.
    pub fn save(&self, creds: &AgentCredentials) -> Result<()> {
        if let Some(parent) = self.path.parent() {
            fs::create_dir_all(parent).map_err(|e| {
                RelayError::InvalidResponse(format!("failed to create credential directory: {e}"))
            })?;
        }

        let data = serde_json::to_vec_pretty(creds)?;
        fs::write(&self.path, &data).map_err(|e| {
            RelayError::InvalidResponse(format!("failed to write credentials: {e}"))
        })?;

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let perms = std::fs::Permissions::from_mode(0o600);
            let _ = fs::set_permissions(&self.path, perms);
        }

        Ok(())
    }
}

fn now_iso8601() -> String {
    // Simple UTC timestamp without chrono dependency.
    // Uses SystemTime which is always available.
    let duration = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default();
    let secs = duration.as_secs();
    // Format as simplified ISO 8601
    let days_since_epoch = secs / 86400;
    let time_of_day = secs % 86400;
    let hours = time_of_day / 3600;
    let minutes = (time_of_day % 3600) / 60;
    let seconds = time_of_day % 60;

    // Approximate date calculation (good enough for a timestamp)
    let mut year = 1970i64;
    let mut remaining_days = days_since_epoch as i64;
    loop {
        let days_in_year = if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) {
            366
        } else {
            365
        };
        if remaining_days < days_in_year {
            break;
        }
        remaining_days -= days_in_year;
        year += 1;
    }
    let is_leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
    let days_in_months: [i64; 12] = [
        31,
        if is_leap { 29 } else { 28 },
        31,
        30,
        31,
        30,
        31,
        31,
        30,
        31,
        30,
        31,
    ];
    let mut month = 1u32;
    for &dim in &days_in_months {
        if remaining_days < dim {
            break;
        }
        remaining_days -= dim;
        month += 1;
    }
    let day = remaining_days + 1;

    format!("{year:04}-{month:02}-{day:02}T{hours:02}:{minutes:02}:{seconds:02}Z")
}

/// Bootstrap an agent session using cached credentials or fresh registration.
///
/// Tries these strategies in order:
/// 1. If cached credentials exist with matching name → rotate token
/// 2. If an API key is available (config or cache) → register a new agent
/// 3. If no API key → create a new workspace, then register
///
/// Saves credentials to the store on success.
pub async fn bootstrap_session(
    store: &CredentialStore,
    config: BootstrapConfig,
) -> Result<AgentSession> {
    let cached = store.load();
    let base_url = config.base_url.as_deref();

    // Strategy 1: rotate existing token if we have matching cached creds
    if let Some(ref creds) = cached {
        if let Some(ref cached_name) = creds.agent_name {
            let preferred = config.preferred_name.as_deref().unwrap_or(cached_name);
            if cached_name == preferred {
                let relay = build_relay(&creds.api_key, base_url)?;
                match relay.rotate_agent_token(cached_name).await {
                    Ok(result) => {
                        let session = finish_session(
                            store,
                            creds.workspace_id.clone(),
                            creds.agent_id.clone(),
                            creds.api_key.clone(),
                            Some(cached_name.clone()),
                            result.token,
                        )?;
                        return Ok(session);
                    }
                    Err(e) if e.is_not_found() || e.is_auth_rejection() => {
                        // Fall through to registration
                    }
                    Err(e) if e.is_rate_limited() => {
                        // If we have a cached token, use it
                        if let Some(ref token) = creds.agent_token {
                            return Ok(AgentSession {
                                credentials: creds.clone(),
                                token: token.clone(),
                            });
                        }
                        return Err(e);
                    }
                    Err(e) => return Err(e),
                }
            }
        }
    }

    // Determine API key: config > cached > create workspace
    let (api_key, workspace_id) = if let Some(ref key) = config.api_key {
        (key.clone(), cached.as_ref().map(|c| c.workspace_id.clone()))
    } else if let Some(ref creds) = cached {
        if creds.api_key.starts_with("rk_") {
            (creds.api_key.clone(), Some(creds.workspace_id.clone()))
        } else {
            create_fresh_workspace(base_url).await?
        }
    } else {
        create_fresh_workspace(base_url).await?
    };

    // Strategy 2: register agent with the API key
    let relay = build_relay(&api_key, base_url)?;
    let cached_name = cached.as_ref().and_then(|c| c.agent_name.clone());
    let cached_agent_id = cached
        .as_ref()
        .map(|c| c.agent_id.clone())
        .unwrap_or_default();

    let name = config
        .preferred_name
        .or(cached_name)
        .unwrap_or_else(|| format!("agent-{}", &uuid_v4_short()));

    let agent_type = config.agent_type.unwrap_or_else(|| "agent".into());
    let conflict_strategy = config.conflict_strategy;

    match relay
        .register_agent(CreateAgentRequest {
            name: name.clone(),
            agent_type: Some(agent_type.clone()),
            persona: None,
            metadata: None,
        })
        .await
    {
        Ok(result) => {
            let ws_id = workspace_id.unwrap_or_default();
            finish_session(
                store,
                ws_id,
                result.id,
                api_key,
                Some(result.name),
                result.token,
            )
        }
        Err(e) if e.is_conflict() => match conflict_strategy {
            NameConflictStrategy::RotateExisting => {
                let rotate_result = relay.rotate_agent_token(&name).await?;
                let ws_id = workspace_id.unwrap_or_default();
                finish_session(
                    store,
                    ws_id,
                    cached_agent_id,
                    api_key,
                    Some(name),
                    rotate_result.token,
                )
            }
            NameConflictStrategy::RetryWithSuffixOnce => {
                let suffix_name = format!("{}-{}", name, uuid_v4_short());
                let retried = relay
                    .register_agent(CreateAgentRequest {
                        name: suffix_name.clone(),
                        agent_type: Some(agent_type),
                        persona: None,
                        metadata: None,
                    })
                    .await;

                match retried {
                    Ok(result) => {
                        let ws_id = workspace_id.unwrap_or_default();
                        finish_session(
                            store,
                            ws_id,
                            result.id,
                            api_key,
                            Some(result.name),
                            result.token,
                        )
                    }
                    Err(err) if err.is_conflict() => Err(RelayError::api(
                        "agent_already_exists",
                        format!("agent name '{}' already exists after retry", suffix_name),
                        409,
                    )),
                    Err(err) => Err(err),
                }
            }
            NameConflictStrategy::Fail => Err(RelayError::api(
                "agent_already_exists",
                format!("agent name '{}' already exists", name),
                409,
            )),
        },
        Err(e) if e.is_auth_rejection() => {
            // Cached key is stale — create fresh workspace
            let (fresh_key, fresh_ws_id) = create_fresh_workspace(base_url).await?;
            let fresh_relay = build_relay(&fresh_key, base_url)?;
            let result = fresh_relay
                .register_agent(CreateAgentRequest {
                    name: name.clone(),
                    agent_type: Some("agent".into()),
                    persona: None,
                    metadata: None,
                })
                .await?;
            let ws_id = fresh_ws_id.unwrap_or_default();
            finish_session(
                store,
                ws_id,
                result.id,
                fresh_key,
                Some(result.name),
                result.token,
            )
        }
        Err(e) => Err(e),
    }
}

async fn create_fresh_workspace(base_url: Option<&str>) -> Result<(String, Option<String>)> {
    let ws_name = format!("relay-{}", &uuid_v4_short());
    let result = RelayCast::create_workspace(&ws_name, base_url).await?;
    Ok((result.api_key, Some(result.workspace_id)))
}

fn build_relay(api_key: &str, base_url: Option<&str>) -> Result<RelayCast> {
    let mut opts = RelayCastOptions::new(api_key);
    if let Some(url) = base_url {
        opts = opts.with_base_url(url);
    }
    RelayCast::new(opts)
}

fn finish_session(
    store: &CredentialStore,
    workspace_id: String,
    agent_id: String,
    api_key: String,
    agent_name: Option<String>,
    token: String,
) -> Result<AgentSession> {
    let creds = AgentCredentials {
        workspace_id,
        agent_id,
        api_key,
        agent_name,
        agent_token: Some(token.clone()),
        updated_at: now_iso8601(),
    };
    store.save(&creds)?;
    Ok(AgentSession {
        credentials: creds,
        token,
    })
}

/// Generate a short random hex string (8 chars) for unique naming.
fn uuid_v4_short() -> String {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};
    let mut hasher = DefaultHasher::new();
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos()
        .hash(&mut hasher);
    std::thread::current().id().hash(&mut hasher);
    format!("{:016x}", hasher.finish())[..8].to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use wiremock::matchers::{body_string_contains, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    fn ok(data: serde_json::Value) -> ResponseTemplate {
        ResponseTemplate::new(200).set_body_json(json!({ "ok": true, "data": data }))
    }

    fn api_error(status: u16, code: &str, message: &str) -> ResponseTemplate {
        ResponseTemplate::new(status).set_body_json(json!({
            "ok": false,
            "error": {
                "code": code,
                "message": message
            }
        }))
    }

    #[test]
    fn credential_store_round_trip() {
        let dir = tempfile::tempdir().unwrap();
        let store = CredentialStore::new(dir.path().join("creds.json"));

        let creds = AgentCredentials {
            workspace_id: "ws_123".into(),
            agent_id: "a_456".into(),
            api_key: "rk_live_test".into(),
            agent_name: Some("test-agent".into()),
            agent_token: Some("at_live_token".into()),
            updated_at: "2025-01-01T00:00:00Z".into(),
        };

        store.save(&creds).unwrap();
        let loaded = store.load().unwrap();

        assert_eq!(loaded.workspace_id, "ws_123");
        assert_eq!(loaded.agent_id, "a_456");
        assert_eq!(loaded.api_key, "rk_live_test");
        assert_eq!(loaded.agent_name.as_deref(), Some("test-agent"));
        assert_eq!(loaded.agent_token.as_deref(), Some("at_live_token"));
    }

    #[test]
    fn load_missing_file_returns_none() {
        let store = CredentialStore::new("/tmp/nonexistent-relaycast-test.json");
        assert!(store.load().is_none());
    }

    #[test]
    fn load_corrupt_file_returns_none() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("bad.json");
        fs::write(&path, "not-json").unwrap();

        let store = CredentialStore::new(path);
        assert!(store.load().is_none());
    }

    #[test]
    fn now_iso8601_produces_valid_format() {
        let ts = now_iso8601();
        assert!(ts.contains('T'));
        assert!(ts.ends_with('Z'));
        assert_eq!(ts.len(), 20); // "2025-01-01T00:00:00Z"
    }

    #[cfg(unix)]
    #[test]
    fn saved_file_has_restricted_permissions() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let store = CredentialStore::new(dir.path().join("creds.json"));

        let creds = AgentCredentials {
            workspace_id: "ws".into(),
            agent_id: "a".into(),
            api_key: "rk".into(),
            agent_name: None,
            agent_token: None,
            updated_at: "2025-01-01T00:00:00Z".into(),
        };
        store.save(&creds).unwrap();

        let perms = fs::metadata(store.path()).unwrap().permissions();
        assert_eq!(perms.mode() & 0o777, 0o600);
    }

    #[tokio::test]
    async fn conflict_strategy_fail_returns_conflict_error() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/agents"))
            .and(body_string_contains("\"name\":\"lead\""))
            .respond_with(api_error(409, "agent_already_exists", "name taken"))
            .expect(1)
            .mount(&server)
            .await;

        let dir = tempfile::tempdir().unwrap();
        let store = CredentialStore::new(dir.path().join("creds.json"));
        let result = bootstrap_session(
            &store,
            BootstrapConfig {
                preferred_name: Some("lead".to_string()),
                api_key: Some("rk_live_test".to_string()),
                base_url: Some(server.uri()),
                conflict_strategy: NameConflictStrategy::Fail,
                ..Default::default()
            },
        )
        .await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.is_conflict());
    }

    #[tokio::test]
    async fn conflict_strategy_retry_with_suffix_registers_new_name() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/agents"))
            .and(body_string_contains("\"name\":\"lead\""))
            .respond_with(api_error(409, "agent_already_exists", "name taken"))
            .expect(1)
            .mount(&server)
            .await;

        Mock::given(method("POST"))
            .and(path("/v1/agents"))
            .and(body_string_contains("\"name\":\"lead-"))
            .respond_with(ok(json!({
                "id": "a_retry",
                "name": "lead-suffixed",
                "token": "at_live_retry",
                "status": "online",
                "created_at": "2026-01-01T00:00:00.000Z"
            })))
            .expect(1)
            .mount(&server)
            .await;

        let dir = tempfile::tempdir().unwrap();
        let store = CredentialStore::new(dir.path().join("creds.json"));
        let session = bootstrap_session(
            &store,
            BootstrapConfig {
                preferred_name: Some("lead".to_string()),
                api_key: Some("rk_live_test".to_string()),
                base_url: Some(server.uri()),
                conflict_strategy: NameConflictStrategy::RetryWithSuffixOnce,
                ..Default::default()
            },
        )
        .await
        .expect("bootstrap with suffix retry should succeed");

        assert_eq!(session.token, "at_live_retry");
        assert_eq!(
            session.credentials.agent_name.as_deref(),
            Some("lead-suffixed")
        );
    }
}