async function pollTask(taskId, options = {}) {
const {
pollInterval = 1000,
timeout = 300000, // 5 minutes
onEvent = null
} = options;
const startTime = Date.now();
let lastEventT = 0;
while (true) {
// Check timeout
if (Date.now() - startTime > timeout) {
throw new Error('Polling timeout exceeded');
}
// Poll for updates
const response = await fetch(
`https://api.smooth.sh/api/v1/task/${taskId}?event_t=${lastEventT}`,
{ headers: { 'apikey': API_KEY } }
);
const { r: task } = await response.json();
// Process events
if (task.events && task.events.length > 0) {
for (const event of task.events) {
if (onEvent) {
await onEvent(event);
}
}
// Update timestamp for next poll
lastEventT = task.events[task.events.length - 1].timestamp;
}
// Check if task is complete
if (!['running', 'waiting'].includes(task.status)) {
return task;
}
// Wait before next poll
await new Promise(r => setTimeout(r, pollInterval));
}
}
// Usage
const result = await pollTask('task_abc123', {
pollInterval: 1000,
timeout: 300000,
onEvent: async (event) => {
console.log('Event:', event.name, event.id);
// Handle tool calls
if (event.name === 'tool_call') {
const output = await executeMyTool(event.payload);
await sendToolResponse(taskId, event.id, output);
}
}
});