- Basic Execution
- Status Monitoring
- Complex Data
- Advanced Variables
- Interactive Agent
- Agent Profile Cookies
Execute an agent and wait for the result in the simplest way possible.
Copy
import { AsteroidClient, executeAgent, waitForExecutionResult } from 'asteroid-odyssey';
async function basicExample() {
const client = AsteroidClient('YOUR_API_KEY');
const executionId = await executeAgent(client, 'YOUR_AGENT_ID', {
dynamic_data: {
DATA: "First name: John, Last name: Smith"
},
agent_profile_id: 'YOUR_AGENT_PROFILE_ID'
});
const result = await waitForExecutionResult(client, executionId);
console.log('Result:', result);
}
basicExample().catch(console.error);
Monitor an agent’s execution status in real-time while it’s running.
Copy
import { AsteroidClient, executeAgent, getExecutionStatus } from 'asteroid-odyssey';
async function monitorExecution() {
const client = AsteroidClient('YOUR_API_KEY');
const executionId = await executeAgent(client, 'YOUR_AGENT_ID', {
dynamic_data: {
DATA: "First name: John, Last name: Smith"
},
agent_profile_id: 'YOUR_AGENT_PROFILE_ID'
});
console.log('Execution started:', executionId);
// Check status periodically
const checkStatus = async () => {
const status = await getExecutionStatus(client, executionId);
console.log(`Status: ${status.status}`);
// Continue checking if status is not final
// Possible statuses: 'starting' | 'running' | 'paused' | 'awaiting_confirmation' | 'completed' | 'error' | 'cancelled'
const finalStatuses = ['completed', 'error', 'cancelled'];
if (!finalStatuses.includes(status.status)) {
setTimeout(checkStatus, 2000); // Check again in 2 seconds
} else {
console.log('Execution finished with final status:', status.status);
}
};
checkStatus();
}
monitorExecution().catch(console.error);
Handle complex form data and structured information with your agents.
Copy
import { AsteroidClient, executeAgent, waitForExecutionResult } from 'asteroid-odyssey';
async function complexFormExample() {
const client = AsteroidClient('YOUR_API_KEY');
const formData = {
personalInfo: {
firstName: "John",
lastName: "Smith",
email: "[email protected]"
},
preferences: {
newsletter: true,
notifications: false
},
address: {
street: "123 Main St",
city: "Anytown",
zipCode: "12345"
}
};
const executionId = await executeAgent(client, 'YOUR_AGENT_ID', {
dynamic_data: {
DATA: JSON.stringify(formData)
},
agent_profile_id: 'YOUR_AGENT_PROFILE_ID'
});
const result = await waitForExecutionResult(client, executionId);
console.log('Form submission result:', result);
}
complexFormExample().catch(console.error);
Use conditionals, loops, and nested data in your agent prompts for dynamic behavior.
Copy
import { AsteroidClient, executeAgent, waitForExecutionResult } from 'asteroid-odyssey';
async function advancedVariablesExample() {
const client = AsteroidClient('YOUR_API_KEY');
// Your agent prompt might look like:
// {{if .is_premium}}
// Navigate to premium dashboard and enable all features
// {{else}}
// Navigate to free dashboard with limited features
// {{end}}
//
// Fill the form with user info:
// Name: {{.user.name}}
// Email: {{.user.email}}
//
// {{range .items}}
// - Add "{{.name}}" ({{.price}}) to cart
// {{end}}
const executionId = await executeAgent(client, 'YOUR_AGENT_ID', {
dynamic_data: {
// Booleans for conditionals
is_premium: true,
// Nested objects
user: {
name: "Jane Smith",
email: "[email protected]",
verified: true
},
// Arrays for loops
items: [
{ name: "Product A", price: "$29.99" },
{ name: "Product B", price: "$49.99" },
{ name: "Product C", price: "$19.99" }
],
// Numbers and strings
max_quantity: 10,
coupon_code: "SAVE20"
},
agent_profile_id: 'YOUR_AGENT_PROFILE_ID'
});
const result = await waitForExecutionResult(client, executionId);
console.log('Execution result:', result);
}
advancedVariablesExample().catch(console.error);
All JSON data types are supported: strings, numbers, booleans, arrays, and objects. See AI Task Node Dynamic Variables for examples.
Build interactive sessions where agents can request human input during execution.For example, create an AI Agent node with this prompt:How to Run:TypeScript:Key Features:
Prerequisites: Your agent must be configured in the Asteroid UI with a prompt that includes the
{{.data}} variable and instructions to request user input when needed.Copy
Your goal is to schedule an appointment. Go to https://asteroid.ai/ and book a demo using these details:
{{.data}}.
If the requested time isn't available, ask the user for help and suggest alternatives. Before submitting, confirm the final selection with the user.
Copy
import { AsteroidClient, executeAgent, getExecutionStatus, getLastNExecutionActivities, addMessageToExecution } from 'asteroid-odyssey';
import readline from 'readline';
// Configuration - Replace with your actual values
const CONFIG = {
apiKey: "YOUR_API_KEY", // Replace with your Asteroid API key
agentId: 'YOUR_AGENT_ID', // Replace with your agent ID
inputData: "Thursday, First name: Ted, Last name: Clubber-Lang, email: [email protected]", // Replace with your input data
pollInterval: 2000 // How often to check for updates (milliseconds)
};
const client = AsteroidClient(CONFIG.apiKey);
let executionId: string | null = null;
// Utility functions
const logHeader = (title: string, char = '═', width = 60) => {
console.log(`\n${title}`);
console.log(char.repeat(width));
};
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
// Execute agent with data
async function startAgentExecution(): Promise<string> {
logHeader('🚀 Starting Agent Execution');
console.log(`🤖 Agent ID: ${CONFIG.agentId}`);
console.log(`📝 Input: ${CONFIG.inputData}`);
console.log('═'.repeat(60));
try {
const execId = await executeAgent(client, CONFIG.agentId, {
dynamic_data: { data: CONFIG.inputData }
});
console.log('✅ Agent execution started successfully!');
console.log('📋 Execution ID:', execId);
return execId;
} catch (error: any) {
console.error('❌ Failed to start agent execution:', error.message);
process.exit(1);
}
}
// Handle terminal execution states
const handleTerminalStates = (status: any): boolean => {
const states: Record<string, () => void> = {
completed: () => { console.log('✅ Execution completed successfully!'); process.exit(0); },
error: () => { console.log('❌ Execution error:', status.reason || 'Unknown error'); process.exit(1); },
cancelled: () => { console.log('🛑 Execution was cancelled'); process.exit(0); }
};
if (states[status.status]) {
states[status.status]();
return true;
}
return false;
};
// Find and display agent's human input request
const findAndDisplayAgentRequest = async (): Promise<boolean> => {
const activities = await getLastNExecutionActivities(client, executionId!, 20);
// Filter all human input requests
const humanInputRequests = activities.filter((activity: any) =>
activity.payload?.activityType === 'action_started'
);
if (humanInputRequests.length === 0) return false;
const humanInputRequest = humanInputRequests[0];
const message = (humanInputRequest.payload.data as any).message;
const timestamp = new Date(humanInputRequest.timestamp).toLocaleString();
logHeader('🤖 Agent Request', '═', 80);
console.log(`📅 ${timestamp}`);
console.log(`💬 ${message}`);
console.log('═'.repeat(80));
return true;
};
async function waitForAgentInput(): Promise<void> {
console.log('🔄 Monitoring execution for agent requests...\n');
while (true) {
try {
const status = await getExecutionStatus(client, executionId!);
if (handleTerminalStates(status)) return;
if (status.status === 'paused_by_agent') {
console.log('⏸️ Agent has paused execution and is requesting input!\n');
if (await findAndDisplayAgentRequest()) return;
} else {
process.stdout.write(`\r📊 Current Status: ${status.status.toUpperCase()}${' '.repeat(20)}`);
}
await sleep(CONFIG.pollInterval);
} catch (error: any) {
console.error('\n❌ Error checking execution status:', error.message);
await sleep(CONFIG.pollInterval);
}
}
}
// Get user input with readline
const getUserInput = (): Promise<string> => new Promise((resolve) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('\n💭 Enter your response: ', (answer) => {
rl.close();
resolve(answer);
});
});
// Send message to execution
const sendMessage = async (message: string): Promise<void> => {
console.log('\n📤 Sending message...');
await addMessageToExecution(client, executionId!, message);
console.log('✅ Message sent successfully!\n🔄 Waiting for agent to continue...\n');
};
// Main interactive session loop
async function runInteractiveSession(): Promise<void> {
while (true) {
await waitForAgentInput();
const userMessage = await getUserInput();
if (userMessage.trim() === '') {
console.log('⚠️ Empty message, please try again.');
continue;
}
try {
await sendMessage(userMessage);
} catch (error: any) {
console.error('❌ Error sending message:', error.message);
}
}
}
// Main execution flow
async function main(): Promise<void> {
logHeader('🚀 Interactive Agent Session');
console.log('💡 Press Ctrl+C to exit\n');
executionId = await startAgentExecution();
await runInteractiveSession();
}
// Graceful exit and error handling
process.on('SIGINT', () => {
console.log('\n\n👋 Goodbye!');
process.exit(0);
});
main().catch(error => {
console.error('❌ Fatal error:', error.message);
process.exit(1);
});
- Save the code above as
interactive-agent.ts - Install the required dependencies:
Copy
npm install asteroid-odyssey@latest typescript ts-node - Run the TypeScript file directly:
Copy
npx tsx interactive-agent.ts
- Save the code above as
interactive-agent.py - Install the required dependencies:
Copy
pip install asteroid-odyssey - Set your API key as an environment variable:
Copy
export ASTEROID_API_KEY="your-api-key-here" - Run the Python script:
Copy
python interactive-agent.py
Copy
🚀 Interactive Agent Session
════════════════════════════════════════════════════════════
💡 Press Ctrl+C to exit
🚀 Starting Agent Execution
════════════════════════════════════════════════════════════
🤖 Agent ID: 216a4c51-217b-401e-ab49-0e87e0e778fd
📝 Input: Thursday, First name: Ted, Last name: Clubber-Lang, email: [email protected]
════════════════════════════════════════════════════════════
✅ Agent execution started successfully!
📋 Execution ID: 199b0638-82ea-4976-b996-13f828dbc066
🔄 Monitoring execution for agent requests...
📊 Current Status: STARTING 📊 Current Status: RUNNING ⏸️ Agent has paused execution and is requesting input!
════════════════════════════════════════════════════════════════════════════════
🤖 Agent Request
════════════════════════════════════════════════════════════════════════════════
📅 2025-09-16 13:45:23
💬 I found the booking form on the website. I can see that Thursday is available, but I need to confirm the specific time. What time would you prefer for your appointment on Thursday? The available slots are: 10:00 AM, 2:00 PM, and 4:30 PM.
💭 Enter your response: 2:00 PM
📤 Sending message...
✅ Message sent successfully!
🔄 Waiting for agent to continue...
🔄 Monitoring execution for agent requests...
📊 Current Status: RUNNING ⏸️ Agent has paused execution and is requesting input!
════════════════════════════════════════════════════════════════════════════════
🤖 Agent Request
════════════════════════════════════════════════════════════════════════════════
📅 2025-09-16 13:45:45
💬 Perfect! I've selected 2:00 PM on Thursday for Ted Clubber-Lang. Before I submit the booking, please confirm these details:
- Name: Ted Clubber-Lang
- Email: [email protected]
- Date: Thursday
- Time: 2:00 PM
Is this correct? Please type 'yes' to confirm or 'no' to make changes.
💭 Enter your response: yes
📤 Sending message...
✅ Message sent successfully!
🔄 Waiting for agent to continue...
🔄 Monitoring execution for agent requests...
📊 Current Status: RUNNING 📊 Current Status: COMPLETED ✅ Execution completed successfully!
- Real-time status monitoring with visual feedback
- Automatic detection of agent input requests
- Clean command-line interface with emojis and formatting
- Proper error handling and retry logic
- Graceful exit handling
- Replace
YOUR_API_KEYwith your Asteroid API key (or setASTEROID_API_KEYenvironment variable for Python) - Replace
YOUR_AGENT_IDwith the ID of your agent - Replace the
inputDatawith appropriate data for your agent - Adjust
pollIntervalif needed (default: 2 seconds)
Create a profile with cookies and manage them later.
Replace the ID placeholders in the snippet below before running
Copy
import { AsteroidClient, createAgentProfile, getAgentProfile, updateAgentProfile, executeAgent, waitForExecutionResult, deleteAgentProfile } from 'asteroid-odyssey';
(async () => {
const client = AsteroidClient('YOUR_API_KEY');
// 1) Create an agent profile with cookies
const created = await createAgentProfile(client, {
name: 'Profile With Cookies',
description: 'Profile preloaded with site cookies',
organization_id: 'YOUR_ORGANIZATION_ID',
proxy_cc: 'us',
proxy_type: 'residential',
captcha_solver_active: false,
sticky_ip: false,
credentials: [],
cookies: [
{
name: 'Session Cookie',
key: 'session_id',
value: 'abc123',
domain: 'example.com',
secure: true,
http_only: true,
same_site: 'Lax',
expiry: '2026-01-01T00:00:00Z',
created_at: new Date().toISOString()
}
]
});
console.log('Created Profile ID:', created.id);
// 2) Fetch the profile to confirm cookies
const profile = await getAgentProfile(client, created.id);
console.log('Cookies on profile:', profile.cookies);
// 3) Update cookies: add one and remove one by ID
const updated = await updateAgentProfile(client, created.id, {
cookies_to_add: [
{
name: 'Auth Token',
key: 'auth_token',
value: 'new-token',
domain: 'example.com',
secure: true,
http_only: true,
same_site: 'Strict',
created_at: new Date().toISOString()
}
],
// Replace with a real cookie id from profile.cookies
cookies_to_delete: profile.cookies.length ? [profile.cookies[0].id as string] : []
});
console.log('Updated cookie count:', updated.cookies.length);
// 4) Execute an agent using the profile with cookies
// Replace with your actual agent ID and any dynamic_data expected by your agent
const executionId = await executeAgent(client, 'YOUR_AGENT_ID', {
agent_profile_id: created.id,
dynamic_data: {
DATA: 'Form input or other structured data'
}
});
console.log('Execution started with ID:', executionId);
// Optionally wait for the result
const result = await waitForExecutionResult(client, executionId, 2000);
console.log('Execution result:', result);
// 5) Cleanup: delete the agent profile
await deleteAgentProfile(client, created.id);
console.log('Deleted profile:', created.id);
})().catch((err) => {
console.error(err);
process.exit(1);
});

