Skip to main content

Overview

Session snapshots preserve authentication state, allowing you to maintain logged-in sessions across multiple agent sessions without re-authenticating.

How Authentication is Preserved

Authentication state is preserved through snapshots in several ways:

Browser Cookies

All cookies stored in browser profile
Preserved in filesystem snapshots

Web Storage

localStorage and sessionStorage
Preserved in browser profile

Browser State

Logged-in sessions
Authentication tokens
Session data
When you save a filesystem snapshot, all browser state including cookies, localStorage, sessionStorage, and authentication tokens are captured and can be restored in future sessions.

Best Practices

1. Use Filesystem Snapshots

For authentication-critical applications, always use save_snapshot_mode=filesystem:
// ✅ Correct: Use filesystem for authentication
await fetch(`https://api.agi.tech/v1/sessions/${sessionId}?save_snapshot_mode=filesystem&save_as_default=true`, {
  method: 'DELETE',
  headers: { 'Authorization': `Bearer ${apiKey}` }
});

// ❌ Incorrect: Memory snapshots may not preserve all auth state
// await fetch(`https://api.agi.tech/v1/sessions/${sessionId}?save_snapshot_mode=memory&save_as_default=true`, {
//   method: 'DELETE',
//   headers: { 'Authorization': `Bearer ${apiKey}` }
// });

2. Save After Login

Save snapshots immediately after successful authentication:
// After logging in and completing authentication
await fetch(`https://api.agi.tech/v1/sessions/${sessionId}?save_snapshot_mode=filesystem&save_as_default=true`, {
  method: 'DELETE',
  headers: { 'Authorization': `Bearer ${apiKey}` }
});

3. Update Regularly

Refresh snapshots periodically to update authentication tokens before they expire:
// Check if authentication is still valid
const result = await session.runTask("Check if I'm logged in");

if (result.toLowerCase().includes("not logged in")) {
  // Re-authenticate and save new snapshot
  await session.runTask("Login again");
  
  // Save updated snapshot
  await fetch(`https://api.agi.tech/v1/sessions/${sessionId}?save_snapshot_mode=filesystem&save_as_default=true`, {
    method: 'DELETE',
    headers: { 'Authorization': `Bearer ${apiKey}` }
  });
}

4. Multiple Environments

Maintain separate environments for different authentication contexts:
// Work account
await fetch(`https://api.agi.tech/v1/sessions/${workSessionId}?save_snapshot_mode=filesystem&save_as_default=true`, {
  method: 'DELETE',
  headers: { 'Authorization': `Bearer ${apiKey}` }
});

// Personal account (use different user_id)
await fetch(`https://api.agi.tech/v1/sessions/${personalSessionId}?save_snapshot_mode=filesystem&save_as_default=true`, {
  method: 'DELETE',
  headers: { 'Authorization': `Bearer ${apiKey}` }
});

Authentication State Lifecycle

1. Create Session → Fresh environment (no auth)
2. Login to Service → Authentication cookies stored
3. Delete Session with Snapshot → Auth state saved
4. Create New Session from Snapshot → Auth state restored
5. Continue Using Service → Already authenticated

Troubleshooting

Authentication Not Preserved

If authentication is not preserved, check these common issues:
Ensure you’re using filesystem mode, not memory or none:
# Check your delete request includes filesystem mode
http DELETE "https://api.agi.tech/v1/sessions/$SESSION_ID?save_snapshot_mode=filesystem&save_as_default=true" \
  Authorization:"Bearer $AGI_API_KEY"
Confirm the environment is set as default:
# When creating session, ensure you're restoring from default
http POST https://api.agi.tech/v1/sessions \
  Authorization:"Bearer $AGI_API_KEY" \
  agent_name=agi-0 \
  restore_default_environment_from_user_id=$USER_ID
Some authentication tokens expire. You may need to re-authenticate periodically:
// Check if authentication is still valid
const result = await session.runTask("Check if I'm logged in");

if (result.toLowerCase().includes("not logged in")) {
  // Re-authenticate and save new snapshot
  await session.runTask("Login again");
}

Complete Example

Complete workflow for authentication management:
class AuthManager {
  constructor(apiKey, baseUrl, userId) {
    this.apiKey = apiKey;
    this.baseUrl = baseUrl;
    this.userId = userId;
  }

  async createSession(restoreFromDefault = true) {
    const payload = { agent_name: "agi-0" };
    
    if (restoreFromDefault) {
      payload.restore_default_environment_from_user_id = this.userId;
    }

    const response = await fetch(`${this.baseUrl}/v1/sessions`, {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${this.apiKey}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(payload),
    });

    if (!response.ok) {
      throw new Error(`Failed to create session: ${response.statusText}`);
    }

    return await response.json();
  }

  async saveSessionAsDefault(sessionId, snapshotMode = "filesystem") {
    const url = new URL(`${this.baseUrl}/v1/sessions/${sessionId}`);
    url.searchParams.set("save_snapshot_mode", snapshotMode);
    url.searchParams.set("save_as_default", "true");

    const response = await fetch(url.toString(), {
      method: "DELETE",
      headers: {
        "Authorization": `Bearer ${this.apiKey}`,
      },
    });

    if (!response.ok) {
      throw new Error(`Failed to save session: ${response.statusText}`);
    }

    return await response.json();
  }
}

// Usage
const manager = new AuthManager("your-api-key", "https://api.agi.tech", "your-user-id");

// Create session and authenticate
const session = await manager.createSession(false);
const sessionId = session.session_id;

// ... perform authentication ...

// Save as default for future sessions
await manager.saveSessionAsDefault(sessionId, "filesystem");

// Future sessions will automatically restore from default
const newSession = await manager.createSession(true);