Skip to main content

401 Unauthorized

Problem: Authentication failing Quick Fix: Verify API key format, environment variables, and test authentication.
1

1. Verify API Key Format

Check that your API key is properly formatted:
// Check API key format
if (!API_KEY || API_KEY.length < 20) {
  throw new Error('Invalid API key format');
}

// Ensure Bearer prefix in header
const headers = {
  'Authorization': `Bearer ${API_KEY}`,  // Must include "Bearer "
  'Content-Type': 'application/json'
};
2

2. Check Environment Variables

Load API key from environment, never hardcode:
// Load from environment
const API_KEY = process.env.AGI_API_KEY;

if (!API_KEY) {
  throw new Error('AGI_API_KEY environment variable not set');
}

// For development, use .env file with dotenv
import 'dotenv/config';
const API_KEY = process.env.AGI_API_KEY;
3

3. Test Authentication

Verify your API key works before starting work:
async function testAuth() {
  try {
    const response = await fetch('https://api.agi.tech/v1/models', {
      headers: { 'Authorization': `Bearer ${API_KEY}` }
    });
    
    if (response.status === 200) {
      console.log('✓ Authentication successful');
      return true;
    } else if (response.status === 401) {
      console.log('✗ Invalid API key');
      return false;
    } else if (response.status === 403) {
      console.log('✗ API key not authorized for this resource');
      return false;
    }
  } catch (e) {
    console.log(`✗ Connection error: ${e.message}`);
    return false;
  }
}

// Run before starting work
if (!(await testAuth())) {
  process.exit(1);
}

Authentication Not Preserved

Problem: Authentication state is lost when restoring from snapshot Solution: Use filesystem snapshots and verify default environment
Ensure you’re using filesystem mode, not memory:
// 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 ${API_KEY}` }
});
Check if default environment is set correctly:
// When creating session, ensure you're restoring from default
const response = await fetch('https://api.agi.tech/v1/sessions', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${API_KEY}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    agent_name: 'agi-0',
    restore_default_environment_from_user_id: userId  // Must match
  })
});
Some authentication tokens expire. You may need to re-authenticate:
// 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 ${API_KEY}` }
  });
}

Snapshot Restoration Fails

Problem: Unable to restore from snapshot Solution: Implement fallback logic with multiple restore strategies
async function safeRestoreFromSnapshot(sourceSessionId, userId) {
  try {
    // Try restoring from specific session
    const response = await fetch('https://api.agi.tech/v1/sessions', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        agent_name: 'agi-0',
        restore_from_session_id: sourceSessionId
      })
    });
    
    if (response.ok) {
      return (await response.json()).session_id;
    }
    
    if (response.status === 404) {
      // Snapshot not found, try default
      console.log('Specific snapshot not found, trying default...');
      const defaultResponse = await fetch('https://api.agi.tech/v1/sessions', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${API_KEY}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          agent_name: 'agi-0',
          restore_default_environment_from_user_id: userId
        })
      });
      return (await defaultResponse.json()).session_id;
    }
  } catch (e) {
    // Fallback to fresh session
    console.log('Restoration failed, creating fresh session...');
    const freshResponse = await fetch('https://api.agi.tech/v1/sessions', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ agent_name: 'agi-0' })
    });
    return (await freshResponse.json()).session_id;
  }
}