Tasks
Tasks represent automated actions that can be executed on a schedule or triggered on-demand within the ChatBotKit platform. They enable you to build powerful automation workflows by allowing bots to perform operations at specific times or in response to events, without manual intervention.
A task combines a bot with a schedule and optional contact, creating an automated workflow that executes according to your defined parameters. Tasks are particularly useful for periodic notifications, scheduled data processing, automated reporting, or any operation that needs to run at regular intervals or be triggered programmatically.
Creating Tasks
Creating a task establishes an automated workflow by connecting a bot with a schedule and optional configuration parameters. Tasks can be scheduled to run at regular intervals (quarterhourly, halfhourly, hourly, daily, weekly, monthly) or triggered manually through the API.
When creating a task, you specify the bot that will handle the execution, the schedule defining when it should run, and optional parameters like session duration and contact associations. The system automatically manages task execution based on your schedule configuration.
To create a task with a bot association, send a POST request with the required parameters:
You can also create a task without a bot association by omitting the botId
parameter:
Task Scheduling Options
The schedule parameter is flexible and supports three distinct scheduling patterns,
each designed for different use cases:
Predefined Intervals:
Use predefined interval values for common scheduling patterns. These are simple string values that automatically calculate the next run time:
"quarterhourly"- Runs every 15 minutes"halfhourly"- Runs every 30 minutes"hourly"- Runs every hour"daily"- Runs once per day"weekly"- Runs once per week"monthly"- Runs once per month"never"- Task is created but never runs automatically (manual trigger only)
Cron Expressions:
For more precise scheduling control, use standard cron expressions. The platform supports the standard 5-field cron format (minute, hour, day of month, month, day of week):
Common cron expression examples:
"0 9 * * *"- Every day at 9:00 AM"0 0 * * 0"- Every Sunday at midnight"0 9 * * 1-5"- Weekdays at 9:00 AM"0 0 1 * *"- First day of every month at midnight"30 14 * * 1,3,5"- Monday, Wednesday, Friday at 2:30 PM
Specific Date/Time:
Schedule a task to run once at a specific date and time using ISO 8601 datetime strings or any valid JavaScript date format:
Valid date formats include:
- ISO 8601:
"2025-12-25T10:00:00.000Z" - RFC 2822:
"Wed, 25 Dec 2025 10:00:00 GMT" - Date only:
"2025-12-25"(defaults to midnight UTC)
Important: When using a specific date/time, the task will run once at that time and then stop. If you need the task to run multiple times, use intervals or cron expressions instead.
Session Duration
The sessionDuration parameter (in milliseconds) controls how long the conversation
session remains active during task execution. This determines how much time the bot
has to complete its work before the session times out:
- Minimum: 0 milliseconds (immediate termination after execution)
- Maximum: 3,600,000 milliseconds (1 hour)
- Default: If not specified, uses platform default
Choose an appropriate session duration based on the complexity of your task. Simple notifications might need only a few seconds, while complex data processing or multi-step workflows may require longer durations.
Important Considerations
Bot Association:
The botId parameter is optional, allowing you to create tasks with or without a
specific bot association. When provided, the bot must exist and be accessible by
your account. The bot configuration determines what actions the task will perform
when executed. Tasks without a bot association can still be created and managed
through the API, useful for scenarios where bot assignment happens at a later stage
or through different workflows.
Automatic Next Run Calculation:
Once created, the task automatically calculates the next run time based on your schedule configuration. For intervals and cron expressions, this is computed dynamically. For specific dates, the next run is set to that exact time.
Timezone Handling:
Task schedules default to UTC when no timezone is provided. Set the optional
timezone field to an IANA timezone identifier such as America/New_York
when you want cron expressions or date-based schedules evaluated in a local
timezone.
Schedule Validation:
The platform validates all schedule values at creation time:
- Predefined intervals must match exactly (case-sensitive)
- Cron expressions must be valid standard cron format
- Date strings must be parseable as valid JavaScript dates
- Invalid schedules will result in a validation error
Listing Tasks
Retrieving a list of your tasks allows you to view all automated workflows configured in your account. The list endpoint provides pagination support and filtering capabilities to help you manage large collections of tasks efficiently.
The list endpoint returns tasks in reverse chronological order by default (most recently created first), with support for cursor-based pagination to handle large datasets. Each task in the response includes its configuration details, schedule information, and associated resource identifiers.
To retrieve your tasks, send a GET request:
For paginated results, you can specify query parameters:
The take parameter controls how many tasks to retrieve per page (default behavior
applies if not specified). The order parameter accepts asc or desc to control
sorting direction. The cursor parameter is used for pagination, allowing you to
fetch subsequent pages of results by providing the cursor from the previous response.
Filtering by Bot or Status
You can filter tasks by associated bot or by their status:
Supported filter parameters include:
- botId: Filter by associated bot
- contactId: Filter by associated contact
- status: Filter by task status (
idle,running, orcanceled)
Each task object in the response includes essential fields like id, name,
description, schedule, timezone, botId, contactId, sessionDuration, maxIterations,
maxTime, lastRunAt, nextRunAt, and timestamps. You can use this
information to display task dashboards, monitor active automation workflows, or
build management interfaces for your task automation system.
Note: Tasks are automatically filtered to show only those belonging to your account. Pagination cursors are designed for forward traversal through your task collection.
Exporting Tasks
The export endpoint provides a convenient way to extract your task configurations in multiple formats, enabling backup, migration, or integration with external systems. Unlike the list endpoint, export is specifically designed for bulk data retrieval and format conversion.
This endpoint supports multiple output formats including JSON, JSONL (JSON Lines), and CSV, making it easy to integrate task data with spreadsheets, data processing pipelines, or backup systems. The JSONL format is particularly useful for streaming large datasets, while CSV provides compatibility with spreadsheet applications.
To export your tasks in JSON format:
For CSV export, which is ideal for spreadsheet applications:
The export endpoint includes the same pagination parameters as the list endpoint,
allowing you to export tasks in batches. However, exported data includes additional
formatting for the specified output type. For example, in CSV format, the meta
field is serialized as YAML for better readability and compatibility.
Exported task records preserve scheduling context including schedule and
timezone, so recurring automations can be recreated without losing local
schedule semantics.
Pagination parameters work identically to the list endpoint, supporting cursor,
order, and take query parameters. This allows you to export large task collections
in manageable chunks or create incremental backups of your automation configurations.
Use Case: Export is particularly valuable when migrating between environments, creating backups of your automation workflows, or integrating task data with external monitoring and reporting systems.
Fetching a Task
Retrieving a specific task by its ID allows you to inspect the complete configuration and current state of an automated workflow. This is essential for monitoring task execution, debugging scheduling issues, or displaying task details in user interfaces.
The fetch endpoint returns comprehensive information about a single task, including all configuration parameters, schedule settings, associated resources (bot and contact IDs), and metadata. This detailed view enables you to verify task configuration, check execution status, and ensure your automation workflows are properly configured.
To retrieve a specific task, use its unique identifier:
For example, to fetch a task with ID "task_abc123":
The response includes all task properties such as name, description, schedule,
timezone, botId, contactId, status, outcome, sessionDuration, maxIterations,
maxTime, lastRunAt, nextRunAt, and meta, along with timestamps indicating
when the task was created and last updated.
This endpoint is particularly useful when you need to display task details in a management interface, verify task configuration before making updates, or retrieve task metadata for monitoring and logging purposes. The returned data provides everything needed to understand and manage the automated workflow.
Updating a Task
Modifying an existing task allows you to adjust automation workflows as your requirements evolve. You can change schedules, update bot associations, modify session parameters, or adjust any other task configuration without recreating the entire task.
The update endpoint accepts the same parameters as task creation, applying only the fields you provide while preserving existing values for omitted fields. This partial update capability makes it easy to modify specific aspects of a task without affecting its other configurations.
When you update a task's schedule, the system automatically recalculates the next run time based on the new schedule. Updating a task's timezone also triggers recalculation so the next execution remains aligned with the intended local time. This ensures that schedule changes take effect immediately and tasks execute at the correct times according to your updated configuration.
To update a task, send a POST request with the fields you want to modify:
For example, to change a task's schedule and session duration:
Important: Updating the schedule will immediately recalculate the next run time. If the task is currently scheduled to run, the update will take effect after the current execution completes.
Deleting a Task
Removing a task permanently deletes the automation workflow and stops all future executions. This operation is irreversible and should be used when a task is no longer needed or needs to be completely removed from your automation configuration.
When a task is deleted, the system immediately stops scheduling it for future execution. Any pending executions that haven't started yet will be cancelled. However, if the task is currently executing at the time of deletion, that execution will be allowed to complete before the task is fully removed.
Deleting a task does not affect the associated bot or any conversations that were created by the task. These resources remain intact and can continue to be used by other tasks or directly through the API. Only the task automation configuration itself is removed.
To delete a task, send a POST request with an empty body:
For example, to delete a task with ID "task_abc123":
The endpoint returns the ID of the deleted task in the response, confirming the deletion was successful. After deletion, attempting to fetch, update, or trigger the task will result in a "not found" error.
Warning: This operation cannot be undone. If you need to preserve task configuration for future reference, consider exporting your tasks before deletion or temporarily disabling the task by setting its schedule to "never" instead of deleting it entirely. Always verify you're deleting the correct task before confirming the operation.
Canceling a Running Task
When a task is currently executing and you need to stop it immediately, the cancel endpoint provides a way to halt the running execution and return the task to an idle state. This is useful for stopping long-running tasks, correcting mistakes, or responding to changing requirements without waiting for the task to complete naturally.
Canceling a task marks all currently running executions for that task as
canceled with a failure outcome. The task itself transitions back to an idle
status, and if the task has a schedule configured, the next scheduled run time
is recalculated and set appropriately so the task will continue its regular
schedule going forward. If the task has a timezone configured, that
timezone is reused when calculating the next scheduled run.
To cancel a running task, send a POST request with an empty body:
For example, to cancel a task with ID "task_abc123":
The response returns the ID of the task that was canceled:
If the task is not currently running (already idle or in another non-running state), the cancel operation completes successfully without making changes. This makes the endpoint safe to call even when you are unsure whether the task is actually running.
Use Cases:
- Stopping a task that is taking longer than expected
- Interrupting a task that was triggered with incorrect configuration
- Responding to errors or rate limits that require immediate task termination
- Cleaning up state before making configuration changes to a task
Note: Canceling a task does not delete it. The task remains in your
configuration and will continue running on its schedule if one is configured.
Canceled executions are recorded in the execution history with a canceled
status and failure outcome for auditing purposes.
Listing Task Executions
Each time a task runs it produces a task execution record that captures the outcome, timing, and any summary produced by the agent. Listing executions for a task gives you a full history of every run, making it straightforward to audit automation activity, debug failures, or display a run log in your application.
To retrieve executions for a task, send a GET request:
The response supports the same cursor-based pagination as other list endpoints:
You can filter by execution status:
Each execution record includes:
id: Unique execution identifiertaskId: The parent taskconversationId: The conversation created for this run (if any)status: Current status (idle,running, orcanceled)outcome: Final outcome (pending,success, orfailure)summary: Agent-generated summary of what happened during the runcompletedAt: Timestamp when the execution finished
Triggering a Task
Manually triggering a task executes it immediately, bypassing the configured schedule. This is valuable for running tasks on-demand in response to external events or executing workflows outside their normal schedule without modifying the task configuration.
When you trigger a task, it queues for immediate execution while maintaining its regular schedule for future automated runs. The trigger operation doesn't modify the task's schedule or next run time - it simply creates an additional execution instance that runs as soon as resources are available.
Task triggering is asynchronous. The API endpoint queues the task for execution and returns immediately, confirming that the trigger request was received. The actual task execution happens in the background, creating a conversation with the configured bot and processing the task's instructions.
To trigger a task manually, send a POST request:
For example, to trigger a task with ID "task_abc123":
The task executes with the same configuration and context as scheduled runs, including the associated bot, contact, session duration, and any configured metadata. The execution creates or reuses a conversation session according to the task's session management settings.
Use Cases: Manual triggering is ideal for responding to external events like
webhooks or user actions, running maintenance tasks on-demand, or executing tasks
that don't require a regular schedule. The lastRunAt timestamp is updated when
triggered executions complete.
Note: Task triggering is subject to your account's conversation limits and plan restrictions. Ensure you have sufficient quota before triggering tasks, especially when triggering multiple tasks simultaneously.
Canceling a Specific Task Execution
When a task spawns multiple executions or you need precise control over which execution to stop, the execution cancel endpoint lets you target a specific task execution by its ID rather than canceling all running executions for a task at once. This is particularly useful when a task has a history of executions and you need to cancel only the currently running one without affecting the task configuration or scheduling.
The endpoint cancels the specified execution if it is in a running state,
marking it with a canceled status and failure outcome. At the same time,
the parent task's status is updated to idle and its next scheduled run time
is recalculated if a schedule is configured. If the specified execution is
not currently running, the operation completes successfully with no changes.
To cancel a specific task execution, send a POST request:
For example, to cancel execution "exec_xyz789" belonging to task "task_abc123":
The response returns both the execution ID and the parent task ID:
The endpoint validates that the execution belongs to the specified task and that both resources are owned by the authenticated user. Attempting to cancel an execution that belongs to a different task, or that was created by another user, returns a not found error.
Difference from Task Cancel:
/task/{taskId}/cancel- Cancels all running executions for the task/task/{taskId}/execution/{taskExecutionId}/cancel- Cancels only the specified execution, offering finer-grained control
Note: Viewing the list of executions via
GET /api/v1/task/{taskId}/execution/list helps you identify the correct
execution ID to cancel, especially when a task has multiple execution records.
Subscribing to Task Workflow Events
The task workflow subscription endpoint provides a real-time stream of events emitted while a task is executing. This allows you to observe the progress of a running task execution as it moves through its workflow steps, enabling live status displays, progress indicators, and reactive dashboards without polling.
Each event in the stream follows the same newline-delimited JSON envelope
used by conversation completion endpoints. Every line is a self-contained
JSON object with a type field identifying the event, a createdAt
timestamp, and a data field carrying the event payload. The stream remains
open for the duration of the subscription and closes automatically when the
client disconnects.
Event Types
The stream emits event types that correspond to steps within the task's conversation engine:
operationBegin- Emitted when the conversation engine starts a new operation step, such as calling a tool, running an ability, or making a model request. Thedataobject contains details about the operation that is beginning.operationEnd- Emitted when an operation step completes, whether successfully or with an error. Thedataobject contains the result or error information for the completed step.error- Emitted when the task conversation engine reports an error. Thedataobject matches the conversation completion error event data.
Pairing operationBegin and operationEnd events lets you build accurate
progress indicators that show exactly which step is in flight and how long
each step takes to complete.
Replaying Recent History
By default the subscription only delivers live events from the moment you
connect. If you want to catch up on events that occurred before your
connection was established - for example when reconnecting after a brief
network interruption - you can request a history replay by including
historyLength in the request body:
The server will replay up to the requested number of recent workflow events
before switching to the live stream. The maximum accepted value is 1000.
Setting historyLength to 0 is equivalent to the default behavior of
delivering only live events.
Reading the Event Stream
Because the response uses newline-delimited JSON (JSONL), you should read it line by line. Each complete line is a valid JSON object that can be parsed independently:
An example sequence of events in the stream might look like:
Access Control
Only authenticated users who own the task may subscribe to its workflow events. Attempting to subscribe to a task that belongs to another user returns a 401 Unauthorized response. Tasks that do not exist return a 404 Not Found response.
Note: The subscription stream reflects events from the task's active execution. If the task is not currently running when you connect, the stream will remain open and deliver events as soon as a new execution begins. This allows you to connect proactively before triggering the task and receive the full event sequence from the start of execution.