ANTIGRAVITY LABJP
Articles/Agents & Manager
Agents & Manager/2026-03-14Intermediate

Antigravity Remote Agents Guide — Run AI Agents in the Cloud

Run Antigravity AI agents on remote servers and cloud VMs via SSH. Execute large-scale tasks without consuming local resources.

Antigravity321remote agentsSSHcloud2automation79

Antigravity Remote Agents Guide

Antigravity's remote agent capability allows you to run AI agents on SSH-connected servers and cloud VMs. This powerful feature enables large-scale data processing and batch automation without consuming local machine resources.

Understanding Remote Agents

Remote agents are AI agents that operate on servers via SSH connections. They're ideal for:

  • Large-scale data processing: Analyzing terabytes of logs and files
  • Long-running tasks: Batch jobs lasting hours or days
  • Resource-intensive work: Machine learning training and compilation
  • Production incident response: Automated remediation workflows
  • Distributed multi-server processing: Leveraging multiple servers in parallel

SSH Connection Setup

Before using remote agents, properly configure SSH connectivity.

Generating and Deploying SSH Keys

# Generate SSH keypair on local machine (if needed)
ssh-keygen -t ed25519 -C "antigravity@example.com" -f ~/.ssh/antigravity_key
 
# Deploy public key to remote server
ssh-copy-id -i ~/.ssh/antigravity_key.pub user@remote-server.com
 
# Test SSH connection
ssh -i ~/.ssh/antigravity_key user@remote-server.com "echo 'Connection successful'"

Configuring Antigravity SSH Settings

Register SSH connection details in ~/.antigravity/config.yaml:

remote_hosts:
  production:
    host: "prod-server.example.com"
    port: 22
    user: "antigravity"
    key_path: "~/.ssh/antigravity_key"
    timeout: 30
    keep_alive_interval: 60
 
  staging:
    host: "staging-server.example.com"
    port: 22
    user: "antigravity"
    key_path: "~/.ssh/staging_key"
 
  gcp_instance:
    host: "34.123.45.67"
    port: 22
    user: "ubuntu"
    key_path: "~/.ssh/gcp_key"
    bastion_host: "bastion.example.com"  # Optional: for bastion jump hosts
ℹ️
Never commit SSH private keys to version control. Either exclude them in `.antigravityignore` or manage them via environment variables.

Cloud VM Setup (GCP/AWS)

Google Cloud Platform Configuration

# Launch GCE instance
gcloud compute instances create antigravity-agent \
  --image-family=ubuntu-2204-lts \
  --image-project=ubuntu-os-cloud \
  --machine-type=n1-standard-4 \
  --zone=asia-northeast1-a
 
# Configure SSH access
gcloud compute os-login ssh-keys add --key-file=~/.ssh/antigravity_key.pub
 
# Verify SSH connectivity
gcloud compute ssh antigravity-agent --zone=asia-northeast1-a

AWS EC2 Configuration

# Launch EC2 instance with AWS CLI
aws ec2 run-instances \
  --image-id ami-0c802847a7dd848c0 \
  --instance-type t3.xlarge \
  --key-name antigravity-key \
  --security-group-ids sg-xxxxxxxx \
  --region ap-northeast-1
 
# Configure security group for SSH access
aws ec2 authorize-security-group-ingress \
  --group-id sg-xxxxxxxx \
  --protocol tcp \
  --port 22 \
  --cidr 0.0.0.0/0
⚠️
In production, restrict SSH access to specific IP addresses. The `0.0.0.0/0` setting is only for development.

Implementing Remote Agents

Creating and Executing Remote Agents

// antigravity-agent.js
import Antigravity from "@antigravitylab/sdk";
 
const client = new Antigravity({
  apiKey: process.env.ANTIGRAVITY_API_KEY,
});
 
// Create agent on remote server
const remoteAgent = await client.createRemoteAgent({
  name: "log-analyzer-agent",
  host: "production",  // Host name from config.yaml
  workDir: "/tmp/antigravity-workspace",
  capabilities: {
    fileSystem: true,
    commandExecution: true,
    networkAccess: true,
  },
});
 
// Assign task to agent
const task = await remoteAgent.execute({
  instruction: `
    Analyze all log files in /tmp/logs directory and extract error patterns.
    Focus on ERROR and CRITICAL level logs. Generate a comprehensive report.
  `,
  timeout: 3600,  // 1 hour
  maxRetries: 3,
});
 
// Retrieve execution results
console.log("Task Status:", task.status);
console.log("Output:", task.output);
console.log("Execution Time:", task.executionTime);

Monitoring Remote Execution

// Monitor execution in real-time
remoteAgent.on("progress", (event) => {
  console.log(`[${event.timestamp}] ${event.message}`);
});
 
remoteAgent.on("error", (error) => {
  console.error(`Execution Error: ${error.message}`);
});
 
remoteAgent.on("complete", (result) => {
  console.log(`Task completed in ${result.duration}ms`);
  console.log(`Output size: ${result.outputSize} bytes`);
});
 
// Retrieve active session information
const sessionInfo = await remoteAgent.getSessionInfo();
console.log("CPU Usage:", sessionInfo.cpuUsage);
console.log("Memory Usage:", sessionInfo.memoryUsage);
console.log("Network I/O:", sessionInfo.networkIO);

File Synchronization Strategies

Unidirectional Sync (Local → Remote)

// Sync local project files to remote server
const syncResult = await remoteAgent.syncFiles({
  direction: "upload",
  source: "./src",
  destination: "/remote/project/src",
  patterns: {
    include: ["**/*.js", "**/*.json", "**/*.md"],
    exclude: ["node_modules", ".git", "dist"],
  },
  compression: true,  // Compress during transfer
  parallel: 4,        // 4 concurrent transfers
});
 
console.log(`Synced ${syncResult.filesTransferred} files`);
console.log(`Total size: ${syncResult.totalSize} bytes`);

Bidirectional Sync (Results Retrieval)

// Download remote execution results to local
await remoteAgent.syncFiles({
  direction: "download",
  source: "/remote/workspace/output",
  destination: "./results",
  patterns: {
    include: ["**/*.log", "**/*.csv", "**/*.json"],
  },
  preserve: true,  // Preserve timestamps
});
 
// Delta sync (transfer only changed files)
await remoteAgent.syncFiles({
  direction: "bidirectional",
  source: "./data",
  destination: "/remote/data",
  deltaSync: true,  // Transfer only differences
  checksum: "md5",  // Detect changes via MD5
});
ℹ️
When transferring large file volumes, exclude unnecessary files in `.antigravityignore` and enable compression to dramatically reduce transfer time.

Managing Persistent Sessions

Creating and Saving Sessions

// Create persistent session for long-running tasks
const persistentSession = await remoteAgent.createPersistentSession({
  name: "data-pipeline",
  maxIdleTime: 3600,      // Auto-delete after 1 hour idle
  autoReconnect: true,    // Auto-reconnect on disconnection
  checkpoint: true,       // Create periodic checkpoints
});
 
// Queue multiple tasks (pipeline style)
await persistentSession.queue({
  id: "task-1",
  instruction: "Step 1: Download data from source",
  dependencies: [],
});
 
await persistentSession.queue({
  id: "task-2",
  instruction: "Step 2: Process and transform data",
  dependencies: ["task-1"],
});
 
await persistentSession.queue({
  id: "task-3",
  instruction: "Step 3: Upload results to storage",
  dependencies: ["task-2"],
});
 
// Start pipeline execution
await persistentSession.start();
 
// Poll for progress updates
const checkProgress = setInterval(async () => {
  const status = await persistentSession.getStatus();
  console.log(`Pipeline Progress: ${status.completedTasks}/${status.totalTasks}`);
 
  if (status.completed) {
    clearInterval(checkProgress);
    console.log("Pipeline finished successfully");
  }
}, 30000);  // Check every 30 seconds

Resuming and Recovering Sessions

// Resume saved session
const session = await remoteAgent.resumePersistentSession("data-pipeline");
 
// Check available checkpoints
const checkpoints = await session.listCheckpoints();
console.log("Available checkpoints:", checkpoints);
 
// Resume from specific checkpoint
await session.resume(checkpoints[0].id);
 
// Retrieve session statistics
const stats = await session.getStatistics();
console.log("Total execution time:", stats.totalTime);
console.log("Task success rate:", stats.successRate);
console.log("Average task duration:", stats.avgDuration);

Monitoring and Logging

Real-time Log Streaming

// Stream logs from remote agent
const logStream = remoteAgent.streamLogs({
  level: "DEBUG",
  filter: {
    component: "executor",
    tags: ["performance", "error"],
  },
  follow: true,  // Continuously receive new logs
});
 
logStream.on("data", (log) => {
  console.log(`[${log.level}] ${log.timestamp}: ${log.message}`);
});
 
logStream.on("error", (err) => {
  console.error("Log stream error:", err);
});

Performance Metrics Collection

// Monitor remote server performance metrics
const metrics = await remoteAgent.getMetrics({
  interval: 60,  // 60-second collection interval
  duration: 3600,  // Collect for 1 hour
});
 
console.log("CPU Usage Over Time:");
metrics.cpu.forEach(point => {
  console.log(`  ${point.timestamp}: ${point.value}%`);
});
 
console.log("Memory Usage (Peak):", metrics.memory.peak, "MB");
console.log("Disk I/O (Total):", metrics.diskIO.totalBytes, "bytes");
console.log("Network Throughput:", metrics.network.throughput, "Mbps");

Cost Optimization

Auto-scaling Configuration

# Antigravity auto-scaling settings
remote_hosts:
  auto_scaling_pool:
    type: "aws_auto_scaling_group"
    min_instances: 1
    max_instances: 10
    target_instance_type: "t3.large"
 
    scale_up_policy:
      metric: "cpu_usage"
      threshold: 75
      scale_increment: 2
      cooldown: 300
 
    scale_down_policy:
      metric: "cpu_usage"
      threshold: 25
      scale_decrement: 1
      cooldown: 600
 
    cost_optimization:
      spot_instances: true
      spot_max_price: "0.15"
      preemptible: true

Resource Utilization Efficiency

// Maximize efficiency through parallel task execution
const tasks = Array.from({ length: 100 }, (_, i) => ({
  id: `task-${i}`,
  instruction: `Process file segment ${i}`,
}));
 
// Execute batch with parallelization
const batchResult = await remoteAgent.executeBatch(tasks, {
  parallelism: 8,           // Concurrent task count
  batchSize: 50,            // Tasks per batch
  progressCallback: (completed, total) => {
    console.log(`Progress: ${completed}/${total}`);
  },
});
 
console.log(`Total cost: $${batchResult.estimatedCost}`);
console.log(`Time saved by parallelization: ${batchResult.timeSaved}s`);
⚠️
Cloud resources incur charges continuously. Always delete unused instances and sessions to prevent unnecessary costs.

Result Optimization

// Optimize results before transfer
const optimizedResult = await remoteAgent.getResult({
  outputPath: "/remote/output",
  compression: "gzip",      // Apply gzip compression
  chunkSize: "10MB",        // Split large files
  cleanup: true,            // Delete remote files after download
});
 
console.log(`Downloaded ${optimizedResult.files} files`);
console.log(`Compressed size: ${optimizedResult.compressedSize} MB`);

Practical Example: Large-Scale Log Analysis

A complete example of using remote agents for production log analysis.

// Analyze large logs on production server
const analysisTask = await client.createRemoteAgent({
  name: "log-analyzer",
  host: "production",
}).execute({
  instruction: `
    Analyze /var/log/application.log from the last 24 hours:
 
    1. Identify error locations
    2. Calculate error frequencies
    3. Analyze patterns (what operations precede errors)
    4. Estimate affected user count
    5. Generate JSON format report
  `,
  timeout: 1800,
});
 
// Retrieve and visualize results locally
const report = JSON.parse(analysisTask.output);
console.log("=== Error Analysis Report ===");
console.log(`Total errors: ${report.summary.totalErrors}`);
console.log(`Unique patterns: ${report.patterns.length}`);
console.log(`Affected users: ${report.affectedUsers}`);
 
report.patterns.forEach(pattern => {
  console.log(`\nPattern: ${pattern.name}`);
  console.log(`  Frequency: ${pattern.count}`);
  console.log(`  Severity: ${pattern.severity}`);
});

Next Steps

  • Configure monitoring and alerting for remote agents
  • Implement security best practices for cloud environments
  • Develop multi-region distributed processing strategies
  • Troubleshoot production agent issues

Remote agents unlock Antigravity's full scalability potential. Harness cloud computing power effectively with these advanced capabilities.

Share

Thank You for Reading

Antigravity Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • Copy-paste ready implementation code
  • New advanced guides published daily
  • $5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

Agents & Manager2026-07-01
Keeping Naming and Formatting Stable When Your Model Falls Back
When a model falls back mid-run, an agent's naming conventions and formatting drift quietly. Here is how I enforce a model-independent style contract plus a drift probe to keep output consistent.
Agents & Manager2026-06-27
When Your Agent Automation Breaks: How Many Minutes to Recovery?
As Antigravity 2.0 adds desktop, CLI, and SDK surfaces, the things you must restore after a failure multiply too. As an indie developer running several sites on autopilot, I lay out a three-layer recovery design covering credentials, definitions, and state, plus a monthly restore drill.
Agents & Manager2026-06-27
Turning a throwaway prompt into a reusable sub-agent
When a one-off prompt to an Antigravity 2.0 dynamic sub-agent works beautifully, it usually vanishes into your chat history. Here is how to capture it as a reusable definition, with the actual file layout and the distillation steps.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →