agent-first-http 0.8.0

Give your AI agent its own private browser — so it reads the real page, past logins and bot walls, without ever touching yours.
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
//! Local profile lifecycle: list / info / lock-status / downloads / delete / prune.
//!
//! Operates on disk only; never reaches over the network. Used by both
//! the SDK consumer and the `afhttp profile` CLI subcommand.

pub mod cookie_jar;
pub mod info;
pub mod lock;
pub mod meta;
pub mod paths;

use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};

use serde::{Deserialize, Serialize};

use crate::shared::error::{Error, ErrorCode};

/// Top-level profile inventory entry from `afhttp profile list`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileEntry {
    pub backend: String,
    pub name: String,
    pub path: PathBuf,
    pub size_bytes: u64,
    pub metadata_present: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_used_at_rfc3339: Option<String>,
    pub locked: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DownloadEntry {
    pub filename: String,
    pub path: PathBuf,
    pub size_bytes: u64,
    pub state: String,
}

fn root_or_default(root: Option<&Path>) -> PathBuf {
    root.map(Path::to_path_buf)
        .unwrap_or_else(paths::default_root)
}

pub fn list(profile_root: Option<&Path>) -> Result<Vec<ProfileEntry>, Error> {
    let root = root_or_default(profile_root);
    if !root.exists() {
        return Ok(Vec::new());
    }
    let mut out = Vec::new();
    for backend in paths::KNOWN_BACKENDS {
        let backend_dir = root.join(backend);
        if !backend_dir.is_dir() {
            continue;
        }
        let read = std::fs::read_dir(&backend_dir).map_err(|e| {
            Error::new(
                ErrorCode::ProfileRootUnavailable,
                format!("read_dir({}): {e}", backend_dir.display()),
            )
        })?;
        for entry in read.flatten() {
            let path = entry.path();
            if !path.is_dir() {
                continue;
            }
            let name = match path.file_name().and_then(|s| s.to_str()) {
                Some(n) => n.to_string(),
                None => continue,
            };
            out.push(info_at(&path, backend, &name)?);
        }
    }
    out.sort_by(|a, b| a.backend.cmp(&b.backend).then_with(|| a.name.cmp(&b.name)));
    Ok(out)
}

pub fn info(
    name: &str,
    backend: Option<&str>,
    profile_root: Option<&Path>,
) -> Result<ProfileEntry, Error> {
    paths::validate_name(name)?;
    let root = root_or_default(profile_root);
    let (backend, dir) = resolve_backend_scoped_profile(&root, name, backend)?;
    info_at(&dir, &backend, name)
}

fn info_at(dir: &Path, backend: &str, name: &str) -> Result<ProfileEntry, Error> {
    let meta_path = dir.join("afhttp-profile.json");
    let (metadata_present, last_used_at) = if meta_path.exists() {
        let m = read_profile_meta(&meta_path)?;
        validate_profile_meta(&m, backend, name, dir)?;
        (true, Some(m.last_used_at_rfc3339))
    } else {
        (false, None)
    };
    let size_bytes = dir_size(dir).unwrap_or(0);
    let locked = lock::probe(dir);
    Ok(ProfileEntry {
        backend: backend.to_string(),
        name: name.to_string(),
        path: dir.to_path_buf(),
        size_bytes,
        metadata_present,
        last_used_at_rfc3339: last_used_at,
        locked,
    })
}

pub fn lock_status(
    name: &str,
    backend: Option<&str>,
    profile_root: Option<&Path>,
) -> Result<lock::LockStatus, Error> {
    paths::validate_name(name)?;
    let root = root_or_default(profile_root);
    let (_, dir) = resolve_backend_scoped_profile(&root, name, backend)?;
    Ok(lock::status(&dir))
}

pub fn downloads(
    name: &str,
    backend: Option<&str>,
    profile_root: Option<&Path>,
) -> Result<Vec<DownloadEntry>, Error> {
    let entry = info(name, backend, profile_root)?;
    downloads_at(&entry.path)
}

fn downloads_at(profile_dir: &Path) -> Result<Vec<DownloadEntry>, Error> {
    let dir = profile_dir.join("downloads");
    if !dir.exists() {
        return Ok(Vec::new());
    }
    let read = std::fs::read_dir(&dir).map_err(|e| {
        Error::new(
            ErrorCode::IoError,
            format!("read_dir({}): {e}", dir.display()),
        )
    })?;
    let mut out = Vec::new();
    for entry in read.flatten() {
        let path = entry.path();
        let Ok(meta) = entry.metadata() else {
            continue;
        };
        if !meta.is_file() {
            continue;
        }
        let Some(filename) = path.file_name().and_then(|name| name.to_str()) else {
            continue;
        };
        let filename = filename.to_string();
        let state = if path.extension().and_then(|ext| ext.to_str()) == Some("crdownload") {
            "in_progress"
        } else {
            "completed"
        };
        let path = path.canonicalize().unwrap_or(path);
        out.push(DownloadEntry {
            filename,
            path,
            size_bytes: meta.len(),
            state: state.to_string(),
        });
    }
    out.sort_by(|a, b| a.filename.cmp(&b.filename));
    Ok(out)
}

pub fn delete(
    name: &str,
    confirm: &str,
    backend: Option<&str>,
    profile_root: Option<&Path>,
) -> Result<(), Error> {
    paths::validate_name(name)?;
    if name != confirm {
        return Err(Error::new(
            ErrorCode::InvalidArgument,
            format!("profile delete: --confirm must match name (got {confirm:?})"),
        ));
    }
    let root = root_or_default(profile_root);
    let (backend, dir) = resolve_backend_scoped_profile(&root, name, backend)?;
    if lock::probe(&dir) {
        return Err(Error::new(
            ErrorCode::ProfileDeleteLocked,
            format!("profile {backend}/{name:?} is locked; cannot delete"),
        ));
    }
    std::fs::remove_dir_all(&dir).map_err(|e| {
        Error::new(
            ErrorCode::IoError,
            format!("remove_dir_all({}): {e}", dir.display()),
        )
    })
}

fn resolve_backend_scoped_profile(
    root: &Path,
    name: &str,
    backend: Option<&str>,
) -> Result<(String, PathBuf), Error> {
    if let Some(backend) = backend {
        paths::validate_backend_key(backend)?;
        let dir = paths::join_root_backend_name(root, backend, name)?;
        if dir.exists() {
            return Ok((backend.to_string(), dir));
        }
        return Err(Error::new(
            ErrorCode::ProfileNotFound,
            format!(
                "profile {name:?} not found for backend {backend:?} at {}",
                dir.display()
            ),
        ));
    }

    let mut candidates = Vec::new();
    for backend in paths::KNOWN_BACKENDS {
        let dir = root.join(backend).join(name);
        if dir.exists() {
            candidates.push(((*backend).to_string(), dir));
        }
    }
    match candidates.len() {
        0 => Err(Error::new(
            ErrorCode::ProfileNotFound,
            format!(
                "profile {name:?} not found under backend-scoped root {}",
                root.display()
            ),
        )),
        1 => Ok(candidates.remove(0)),
        _ => Err(Error::new(
            ErrorCode::InvalidArgument,
            format!(
                "profile {name:?} exists under multiple backends ({}); pass --backend <backend>",
                candidates
                    .iter()
                    .map(|(backend, _)| backend.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
        )),
    }
}

pub fn read_profile_meta(path: &Path) -> Result<meta::ProfileMeta, Error> {
    let s = std::fs::read_to_string(path).map_err(|e| {
        Error::new(
            ErrorCode::IoError,
            format!("read profile metadata {}: {e}", path.display()),
        )
    })?;
    serde_json::from_str::<meta::ProfileMeta>(&s).map_err(|e| {
        Error::new(
            ErrorCode::ProfileInvalidName,
            format!(
                "profile metadata {} is not schema v{}: {e}; delete/recreate this profile",
                path.display(),
                meta::ProfileMeta::SCHEMA_VERSION
            ),
        )
    })
}

pub fn validate_profile_meta(
    meta: &meta::ProfileMeta,
    backend: &str,
    name: &str,
    dir: &Path,
) -> Result<(), Error> {
    if meta.schema_version != meta::ProfileMeta::SCHEMA_VERSION {
        return Err(Error::new(
            ErrorCode::ProfileInvalidName,
            format!(
                "profile metadata at {} has schema_version {}; expected {}; delete/recreate this profile",
                dir.join("afhttp-profile.json").display(),
                meta.schema_version,
                meta::ProfileMeta::SCHEMA_VERSION
            ),
        ));
    }
    if meta.backend != backend {
        return Err(Error::new(
            ErrorCode::ProfileInvalidName,
            format!(
                "profile metadata backend {:?} does not match path backend {:?} at {}; delete/recreate this profile",
                meta.backend,
                backend,
                dir.display()
            ),
        ));
    }
    if meta.name != name {
        return Err(Error::new(
            ErrorCode::ProfileInvalidName,
            format!(
                "profile metadata name {:?} does not match path name {:?} at {}; delete/recreate this profile",
                meta.name,
                name,
                dir.display()
            ),
        ));
    }
    Ok(())
}

pub fn prune(
    older_than: Duration,
    dry_run: bool,
    profile_root: Option<&Path>,
) -> Result<Vec<ProfileEntry>, Error> {
    let entries = list(profile_root)?;
    let now = SystemTime::now();
    let mut removed = Vec::new();
    for entry in entries {
        if entry.locked {
            continue;
        }
        let too_old = match std::fs::metadata(&entry.path) {
            Ok(m) => match m.modified() {
                Ok(t) => match now.duration_since(t) {
                    Ok(age) => age >= older_than,
                    Err(_) => false,
                },
                Err(_) => false,
            },
            Err(_) => false,
        };
        if !too_old {
            continue;
        }
        if !dry_run {
            std::fs::remove_dir_all(&entry.path).map_err(|e| {
                Error::new(
                    ErrorCode::IoError,
                    format!("remove_dir_all({}): {e}", entry.path.display()),
                )
            })?;
        }
        removed.push(entry);
    }
    Ok(removed)
}

fn dir_size(dir: &Path) -> std::io::Result<u64> {
    let mut total: u64 = 0;
    let mut stack = vec![dir.to_path_buf()];
    while let Some(p) = stack.pop() {
        for entry in std::fs::read_dir(&p)?.flatten() {
            let path = entry.path();
            let md = match entry.metadata() {
                Ok(m) => m,
                Err(_) => continue,
            };
            if md.is_file() {
                total = total.saturating_add(md.len());
            } else if md.is_dir() {
                stack.push(path);
            }
        }
    }
    Ok(total)
}

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

    fn touch_profile(root: &Path, backend: &str, name: &str) -> PathBuf {
        let dir = root.join(backend).join(name);
        std::fs::create_dir_all(&dir).unwrap();
        let meta = meta::ProfileMeta::new(name, backend);
        std::fs::write(
            dir.join("afhttp-profile.json"),
            serde_json::to_string(&meta).unwrap(),
        )
        .unwrap();
        dir
    }

    #[test]
    fn lists_existing_profiles() {
        let tmp = tempfile::tempdir().unwrap();
        touch_profile(tmp.path(), "brave", "work");
        touch_profile(tmp.path(), "chromium", "alpha");
        std::fs::create_dir_all(tmp.path().join("old-layout")).unwrap();
        let entries = list(Some(tmp.path())).unwrap();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].backend, "brave"); // sorted by backend, then name
        assert_eq!(entries[0].name, "work");
        assert_eq!(entries[1].backend, "chromium");
        assert_eq!(entries[1].name, "alpha");
        assert!(entries[0].metadata_present);
    }

    #[test]
    fn info_returns_profile_details() {
        let tmp = tempfile::tempdir().unwrap();
        touch_profile(tmp.path(), "brave", "work");
        let entry = info("work", Some("brave"), Some(tmp.path())).unwrap();
        assert_eq!(entry.name, "work");
        assert_eq!(entry.backend, "brave");
        assert!(entry.metadata_present);
        assert!(!entry.locked);
    }

    #[test]
    fn downloads_lists_profile_download_artifacts() {
        let tmp = tempfile::tempdir().unwrap();
        let profile = touch_profile(tmp.path(), "brave", "work");
        let download_dir = profile.join("downloads");
        std::fs::create_dir_all(&download_dir).unwrap();
        std::fs::write(download_dir.join("report.csv"), "abc").unwrap();
        std::fs::write(download_dir.join("pending.bin.crdownload"), "partial").unwrap();

        let entries = downloads("work", Some("brave"), Some(tmp.path())).unwrap();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].filename, "pending.bin.crdownload");
        assert_eq!(entries[0].state, "in_progress");
        assert_eq!(entries[1].filename, "report.csv");
        assert_eq!(entries[1].size_bytes, 3);
        assert_eq!(entries[1].state, "completed");
    }

    #[test]
    fn info_missing_profile_returns_not_found() {
        let tmp = tempfile::tempdir().unwrap();
        let err = info("nope", Some("brave"), Some(tmp.path())).err().unwrap();
        assert_eq!(err.error_code, ErrorCode::ProfileNotFound);
    }

    #[test]
    fn delete_requires_matching_confirm() {
        let tmp = tempfile::tempdir().unwrap();
        touch_profile(tmp.path(), "brave", "work");
        let err = delete("work", "different", Some("brave"), Some(tmp.path()))
            .err()
            .unwrap();
        assert_eq!(err.error_code, ErrorCode::InvalidArgument);
    }

    #[test]
    fn delete_removes_profile() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = touch_profile(tmp.path(), "brave", "work");
        delete("work", "work", Some("brave"), Some(tmp.path())).unwrap();
        assert!(!dir.exists());
    }

    #[test]
    fn delete_missing_returns_not_found() {
        let tmp = tempfile::tempdir().unwrap();
        let err = delete("nope", "nope", Some("brave"), Some(tmp.path()))
            .err()
            .unwrap();
        assert_eq!(err.error_code, ErrorCode::ProfileNotFound);
    }

    #[test]
    fn delete_locked_refuses() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = touch_profile(tmp.path(), "brave", "work");
        // Hold the lock for the duration of the assertion.
        let _g = lock::Guard::acquire(&dir).unwrap();
        let err = delete("work", "work", Some("brave"), Some(tmp.path()))
            .err()
            .unwrap();
        assert_eq!(err.error_code, ErrorCode::ProfileDeleteLocked);
    }

    #[test]
    fn prune_dry_run_does_not_delete() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = touch_profile(tmp.path(), "brave", "work");
        // Set mtime far in the past.
        let two_hours = SystemTime::now() - Duration::from_secs(7200);
        filetime::set_file_mtime(&dir, filetime::FileTime::from_system_time(two_hours)).ok();
        let removed = prune(Duration::from_secs(3600), true, Some(tmp.path())).unwrap();
        assert_eq!(removed.len(), 1);
        assert!(dir.exists());
    }

    #[test]
    fn prune_removes_old_profiles() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = touch_profile(tmp.path(), "brave", "work");
        let two_hours = SystemTime::now() - Duration::from_secs(7200);
        filetime::set_file_mtime(&dir, filetime::FileTime::from_system_time(two_hours)).ok();
        let removed = prune(Duration::from_secs(3600), false, Some(tmp.path())).unwrap();
        assert_eq!(removed.len(), 1);
        assert!(!dir.exists());
    }

    #[test]
    fn same_name_multiple_backends_requires_backend() {
        let tmp = tempfile::tempdir().unwrap();
        touch_profile(tmp.path(), "brave", "work");
        touch_profile(tmp.path(), "chromium", "work");
        let err = info("work", None, Some(tmp.path())).err().unwrap();
        assert_eq!(err.error_code, ErrorCode::InvalidArgument);
        assert!(err.detail.contains("--backend"));

        let chromium = info("work", Some("chromium"), Some(tmp.path())).unwrap();
        assert_eq!(chromium.backend, "chromium");
    }

    #[test]
    fn same_name_different_backends_have_independent_locks_and_downloads() {
        let tmp = tempfile::tempdir().unwrap();
        let brave = touch_profile(tmp.path(), "brave", "work");
        let chromium = touch_profile(tmp.path(), "chromium", "work");
        let _guard = lock::Guard::acquire(&brave).unwrap();

        assert!(
            lock_status("work", Some("brave"), Some(tmp.path()))
                .unwrap()
                .locked
        );
        assert!(
            !lock_status("work", Some("chromium"), Some(tmp.path()))
                .unwrap()
                .locked
        );

        std::fs::create_dir_all(brave.join("downloads")).unwrap();
        std::fs::create_dir_all(chromium.join("downloads")).unwrap();
        std::fs::write(brave.join("downloads").join("brave.txt"), "a").unwrap();
        std::fs::write(chromium.join("downloads").join("chromium.txt"), "b").unwrap();
        let brave_downloads = downloads("work", Some("brave"), Some(tmp.path())).unwrap();
        let chromium_downloads = downloads("work", Some("chromium"), Some(tmp.path())).unwrap();
        assert_eq!(brave_downloads[0].filename, "brave.txt");
        assert_eq!(chromium_downloads[0].filename, "chromium.txt");
    }

    #[test]
    fn metadata_backend_mismatch_is_rejected() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("brave").join("work");
        std::fs::create_dir_all(&dir).unwrap();
        let meta = meta::ProfileMeta::new("work", "chromium");
        std::fs::write(
            dir.join("afhttp-profile.json"),
            serde_json::to_string(&meta).unwrap(),
        )
        .unwrap();
        let err = info("work", Some("brave"), Some(tmp.path())).err().unwrap();
        assert_eq!(err.error_code, ErrorCode::ProfileInvalidName);
        assert!(err.detail.contains("backend"));
    }
}