ai-agent 0.13.4

Idiomatic agent sdk inspired by the claude code source leak
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//! Team Memory Sync - ported from ~/claudecode/openclaudecode/src/services/teamMemorySync/
//!
//! Syncs team memory files between the local filesystem and the server API.
//! Team memory is scoped per-repo (identified by git remote hash) and shared
//! across all authenticated org members.

use crate::constants::env::system;
use crate::AgentError;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;

/// Team memory content - flat key-value storage
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct TeamMemoryContent {
    /// Keys are file paths relative to team memory directory
    pub entries: HashMap<String, String>,
    /// Per-key SHA-256 checksums (sha256:<hex>)
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub entry_checksums: HashMap<String, String>,
}

/// Full response from GET /api/claude_code/team_memory
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TeamMemoryData {
    pub organization_id: String,
    pub repo: String,
    pub version: u32,
    pub last_modified: String,
    pub checksum: String,
    pub content: TeamMemoryContent,
}

/// Structured 413 error body for too many entries
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TeamMemoryTooManyEntries {
    pub error: TeamMemoryTooManyEntriesError,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TeamMemoryTooManyEntriesError {
    pub details: TeamMemoryTooManyEntriesDetails,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TeamMemoryTooManyEntriesDetails {
    #[serde(rename = "error_code")]
    pub error_code: String,
    #[serde(rename = "max_entries")]
    pub max_entries: u32,
    #[serde(rename = "received_entries")]
    pub received_entries: u32,
}

/// A file skipped during push due to detected secret
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SkippedSecretFile {
    /// Path relative to team memory directory
    pub path: String,
    /// Gitleaks rule ID (e.g., "github-pat", "aws-access-token")
    pub rule_id: String,
    /// Human-readable label derived from rule ID
    pub label: String,
}

/// Result from fetching team memory
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TeamMemorySyncFetchResult {
    pub success: bool,
    pub data: Option<TeamMemoryData>,
    /// true if 404 (no data exists)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub is_empty: Option<bool>,
    /// true if 304 (ETag matched, no changes)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub not_modified: Option<bool>,
    /// ETag from response header
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub checksum: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub skip_retry: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error_type: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub http_status: Option<u16>,
}

/// Lightweight metadata-only probe result (GET ?view=hashes)
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TeamMemoryHashesResult {
    pub success: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub checksum: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub entry_checksums: Option<HashMap<String, String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error_type: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub http_status: Option<u16>,
}

/// Result from uploading team memory with conflict info
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TeamMemorySyncPushResult {
    pub success: bool,
    pub files_uploaded: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub checksum: Option<String>,
    /// true if 412 Precondition Failed
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub conflict: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Files skipped due to detected secrets
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub skipped_secrets: Vec<SkippedSecretFile>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error_type: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub http_status: Option<u16>,
}

/// Result from uploading team memory
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TeamMemorySyncUploadResult {
    pub success: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub checksum: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_modified: Option<String>,
    /// true if 412 Precondition Failed
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub conflict: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Structured error_code from parsed 413 body
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub server_error_code: Option<String>,
    /// Server-enforced max_entries
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub server_max_entries: Option<u32>,
    /// How many entries the rejected push would have produced
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub server_received_entries: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error_type: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub http_status: Option<u16>,
}

// ─── Sync State ─────────────────────────────────────────────────

/// Mutable state for team memory sync service
#[derive(Debug, Clone)]
pub struct SyncState {
    /// Last known server checksum (ETag) for conditional requests
    pub last_known_checksum: Option<String>,
    /// Per-key content hash (sha256:<hex>) of what we believe server holds
    pub server_checksums: HashMap<String, String>,
    /// Server-enforced max_entries cap, learned from structured 413
    pub server_max_entries: Option<u32>,
}

impl SyncState {
    pub fn new() -> Self {
        Self {
            last_known_checksum: None,
            server_checksums: HashMap::new(),
            server_max_entries: None,
        }
    }
}

impl Default for SyncState {
    fn default() -> Self {
        Self::new()
    }
}

/// Create a new sync state
pub fn create_sync_state() -> SyncState {
    SyncState::new()
}

// ─── Hashing ───────────────────────────────────────────────────

/// Compute sha256:<hex> over UTF-8 bytes of content
pub fn hash_content(content: &str) -> String {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    let mut hasher = DefaultHasher::new();
    content.hash(&mut hasher);
    let hash = hasher.finish();

    // Use SHA256-like format for compatibility with server
    format!("sha256:{:016x}", hash)
}

// ─── Configuration ─────────────────────────────────────────────

/// Team memory sync timeout in milliseconds
pub const TEAM_MEMORY_SYNC_TIMEOUT_MS: u64 = 30_000;
/// Per-entry size cap (250KB)
pub const MAX_FILE_SIZE_BYTES: usize = 250_000;
/// Gateway body-size cap (200KB)
pub const MAX_PUT_BODY_BYTES: usize = 200_000;
/// Max retries for transient failures
pub const MAX_RETRIES: u32 = 3;
/// Max retries for conflict resolution
pub const MAX_CONFLICT_RETRIES: u32 = 2;

// ─── File Operations ───────────────────────────────────────────

/// Get the team memory directory path
pub fn get_team_memory_dir() -> PathBuf {
    let home = std::env::var(system::HOME)
        .or_else(|_| std::env::var(system::USERPROFILE))
        .unwrap_or_else(|_| "/tmp".to_string());
    PathBuf::from(home)
        .join(".open-agent-sdk")
        .join("team_memory")
}

/// Get team memory file path for a given key
pub fn get_team_memory_path(key: &str) -> PathBuf {
    // Validate key to prevent path traversal
    if key.contains("..") || key.starts_with('/') {
        return get_team_memory_dir().join("INVALID");
    }
    get_team_memory_dir().join(key)
}

/// Validate a team memory key
pub fn validate_team_memory_key(key: &str) -> Result<(), String> {
    if key.is_empty() {
        return Err("Key cannot be empty".to_string());
    }
    if key.contains("..") {
        return Err("Key cannot contain '..'".to_string());
    }
    if key.starts_with('/') {
        return Err("Key cannot start with '/'".to_string());
    }
    Ok(())
}

/// Read team memory entries from local filesystem
pub async fn read_local_team_memory() -> Result<HashMap<String, String>, AgentError> {
    let dir = get_team_memory_dir();

    if !dir.exists() {
        return Ok(HashMap::new());
    }

    let mut entries = HashMap::new();
    let mut dirs_to_process: Vec<PathBuf> = vec![dir.clone()];

    while let Some(current_dir) = dirs_to_process.pop() {
        let mut read_dir = tokio::fs::read_dir(&current_dir)
            .await
            .map_err(AgentError::Io)?;

        while let Some(entry) = read_dir.next_entry().await.map_err(AgentError::Io)? {
            let path = entry.path();
            let relative = path
                .strip_prefix(&dir)
                .map_err(|_| AgentError::Internal("Failed to get relative path".to_string()))?
                .to_string_lossy()
                .to_string();

            if path.is_dir() {
                dirs_to_process.push(path);
            } else if path.is_file() {
                // Skip hidden files
                if relative.starts_with('.') {
                    continue;
                }
                let content = tokio::fs::read_to_string(&path)
                    .await
                    .map_err(AgentError::Io)?;
                entries.insert(relative, content);
            }
        }
    }

    Ok(entries)
}

/// Write team memory entries to local filesystem
pub async fn write_local_team_memory(entries: &HashMap<String, String>) -> Result<(), AgentError> {
    let dir = get_team_memory_dir();
    tokio::fs::create_dir_all(&dir)
        .await
        .map_err(AgentError::Io)?;

    for (key, content) in entries {
        let path = get_team_memory_path(key);
        if let Some(parent) = path.parent() {
            tokio::fs::create_dir_all(parent)
                .await
                .map_err(AgentError::Io)?;
        }
        tokio::fs::write(&path, content)
            .await
            .map_err(AgentError::Io)?;
    }

    Ok(())
}

/// Delete a team memory entry
pub async fn delete_local_team_memory_entry(key: &str) -> Result<(), AgentError> {
    let path = get_team_memory_path(key);
    if path.exists() {
        tokio::fs::remove_file(path).await.map_err(AgentError::Io)?;
    }
    Ok(())
}

// ─── Delta Computation ─────────────────────────────────────────

/// Compute delta between local and server checksums
pub fn compute_delta(
    local_entries: &HashMap<String, String>,
    server_checksums: &HashMap<String, String>,
) -> HashMap<String, String> {
    let mut delta = HashMap::new();

    for (key, content) in local_entries {
        let local_hash = hash_content(content);
        let server_hash = server_checksums.get(key);

        // Upload if: key doesn't exist on server, or hash differs
        if server_hash.is_none() || server_hash != Some(&local_hash) {
            delta.insert(key.clone(), content.clone());
        }
    }

    delta
}

/// Batch delta entries by byte size
pub fn batch_delta_by_bytes(
    delta: &HashMap<String, String>,
    max_bytes: usize,
) -> Vec<HashMap<String, String>> {
    let mut batches: Vec<HashMap<String, String>> = Vec::new();
    let mut current_batch: HashMap<String, String> = HashMap::new();
    let mut current_bytes: usize = 0;

    // Sort keys for deterministic ordering
    let mut keys: Vec<&String> = delta.keys().collect();
    keys.sort();

    for key in keys {
        let content = delta.get(key).unwrap();
        let entry_bytes = key.len() + content.len();

        // If single entry exceeds max, it goes in its own batch
        if entry_bytes > max_bytes {
            // Flush current batch if non-empty
            if !current_batch.is_empty() {
                batches.push(current_batch);
                current_batch = HashMap::new();
                current_bytes = 0;
            }
            // Put oversized entry in its own batch
            let mut single = HashMap::new();
            single.insert(key.clone(), content.clone());
            batches.push(single);
            continue;
        }

        // Check if adding this entry would exceed limit
        if current_bytes + entry_bytes > max_bytes && !current_batch.is_empty() {
            batches.push(current_batch);
            current_batch = HashMap::new();
            current_bytes = 0;
        }

        current_batch.insert(key.clone(), content.clone());
        current_bytes += entry_bytes;
    }

    // Push remaining batch
    if !current_batch.is_empty() {
        batches.push(current_batch);
    }

    batches
}

// ─── Sync Functions ───────────────────────────────────────────

/// Check if team memory sync is available
pub fn is_team_memory_sync_available() -> bool {
    // Check OAuth configuration
    // In Rust SDK, this would check for valid OAuth tokens
    // For now, return false as OAuth is not implemented
    false
}

/// Pull team memory from server (not implemented - requires OAuth)
pub async fn pull_team_memory(
    _state: &mut SyncState,
    _repo_slug: &str,
) -> Result<TeamMemorySyncFetchResult, AgentError> {
    Ok(TeamMemorySyncFetchResult {
        success: false,
        data: None,
        is_empty: None,
        not_modified: None,
        checksum: None,
        error: Some("Team memory sync requires OAuth authentication".to_string()),
        skip_retry: Some(true),
        error_type: Some("auth".to_string()),
        http_status: None,
    })
}

/// Push team memory to server (not implemented - requires OAuth)
pub async fn push_team_memory(
    _state: &mut SyncState,
    _repo_slug: &str,
    _entries: &HashMap<String, String>,
) -> Result<TeamMemorySyncPushResult, AgentError> {
    Ok(TeamMemorySyncPushResult {
        success: false,
        files_uploaded: 0,
        checksum: None,
        conflict: None,
        error: Some("Team memory sync requires OAuth authentication".to_string()),
        skipped_secrets: Vec::new(),
        error_type: Some("auth".to_string()),
        http_status: None,
    })
}

/// Full sync: pull, merge, push
pub async fn sync_team_memory(
    state: &mut SyncState,
    repo_slug: &str,
) -> Result<TeamMemorySyncPushResult, AgentError> {
    // Pull from server
    let pull_result = pull_team_memory(state, repo_slug).await?;

    if !pull_result.success {
        return Ok(TeamMemorySyncPushResult {
            success: false,
            files_uploaded: 0,
            checksum: None,
            conflict: None,
            error: pull_result.error,
            skipped_secrets: Vec::new(),
            error_type: pull_result.error_type,
            http_status: pull_result.http_status,
        });
    }

    // Read local entries
    let local_entries = read_local_team_memory().await?;

    // Compute delta
    let delta = compute_delta(&local_entries, &state.server_checksums);

    if delta.is_empty() {
        return Ok(TeamMemorySyncPushResult {
            success: true,
            files_uploaded: 0,
            checksum: state.last_known_checksum.clone(),
            conflict: None,
            error: None,
            skipped_secrets: Vec::new(),
            error_type: None,
            http_status: None,
        });
    }

    // Push delta
    push_team_memory(state, repo_slug, &delta).await
}

// ─── Secret Scanning ───────────────────────────────────────────

/// Scan content for potential secrets (placeholder implementation)
pub fn scan_for_secrets(_content: &str, _path: &str) -> Option<SkippedSecretFile> {
    // Real implementation would use gitleaks or similar
    // For now, return None (no secrets detected)
    None
}

/// Scan entries for secrets
pub fn scan_entries_for_secrets(entries: &HashMap<String, String>) -> Vec<SkippedSecretFile> {
    let mut skipped = Vec::new();

    for (path, content) in entries {
        if let Some(secret) = scan_for_secrets(content, path) {
            skipped.push(secret);
        }
    }

    skipped
}

// ─── State Management ──────────────────────────────────────────

/// Global team memory sync enabled flag
static TEAM_MEMORY_ENABLED: AtomicBool = AtomicBool::new(false);

/// Check if team memory sync is enabled
pub fn is_team_memory_enabled() -> bool {
    TEAM_MEMORY_ENABLED.load(Ordering::SeqCst)
}

/// Enable team memory sync
pub fn enable_team_memory() {
    TEAM_MEMORY_ENABLED.store(true, Ordering::SeqCst);
}

/// Disable team memory sync
pub fn disable_team_memory() {
    TEAM_MEMORY_ENABLED.store(false, Ordering::SeqCst);
}

/// Get last sync error (thread-safe)
static LAST_SYNC_ERROR: Mutex<Option<String>> = Mutex::new(None);

/// Set last sync error
pub fn set_last_sync_error(error: Option<String>) {
    *LAST_SYNC_ERROR.lock().unwrap() = error;
}

/// Get last sync error
pub fn get_last_sync_error() -> Option<String> {
    LAST_SYNC_ERROR.lock().unwrap().clone()
}

// ─── Tests ─────────────────────────────────────────────────────

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

    #[test]
    fn test_create_sync_state() {
        let state = create_sync_state();
        assert!(state.last_known_checksum.is_none());
        assert!(state.server_checksums.is_empty());
        assert!(state.server_max_entries.is_none());
    }

    #[test]
    fn test_hash_content() {
        let hash1 = hash_content("hello");
        let hash2 = hash_content("hello");
        let hash3 = hash_content("world");

        assert!(hash1.starts_with("sha256:"));
        assert_eq!(hash1, hash2);
        assert_ne!(hash1, hash3);
    }

    #[test]
    fn test_validate_team_memory_key() {
        assert!(validate_team_memory_key("MEMORY.md").is_ok());
        assert!(validate_team_memory_key("subdir/notes.md").is_ok());
        assert!(validate_team_memory_key("").is_err());
        assert!(validate_team_memory_key("../etc/passwd").is_err());
        assert!(validate_team_memory_key("/absolute/path").is_err());
    }

    #[test]
    fn test_compute_delta() {
        let local = HashMap::from([
            ("a.txt".to_string(), "content1".to_string()),
            ("b.txt".to_string(), "content2".to_string()),
            ("c.txt".to_string(), "content3".to_string()),
        ]);

        let server = HashMap::from([
            ("a.txt".to_string(), hash_content("content1")), // Same
            ("b.txt".to_string(), hash_content("different")), // Different
        ]);

        let delta = compute_delta(&local, &server);

        assert!(delta.contains_key("b.txt")); // Changed
        assert!(delta.contains_key("c.txt")); // New
        assert!(!delta.contains_key("a.txt")); // Unchanged
    }

    #[test]
    fn test_batch_delta_by_bytes() {
        let delta = HashMap::from([
            ("a.txt".to_string(), "x".repeat(100)),
            ("b.txt".to_string(), "y".repeat(100)),
            ("c.txt".to_string(), "z".repeat(250)), // Oversized
        ]);

        let batches = batch_delta_by_bytes(&delta, 150);

        // c.txt should be in its own batch (oversized)
        // a.txt and b.txt should be together
        assert!(batches.len() >= 2);
    }

    #[test]
    fn test_team_memory_enabled() {
        disable_team_memory();
        assert!(!is_team_memory_enabled());

        enable_team_memory();
        assert!(is_team_memory_enabled());

        disable_team_memory();
        assert!(!is_team_memory_enabled());
    }

    #[test]
    fn test_last_sync_error() {
        set_last_sync_error(None);
        assert!(get_last_sync_error().is_none());

        set_last_sync_error(Some("test error".to_string()));
        assert_eq!(get_last_sync_error(), Some("test error".to_string()));
    }
}