Skip to content

agi-inc/agi-node

Repository files navigation

AGI

AGI Node.js SDK

npm version Build Status Coverage License Downloads

Website β€’ Documentation β€’ Platform β€’ Blog


Universal Computer-Use AI


import { AGIClient } from 'agi';

const client = new AGIClient({ apiKey: process.env.AGI_API_KEY });

// Context manager with automatic cleanup
await using session = client.session('agi-0');

const result = await session.runTask(
  'Find three nonstop flights from SFO to JFK next month under $450. ' +
    'Return flight times, airlines, and booking links.'
);

console.log(result.data);
console.log(`Duration: ${result.metadata.duration}s, Steps: ${result.metadata.steps}`);
// Session automatically deleted

Powered by AGI.tech - the world's most capable computer agent. Trusted by Visa for agentic commerce. Evaluated with REAL Bench.


Installation

npm install agi

Get your API key at platform.agi.tech

export AGI_API_KEY="your-api-key"

Quick Start

Simple Task (Recommended)

import { AGIClient } from 'agi';

const client = new AGIClient({ apiKey: process.env.AGI_API_KEY });

// Context manager with automatic cleanup
await using session = client.session('agi-0');

const result = await session.runTask('Find the cheapest iPhone 15 on Amazon');

console.log(result.data); // Task output
console.log(result.metadata.duration); // Execution time in seconds
console.log(result.metadata.steps); // Number of steps taken
// Session automatically deleted when scope exits

Real-Time Event Streaming

await using session = client.session('agi-0');

await session.sendMessage('Research the top 5 AI companies in 2025');

for await (const event of session.streamEvents()) {
  if (event.event === 'thought') {
    console.log('πŸ’­ Agent:', event.data);
  }
  if (event.event === 'done') {
    console.log('βœ… Result:', event.data);
    break;
  }
}
// Session automatically deleted

Polling Configuration

Configure timeouts and polling intervals for different task types:

await using session = client.session('agi-0');

// Quick task (1 min timeout, 2s polling)
const result1 = await session.runTask('What is 2+2?', {
  timeout: 60000,
  pollInterval: 2000,
});

// Complex task (15 min timeout, 5s polling)
const result2 = await session.runTask('Research AI companies...', {
  timeout: 900000,
  pollInterval: 5000,
});

Manual Session Management

For advanced use cases requiring fine-grained control:

// Create session manually
const response = await client.sessions.create('agi-0', {
  webhookUrl: 'https://yourapp.com/webhook',
  maxSteps: 200,
});

// Send message
await client.sessions.sendMessage(response.sessionId, 'Find flights from SFO to JFK under $450');

// Check status
const status = await client.sessions.getStatus(response.sessionId);

// Delete when done
await client.sessions.delete(response.sessionId);

Session Control

await using session = client.session('agi-0');

await session.sendMessage('Long research task...');

// Control execution
await session.pause(); // Pause the agent
await session.resume(); // Resume later
await session.cancel(); // Or cancel

Core Concepts

Understanding the building blocks of agi

Sessions: The Container for Tasks

Every task runs inside a session - an isolated browser environment:

// Recommended: Context manager (automatic cleanup)
await using session = client.session('agi-0');
await session.runTask('Find flights...');
// Session automatically deleted

// Alternative: Manual management
const response = await client.sessions.create('agi-0');
await client.sessions.delete(response.sessionId);

β–Έ Use context managers (await using) for automatic cleanup. Sessions consume resources and should be deleted when done.

Available Agents

  • agi-0 - General purpose agent (recommended)
  • agi-0-fast - Faster agent for simple tasks
  • agi-1 - Advanced agent with enhanced capabilities

See docs.agi.tech for the full list.


Features

  • Natural Language - Describe tasks in plain English, no selectors or scraping code
  • Real-Time Streaming - Watch agent execution live with Server-Sent Events
  • Session Control - Pause, resume, or cancel long-running tasks
  • Browser Control - Navigate and screenshot for visual debugging
  • Type-Safe - Full TypeScript support with comprehensive type definitions
  • Production-Ready - Built-in retries, automatic cleanup, comprehensive error handling

Common Use Cases

Price Monitoring

Monitor product prices and availability across retailers.

const session = await client.createSession('agi-0');

try {
  const result = await session.runTask(
    'Go to amazon.com and search for "Sony WH-1000XM5". ' +
      "Get the current price, check if it's in stock, and return the product rating. " +
      'Return as JSON with fields: price, in_stock, rating, url.'
  );
  console.log(result);
} finally {
  await session.delete();
}

Lead Generation

Extract structured data from public sources.

const session = await client.createSession('agi-0');

try {
  const result = await session.runTask(
    'Go to ycombinator.com/companies, find companies in the "AI" category ' +
      'from the latest batch. For the first 10 companies, get their name, ' +
      'description, and website. Return as a JSON array.'
  );
  console.log(result);
} finally {
  await session.delete();
}

Flight Booking Research

const session = await client.createSession('agi-0');

try {
  const result = await session.runTask(
    'Find three nonstop SFO→JFK flights next month under $450. ' +
      'Compare prices on Google Flights, Kayak, and Expedia. ' +
      'Return flight details and booking links.'
  );
  console.log(result);
} finally {
  await session.delete();
}
Browser Control – Navigate and take screenshots for visual debugging
const session = await client.createSession('agi-0');

try {
  // Navigate to specific URL
  await session.navigate('https://amazon.com');

  // Get screenshot for debugging
  const screenshot = await session.screenshot();
  console.log(screenshot.url); // Current page URL
  console.log(screenshot.title); // Page title
  // screenshot.screenshot contains base64 JPEG data
} finally {
  await session.delete();
}
Session Snapshots – Preserve authentication and browser state
// Create session and save environment
const session1 = await client.createSession('agi-0');
// ... do some authentication work ...
await session1.delete('filesystem');

// Later, restore from saved environment
const session2 = await client.createSession('agi-0', {
  restoreFromEnvironmentId: session1.environmentId,
});
// Authentication state and cookies preserved!

await session2.delete();
Advanced Session Management – Full control over session lifecycle
// Create session with options
const session = await client.createSession('agi-0-fast', {
  webhookUrl: 'https://yourapp.com/webhook',
  maxSteps: 200,
});

// Send message
await session.sendMessage('Find flights from SFO to JFK under $450');

// Check status
const status = await session.getStatus();
console.log(status.status); // "running", "finished", etc.

// List all sessions
const sessions = await client.listSessions();

// Delete when done
await session.delete();
Webhooks – Get notified when tasks complete
const session = await client.createSession('agi-0', {
  webhookUrl: 'https://yourapp.com/webhook',
});

// Your webhook will receive events:
// POST https://yourapp.com/webhook
// {
//   "event": "done",
//   "session_id": "sess_...",
//   "data": {...}
// }
Client-Driven Sessions – Run agents on desktop, mobile, or custom environments

Note: Desktop mode is currently feature-gated. For enterprise access, contact [email protected].

For scenarios where you control the execution environment (desktop automation, mobile apps, custom browsers), use client-driven sessions with AgentLoop:

import { AGIClient, AgentLoop } from 'agi';

const client = new AGIClient({ apiKey: process.env.AGI_API_KEY });

// Create a client-driven session
const session = await client.sessions.create('agi-2-claude', {
  agentSessionType: 'desktop',
  goal: 'Open calculator and compute 2+2',
});

// Create and run the loop
const loop = new AgentLoop({
  client,
  agentUrl: session.agentUrl!,
  captureScreenshot: async () => {
    // Return base64-encoded screenshot from your environment
    return '...';
  },
  executeActions: async (actions) => {
    for (const action of actions) {
      console.log(`Executing: ${action.type}`);
      // Execute action in your environment
    }
  },
  onThinking: (t) => console.log(`πŸ’­ ${t}`),
});

const result = await loop.start();
console.log(`Finished: ${result.finished}`);

Loop Control:

// Start without awaiting
const promise = loop.start();

// Pause/resume/stop
loop.pause(); // Pause after current step
loop.resume(); // Continue execution
loop.stop(); // Stop the loop

// Check state
loop.state; // 'running', 'paused', 'stopped', 'finished'
loop.currentStep; // Current step number
loop.lastResult; // Last StepDesktopResponse

Manual Step Control:

// Or manage the loop yourself
let finished = false;
while (!finished) {
  const screenshot = await captureScreenshot();
  const result = await client.sessions.step(session.agentUrl!, screenshot);
  await executeActions(result.actions);
  finished = result.finished;
}

Error Handling

Robust error handling with detailed debugging
import {
  AGIClient,
  AuthenticationError,
  NotFoundError,
  RateLimitError,
  AgentExecutionError,
  AGIError,
} from 'agi';

const client = new AGIClient({ apiKey: process.env.AGI_API_KEY });

try {
  const session = await client.createSession('agi-0');
  try {
    const result = await session.runTask('Find flights...');
    console.log(result);
  } finally {
    await session.delete();
  }
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Invalid API key');
  } else if (error instanceof NotFoundError) {
    console.error('Session not found');
  } else if (error instanceof RateLimitError) {
    console.error('Rate limit exceeded - please retry');
  } else if (error instanceof AgentExecutionError) {
    console.error('Task failed:', error.message);
    // Debug at VNC URL if available
  } else if (error instanceof AGIError) {
    console.error('API error:', error.message);
  }
}

Examples

Real-world, production-ready examples β†’ See examples/

Quick Start

# 5-line hello world
npx tsx examples/hello-world.ts

# Price tracking
npx tsx examples/ecommerce/price-tracker.ts \
  --product "Sony WH-1000XM5" --max-price 350

# Flight search
npx tsx examples/travel/flight-finder.ts \
  --from SFO --to JFK --date "2026-02-15" --max-price 450

# B2B lead generation
npx tsx examples/sales-marketing/linkedin-scraper.ts \
  --industry "SaaS" --location "San Francisco" --count 10

# Competitor analysis
npx tsx examples/research/competitor-analysis.ts \
  --competitors "stripe.com,square.com,paypal.com"

Example Categories

  • Basic (⭐ Beginner) - Quickstart, error handling, streaming
  • E-Commerce (⭐⭐ Intermediate) - Price tracking, product comparison
  • Travel (⭐⭐ Intermediate) - Flight search, booking research
  • Sales & Marketing (⭐⭐ Intermediate) - Lead generation, LinkedIn scraping
  • Research (⭐⭐ Intermediate) - Competitive analysis, market research
  • Production (⭐⭐⭐ Advanced) - Batch processing, webhook servers

Learning Path: hello-world.ts β†’ basic/quickstart.ts β†’ Choose your domain β†’ Production patterns


Documentation & Resources

Learn More

Get Help


TypeScript Support

This SDK is written in TypeScript and provides full type definitions:

import type { Session, SessionStatus, SSEEvent, NavigateResponse } from 'agi';

const session: Session = await client.createSession('agi-0');
const status: SessionStatus = (await session.getStatus()).status;

Requirements

  • Node.js 20.4 or higher (required for await using syntax)
  • TypeScript 5.0+ (for TypeScript users)

License

MIT License - see LICENSE for details.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 5