Skip to content

Triggering from your app

Coming from Trigger.dev

Bok Joy keeps Trigger.dev's names where the behavior matches, in your tasks and in your backend. This page lists every place it differs, and what to change when you move a project over.

On this page

Most code moves over with an import change, and a codemod makes it. Task files import from @bokjoy/sdk/trigger instead of @trigger.dev/sdk, and keep their task(), schemaTask() and schedules.task() definitions: see Defining tasks. Backends import tasks and runs from @bokjoy/sdk. In Python, import them with from bokjoy import tasks, runs. The names are the same, in snake case. The differences that matter are status casing, a few flags, idempotency keys, batches, schedules, delays and debounces, tags and run lists, lifecycle hooks, and the options Bok Joy does not have. The Trigger.dev side below was checked against its documentation and source on October 7, 8, 10, 11 and 13, 2026.

Triggering from your backend#

import { tasks } from '@trigger.dev/sdk'; const handle = await tasks.trigger('email.send', payload, {  idempotencyKey: `order-${orderId}:receipt`,});
Trigger.devBok JoyWhat to change
import { tasks, runs } from '@trigger.dev/sdk'import { tasks, runs } from '@bokjoy/sdk'The import.
TRIGGER_SECRET_KEY, TRIGGER_API_URLBOKJOY_API_KEY, BOKJOY_API_URLThe variables. The key is an environment API key, bjk_<env>_....
configure({ secretKey, baseURL })configure({ apiKey, url })The option names.
tasks.trigger(id, payload, options)tasks.trigger(id, payload, options), returning a handle with id, taskIdentifier and isCached. From @bokjoy/sdk/trigger it also has publicAccessToken, which reads that run alone for an hour, as Trigger.dev's doesNothing, apart from the options below.
new TriggerClient({ accessToken, baseURL, previewBranch })The same from @bokjoy/sdk/trigger, with Trigger.dev's key rules and handle. A Bok Joy key belongs to one environment, so previewBranch must name the key's own preview environment: a trigger that names another fails with a NotFoundError and starts nothing. The branch is never read from the environmentThe import.
tasks.trigger(id, payload) without a type argument takes any payloadThe same from @bokjoy/sdk/trigger. From @bokjoy/sdk, any JSON valueNothing.
tasks.batchTrigger(id, items): up to 1,000 items (SDK 4.3.1 and later, 500 before), returning a batch handle with a batchIdtasks.batchTrigger(id, items): 1 to 1,000 items, all or none in one transaction, returning {runs} with every handleRead the handles from runs.
A batch idempotencyKey gives each item a key derived from it and the item's indexItem i gets <key>:<i>Nothing.
triggerAndWait only inside a task's run(). It returns {ok, id, output} or {ok: false, error}, with .unwrap()tasks.triggerAndWait from any backend. It returns the output, and throws RunFailedError for a failed or cancelled runReplace if (result.ok) with try/catch. Inside a task, see Waiting on child runs.
batchTriggerAndWaitFrom a backend, noneCall batchTrigger, then runs.poll each run. Inside a task, see Waiting on child runs.
runs.retrieve(id)runs.retrieve(run)Nothing. It takes an ID or a handle.
A payload over 512 KB goes to object storage, and runs.retrieve returns payloadPresignedUrl and outputPresignedUrl for large values. The SDK uploads a payload over 128 KB itself.A payload is at most 3 MiB and an output at most 10 MiB. Bok Joy stores a value over 512 KiB out of line, and runs.retrieve returns payload and output whole. There are no presigned URLs. The SDK sends the payload in the request.Read payload and output instead of fetching a presigned URL.
runs.list(params), with Trigger.dev's statuses and taskIdentifierThe same from @bokjoy/sdk/trigger. runs.list from @bokjoy/sdk takes Bok Joy's statuses and taskImport runs from @bokjoy/sdk/trigger. See Tags and run lists.
runs.poll(id, { pollIntervalMs }), which gives up after 500 readsruns.poll(run, { pollIntervalMs, timeoutMs, until, signal }), with no read limitSet timeoutMs for a bound.
runs.cancel(id)runs.cancel(run), which also cancels every unfinished run below itNothing.
runs.reschedule(id, { delay })runs.reschedule(run, { delay }). In Python, runs.reschedule(run, delay).Nothing. See Delays and debounces for what differs.
runs.replay(id) starts the run again from the startNo SDK call: Replay run in the console. For a failed workflow, runs.retryFromFailure(run) starts a new run that reuses the steps that succeeded before the failure and runs the restTo run every step again, use Replay run. After fixing a failed workflow, use runs.retryFromFailure.
runs.subscribeToRun(id) yields the run object on each changeruns.subscribe(run) yields stream messages (snapshot, event, end) for the run and every run below itRead the run with runs.retrieve when a message says it changed.
Machines micro, small-1x, small-2x, medium-1x, medium-2x, large-1x, large-2xmicro, small, small-2x, medium, medium-2x, large, large-2x, with the same sizesNothing in Node: the client and task definitions take Trigger.dev's names. In Python, rename small-1x, medium-1x and large-1x.

Statuses and flags#

Trigger.dev's statuses are upper case. Bok Joy's are lower case, so status === 'COMPLETED' never matches. Compare with 'completed', or better, use the flags.

Code that imports runs from @bokjoy/sdk/trigger gets Trigger.dev's statuses instead. runs.retrieve, runs.poll, runs.cancel and runs.list answer with the upper case values in the first column, one for each Bok Joy status: running is EXECUTING, and failed is FAILED. Their isFailed is true for a cancelled run too, as Trigger.dev's is, and taskIdentifier names the task. The root @bokjoy/sdk keeps the lower case statuses.

Trigger.dev statusBok Joy status
DELAYEDdelayed
QUEUEDqueued
DEQUEUED, EXECUTINGrunning
WAITINGwaiting
COMPLETEDcompleted
CANCELEDcancelled, with two Ls
FAILED, CRASHED, SYSTEM_FAILURE, TIMED_OUTfailed, once its attempts are used, with the reason in error. A run past its timeout is failed at once.
EXPIREDNone: Bok Joy has no TTL. A run no worker can hold yet has a capacityWait, and fails at its until.
PENDING_VERSIONNone: a trigger for a task the environment's deployment lacks is refused with a ValidationError.
FlagIn Bok Joy
isCompletedThe same as Trigger.dev's: true for any finished run, failed and cancelled included. isFinished is a clearer name for it.
isFailedTrue for failed only. Trigger.dev's is also true for a cancelled run, so check isCancelled too where a cancelled run should count as failed.
isSuccess, isCancelled, isQueued, isExecuting, isWaitingThe same names and meanings as Trigger.dev's. isQueued is true for a delayed run too.

Python has the same names in snake case: is_success, is_cancelled and so on.

Idempotency keys#

Trigger.devBok JoyWhat to change
Up to 2,048 characters1 to 128 bytes, and 124 for a batch keyHash a longer key, for example to a 64-character SHA-256 hex digest.
Kept for 30 days by default (idempotencyKeyTTL), then a new run can startThe same from @bokjoy/sdk/trigger, in a run and from a backend. idempotencyKeyTTL takes Trigger.dev's durations, such as "60s", "10m", "2h", "7d" or "1w", from 1 second to 365 days. tasks.trigger from @bokjoy/sdk keeps a key as long as its run, until run retention deletes it.Nothing.
A run that fails releases its key, so the same key starts a new runThe same from @bokjoy/sdk/trigger. The failed run records the run that took its key (released_to). A completed or cancelled run keeps its key until its TTL passes.Nothing.
idempotencyKeys.reset(taskId, key, {scope, parentRunId}) lets the key start a new runThe same, with the same options. From a backend, a key that only triggers inside runs hold needs parentRunId, the run's ID, or the control plane answers 422; Trigger.dev throws there. It calls the control plane with the client's API key (BOKJOY_API_KEY or configure()), from a backend or a run.Set BOKJOY_API_KEY where a task resets a key.
A trigger's handle names the run it startedAn in-task trigger's handle names the first run its key started. runs.retrieve and runs.poll from @bokjoy/sdk/trigger read it as the run the key moved to, after a failed run gave the key up.Nothing.
A reused key returns the original run, marked isCached, whatever the payloadThe same from @bokjoy/sdk/trigger and TriggerClient, batch items included. From @bokjoy/sdk, a different payload, placement, machine or queue is a ConflictError. In both, a key that already names a run of another task is a ConflictError, as Bok Joy keys are per environment and Trigger.dev's per task.Import from @bokjoy/sdk/trigger. Never reuse a key across tasks.
idempotencyKeys.create() scopes a key to the parent run, an attempt, or makes it globalA key is scoped to its environment. idempotencyKeys.create() makes the same SHA-256 key from the same scope. Inside a run, tasks.trigger from @bokjoy/sdk/trigger uses a key of exactly 64 characters, as every made key is, as it is: it starts one child across the environment, as in Trigger.dev. Any other key is scoped to the parent run. A wait makes it in the run's scope, as Trigger.dev does, so a child that completed is never started again by the parent's retry.Nothing.

Holding a key as Trigger.dev does needs a control plane and worker agents from the release that added it. Under older ones, a keyed trigger and every wait for children fail with an error that says to upgrade, before anything starts, and a trigger from a backend with a key gets a ValidationError that names the field the control plane does not take.

Options Bok Joy refuses#

Bok Joy refuses these trigger options by name, with a ValidationError, rather than ignore them:

Trigger.dev optionWhy Bok Joy refuses itWhat to do
ttlNo time-to-liveRemove it.
maxAttemptsAttempts are part of the task's definitionSet retry: { maxAttempts } on the task, or max_attempts in the manifest.
priorityNo prioritiesRemove it.
versionRuns use the environment's current deploymentPromote the deployment you want.

maxDuration and region are refused too, as unknown options. A run's longest attempt is its task's maxDuration. idempotencyKey, idempotencyKeyTTL and machine carry over unchanged, and so do queue and concurrencyKey, as below. metadata carries over from a backend, batch items included: it is the run's first metadata, which metadata.current() reads inside the run (not in a workflow, whose attempts rebuild their metadata as they replay), and at most 64 KiB. A trigger inside a run carries idempotencyKeyTTL and concurrencyKey too, and delay and debounce, and refuses the same options, queue, metadata, and maxDuration, region, lockToVersion and payloadType by name, before any child starts.

Delays and debounces#

delay, debounce and runs.reschedule carry over, from a backend and inside a run. See Start a run later and Debounce triggers.

Trigger.devBok JoyWhat to change
delay: '1h', a Date, or an ISO 8601 timeThe same, with the same duration unitsNothing.
A delay it cannot read starts the run at once, with no errorA ValidationError, and no run startsFix the delay the error names.
No latest timeAt most the end of year 9999Nothing.
runs.reschedule on a run that is not delayed is a 400A ConflictError (409)Catch ConflictError if you reschedule runs that may have started.
debounce: { key, delay, mode, maxDelay }, its key scoped to the environment and the taskThe same. Python takes max_delay.Nothing.
An empty debounce keyRefused: a key is 1 to 512 charactersUse a real key.
A trigger inside a run that a debounce folds into a run that already waits returns that run's IDIt returns the ID it made for the child, at once, before the control plane answers. That ID then names the run it joined: runs.retrieve, runs.cancel and every other call read that run with it, and its run page lists it under "Also returned as".Nothing, unless you compare IDs: two handles from one debounce can hold different IDs for the same run. Compare runs.retrieve(id).id.
delay and debounce on triggerAndWait and batchTriggerAndWait inside a runNot yet: refused by nameTrigger the child with trigger, then wait for it another way, such as a workflow sleep.
DELAYED runs take no concurrency slotThe sameNothing.
A trigger folded into a debounced run records no idempotency key, so sent again with its key it counts againThe sameNothing.
A delayed run's idempotencyKeyTTL counts from the trigger, not from when the run startsThe same: a delay longer than the TTL frees the key before the run startsNothing.
idempotencyKeys.reset on the key of the trigger that started a debounced runThe same: the run keeps waiting, and the same trigger again joins it and counts againNothing.
A debounced trigger whose delay has passed is refusedThe same from a backend. Inside a run, ctx.trigger refuses it at the call, by the worker's clock, because it returns the child's ID at once. One whose delay passes after the call starts at once, or joins the run that waits for its key.Nothing.
A delayed run runs the version deployed when it starts, unless triggered with lockToVersionA run runs the deployment it was triggered with, however long its delay: the environment's current one from a backend, its parent's inside a run. A deploy during the delay does not change the code it runs.To run newer code, cancel the run that waits and trigger it again after the deploy.

Tags and run lists#

Run tags and runs.list carry over, from a backend and inside a run. Import runs from @bokjoy/sdk/trigger to keep Trigger.dev's statuses, taskIdentifier and pages. See Tag runs and List runs.

import { runs, tasks } from '@trigger.dev/sdk'; await tasks.trigger('reports.build', { orgId }, {  idempotencyKey: `report-${orgId}-${month}`,  tags: [`org_${orgId}`, 'monthly'],}); const page = await runs.list({ taskIdentifier: 'reports.build', tag: `org_${orgId}`, limit: 1 });const latest = page.data?.[0];const { metadata } = await runs.retrieve(latest.id); const busy = await runs.list({ status: 'EXECUTING', period: '30m', limit: 50 });
Trigger.devBok JoyWhat to change
tags on trigger, triggerAndWait, and each item of batchTrigger and batchTriggerAndWait: up to 10 per run, each 1 to 128 charactersThe same, from a backend and inside a runNothing.
A tag given twiceKept once, where it first appearsNothing.
A repeated idempotencyKey returns the original runThe same, with the original run's tags, whatever tags the repeat namesNothing.
tags.add(tags) inside a run. Past 10 tags in all it logs an error and ignores the new tags.The same. Outside a run it does nothing.Nothing.
ctx.run.tagsThe run's tags when the attempt started. Tags tags.add adds show from the next attempt on.Nothing.
runs.list({ status, taskIdentifier, tag, from, to, period, limit, after, before })The same, with a list matching any of its values. Await it for a page with data, pagination, hasNextPage() and getNextPage(), or for await it for every run.Nothing.
limit: 25 by default, at most 100The sameNothing.
status values PENDING_VERSION, DEQUEUED, REATTEMPTING, FROZEN, CRASHED, SYSTEM_FAILURE, TIMED_OUT, EXPIRED and INTERRUPTEDAccepted, and they match no run: Bok Joy's runs are never in those states. A list that names only those is empty, and sends no request. EXECUTING matches every running run, and FAILED every failed one, crashed or timed out.Nothing.
The version, schedule, bulkAction, batch, region, machine, queue and error filtersRefused by name with a ValidationErrorFilter by task, tag, status and time.
isTesttrue lists the runs started from the console's Test dialog, false every other runNothing.
envAccepted and ignored: an API key lists its own environmentNothing.
runs.list(projectRef, params), across a project's environmentsRefused with a ValidationErrorList each environment with its own key.
A tag with a comma in itCannot be filtered on: refused with a ValidationErrorUse tags without commas where you list by them.
createdAt, updatedAt, startedAt, finishedAt and delayedUntil are Date objectsRFC 3339 strings, in runs.list and runs.retrieveWrap them, as in new Date(run.createdAt).
costInCents, baseCostInCents, durationMsAlways 0Do not rely on them.
A run ID starts with run_A UUIDNothing, unless your code checks the prefix.
runs.retrieve(id).metadataThe same: what the run set with metadata, or undefined when it set nothingNothing.
List items carry no payload or outputThe same: no payload, output or error. runs.retrieve has them.Nothing.
toExclusive: a run created exactly at to is left outAdd a millisecond to include it.
period with fromRefused with a ValidationError, rather than one of them winningGive one of them.
tag: []No tag filter: every runLeave tag out, or name at least one.
tags.add and ctx.run.tags in lifecycle hooksThe same: hooks see and tag the run they belong toNothing.
Hook runs in runs.listLeft out, unless source: 'hook' is passed to the Bok Joy clientNothing.
A debounced trigger in trailing mode with tags: []Keeps the run's tags. Only a trigger that names a tag replaces them.Name the tags you want, or leave them.
run.tags on the runThe same, in runs.retrieve and every page of runs.listNothing.

Tagging inside a run needs a control plane and worker agents from the release that added tags. Under older ones, tags.add and every trigger with tags inside a run throw, rather than leave the run untagged.

Queues and concurrency limits#

A task's queue and Trigger.dev's queue() carry over: the same name and concurrencyLimit, with the same per-environment limit. The queue trigger option names a declared queue, as in v4, and concurrencyKey applies the limit per key. See Queues and concurrency limits.

Trigger.devBok JoyWhat to change
queue: { concurrencyLimit: 10 } on task()The same on a task() in build.dirs, and "queue": {"concurrencyLimit": 10} in a definition you writeNothing for a discovered task.
queue({ name, concurrencyLimit }) from @trigger.dev/sdkqueue({ name, concurrencyLimit }) from @bokjoy/sdk or @bokjoy/sdk/trigger. In Python, pass queue={"name": ..., "concurrencyLimit": ...}.The import.
Tasks that give one queue different limits: the first wins, with a warningThe deploy is refusedGive every task the same limit.
A trigger's queue names a queue no version declares, and the run waitsA ValidationError, and no run startsName only declared queues.
concurrencyLimit: 0, and pausing or overriding a queueNot supported. A limit is 1 to 100,000.Lower the limit and deploy.
concurrencyKey on a triggerThe same option: the queue's limit applies per keyNothing.
A short wait.for keeps its slot; longer waits, triggerAndWait and batchTriggerAndWait release itThe same rule, for sleeps, waits for children and event waitsNothing.

Scheduled tasks#

A schedules.task keeps its code. Deploy registers its cron as the task's schedule, and schedules your backend creates keep their calls. See Schedules.

import { schedules } from '@trigger.dev/sdk'; export const digest = schedules.task({  id: 'reports.digest',  cron: { pattern: '0 6 * * *', timezone: 'America/Denver' },  run: async (payload) => {    // payload.timestamp is a Date  },});
Trigger.devBok JoyWhat to change
schedules.task({ id, cron, run })The same, in a folder of build.dirsThe import.
cron: '0 * * * *' or { pattern, timezone, environments }The sameNothing. Deploy writes schedule: {cron, timezone, environments}, with PRODUCTION, STAGING, DEVELOPMENT and PREVIEW as prod, staging, dev and preview.
A declared schedule without environments fires in every environmentIt fires in prod only. This is on purpose: staging and previews are long-lived and run against real services.Name environments: ['PRODUCTION', 'STAGING'] on each schedule that should fire in staging too, and add 'PREVIEW' for previews.
A declared schedule cannot be pausedschedules.deactivate pauses either kind, and the pause survives deploysNothing.
A tick while the previous run is unfinished queues another runThe tick is skipped, and the skip names the unfinished runExpect skipped ticks when a run outlasts its interval.
Schedules made in the dashboard or with schedules.create live in Trigger.devBok Joy cannot read themExport them and run the schedule import script.
schedules.create, retrieve, list, update, activate, deactivate, delThe same names. Python has them in snake case, with delete for del.The import.
A deduplicationKey is unique in the projectUnique in the environmentNothing. The same key in two environments names two schedules.
timestamp, lastTimestamp and upcoming in the payload are Date objectsThe same in a schedules.task. A plain handler gets RFC 3339 strings in UTC.Nothing.

Realtime in the browser#

auth.createPublicToken and useRealtimeRun carry over, with the same shapes. See Realtime in the browser.

Trigger.devBok JoyWhat to change
import { auth } from '@trigger.dev/sdk'import { auth } from '@bokjoy/sdk'. In Python, from bokjoy import auth and auth.create_public_token.The import.
auth.createPublicToken({ scopes: { read: { runs: [runId] } }, expirationTime: '1h' })The same call, returning a bjp_... tokenNothing.
A token lasts 15 minutes by default, and up to 30 days15 minutes by default, and 24 hours at mostMint a new token for a page that stays open longer.
read scopes for tasks, tags and batch, and runs: trueOnly read: { runs: [...] }, at most 32 runs. The others are refused with a ValidationError.Name the runs.
useRealtimeRun(runId, { accessToken, enabled }) from @trigger.dev/react-hooksuseRealtimeRun(runId, { accessToken, enabled }) from @bokjoy/sdk/reactThe import. Add baseURL when the control plane is not https://api.bokjoy.dev.
run.status is QUEUED, EXECUTING, COMPLETED and so onThe same upper case values. CRASHED, SYSTEM_FAILURE and TIMED_OUT come as FAILED.Nothing.
run.taskIdentifier, run.metadata, run.output, run.isCompleted and the other flagsThe same names and meaningsNothing.
run.payload, run.error, run.tags, and useRealtimeRunsWithTag, useRealtimeStream and the other hooksNot sent to the browser, and no other hooksRead those on your server.

Waiting on child runs#

Inside a task, triggerAndWait and batchTriggerAndWait keep Trigger.dev's results and .unwrap(). A task deploy finds is a plain task, and there a wait holds the task's process until its children finish, as on self-hosted Trigger.dev. The code before the wait runs once, so this task runs as it is, with only its import changed:

import { task } from '@trigger.dev/sdk';import { thumbnail } from './thumbnail'; export const makeThumbnails = task({  id: 'album.thumbnails',  run: async ({ imageIds }) => {    const { runs } = await thumbnail.batchTriggerAndWait(      imageIds.map((imageId) => ({ payload: { imageId } })),    );    return runs.filter((run) => run.ok).map((run) => run.output);  },});
Trigger.devBok Joy, in a plain taskWhat to change
A self-hosted task keeps its machine and queue slots while it waits, so a child in a full queue never startsThe task gives back its machine, queue and project slots while it waits, as Trigger.dev Cloud does when it checkpoints a run. A child in the parent's own concurrencyLimit: 1 queue starts. When the children finish, the task continues once its queue has room.Nothing.
maxDuration leaves time spent waiting outThe same. A task may be held for 24 hours in all. Past that its attempt stops and is not retried.Nothing.
A task that crashes mid-wait runs again from the topThe same. A child started with an idempotencyKey is not started again: the retry waits on it.Key each child that must run once.
Up to 1,000 items in a batchTriggerAndWaitThe same. An attempt starts at most 1,000 children in all, waits included.Split longer lists across attempts.

Held waits are for Node tasks deployed with an sdk folder that has them. A private worker needs an agent from the same release, or a wait throws and names the upgrade. Python tasks wait only as workflows. In a plain task has the rest.

Waiting as a workflow#

Name a task in build.workflows, beside build.dirs, and deploy registers it as a workflow. It keeps no process while it waits:

JavaScript
import { idempotencyKeys, task } from '@bokjoy/sdk/trigger';import { thumbnail } from './thumbnail'; export const makeThumbnails = task({  id: 'album.thumbnails',  run: async ({ imageIds }) => {    const { runs } = await thumbnail.batchTriggerAndWait(      // Sorted, so a replay builds the same batch.      [...imageIds].sort().map((imageId) => ({ payload: { imageId } })),      { idempotencyKey: await idempotencyKeys.create('thumbnails') },    );    return runs.filter((run) => run.ok).map((run) => run.output);  },}); // manifest.json// "build": {"dirs": ["src/trigger"], "workflows": ["album.thumbnails"]}

A workflow's attempt ends at each wait and frees its machine. When the children finish, a new attempt runs the task from the top, and each wait it has passed returns its recorded results. So a task with one wait runs in two attempts, and a task with two waits runs in three.

  • Code before a wait runs again in each later attempt. With one wait, it runs twice.
  • A catch around a wait never sees the wait. An error reporter in it runs only for a real error.
  • A finally around a wait runs once in each later attempt that gets past it. It never runs in the attempt that stops at the wait. Around the only wait, it runs once.
  • Open handles do not keep an attempt running. A database client or a timer is left open when the attempt ends at a wait.

A task with two waits:

JavaScript
export const unpause = task({  id: 'inventory.unpause',  run: async ({ orgId }) => {    logger.info('start'); // attempts 1, 2 and 3    try {      await tasks.triggerAndWait('inventory.gate', { orgId }); // attempt 1 ends here    } finally {      logger.info('gate checked'); // attempts 2 and 3    }    await tasks.triggerAndWait('inventory.rebuild', { orgId }); // attempt 2 ends here    logger.info('done'); // attempt 3  },});

Deploy checks build.workflows. Each entry must name a task that build.dirs finds, once. A task the manifest's own tasks define sets "kind": "workflow" on its entry instead. A wait's child must be a task, so a task in build.workflows cannot be the child of a wait.

Trigger.devBok JoyWhat to change
triggerAndWait and batchTriggerAndWait in any taskThe same, in a task registered as a workflow. Bok Joy's own are ctx.triggerAndWait and ctx.batchTriggerAndWait.Add the task's ID to build.workflows. In Python, await ctx.trigger_and_wait(...) and await ctx.batch_trigger_and_wait(...).
The task carries on from the waitThe attempt ends at the wait, and the run replays from the top when the children finish. Code before the wait runs again.Move side effects before a wait into child tasks.
Waits cannot run side by side, as in Promise.allOne wait at a time. Two at once fail the attempt.Await each wait before the next, or put the children in one batch.
NoneA replay checks each wait against history. With its default key, a wait replays only unchanged, and a changed input or list fails the attempt with an error that says to pass an idempotencyKey. With an explicit key, the recorded results stand, marked drifted: true, a batch's result adds the recorded items, and the run records a replay.drift event.Sort a list you read from a database before a batch over it. Pass an idempotencyKey per wait in loops, and per batch over data that can change between attempts. If you pair runs with your own list, pair them with items when drifted is set. Start children for new items in a new step with a new key.
An idempotencyKeys.create key names one run of a task in the environmentThe same: a wait with a made key waits on the child of that task any run in the environment started with it. A batch key, made or not, gives each item a key made in the run's scope from it and the item's index, as on Trigger.dev, so each run's batch starts its own children. The child belongs to the run that started it. A retry from failure makes its 'run' keys from the failed run's ID (ctx.firstRunId), so it finds the children that run started.Build your own run keys from ctx.firstRunId, not ctx.run.id, to keep them in a retry from failure.
When the parent retries, a wait whose child failed starts a new childThe same: on the workflow's next attempt, the steps before the first wait whose child failed replay, and that wait and every later step run again. A later wait under a key whose child completed waits on that child again. One without a key starts a new child, as every unkeyed child does when a Trigger.dev task retries.Key each wait whose child must run once, as on Trigger.dev.
A key made with scope: 'attempt' names a new child on each attemptA wait refuses it, since the workflow replays its steps on a retry and the key would no longer match. trigger and batchTrigger take it.Make the key with the run's scope, the default, or global.
{ok: true, id, taskIdentifier, output} or {ok: false, id, taskIdentifier, error}, with .unwrap() and SubtaskUnwrapError. await triggerAndWait(...).unwrap() gives the outputThe same. error is {name, message}, with the name RunFailedError or RunCancelledError.Read the reason from error.message.
batchTriggerAndWait gives {id, runs}The same. id names the batch by its children; there is no batch to read with it.Nothing, unless you read the batch by its ID.
A batch takes up to 1,000 itemsThe same: 1 to 1,000 items. Their payloads are at most 10 MiB together, and each child counts toward the run tree's limit of 10,000 triggered and batched runs by default.Split a batch whose payloads are larger into several steps, each with its own key.
Each item takes the trigger optionsEach item is {payload, options}, and options takes idempotencyKey, idempotencyKeyTTL, machine and concurrencyKey. The keyed items of one wait share a TTL: set it on the batch.Remove the other item options.

Inside a task, wait from the task. The tasks client from @bokjoy/sdk is for your backend.

Lifecycle hooks#

onStartAttempt, onStart, onSuccess, onFailure, onComplete and onCancel carry over, on a task and as tasks.onX for every task, with the same parameters. The big difference is that failure hooks also run after a crash or a timeout, in a process of their own. See Lifecycle hooks.

import { tasks } from '@trigger.dev/sdk';import { alerts } from '../lib/alerts'; tasks.onFailure('alerts', async ({ ctx, error }) => {  await alerts.send(`${ctx.task.id} run ${ctx.run.id} failed: ${error.message}`);});
Trigger.devBok JoyWhat to change
The six hooks as options of task(), schemaTask() and schedules.task()The sameThe import.
tasks.onFailure(fn) and the others, in init.ts, in trigger.config.ts or anywhereThe same calls, in an init file or a task file in build.dirsMove hooks from trigger.config.ts into init.ts.
onFailure does not fire for a crashed run or a system failureonFailure and onComplete run after every failure: a crash, an out-of-memory kill, a maxDuration timeout and a lost worker tooExpect failure hooks for runs that used to end without them.
Every hook runs in the run's processonFailure, onComplete after a failure, and onCancel run in a new process once the run has endedRead what a failure hook needs from payload, ctx and error, or set it up in init.ts. A closure or a variable the run set is not there.
onCancel runs while the run is still executing, with up to 30 seconds to await runPromiseonCancel runs after the run's process has been ended, and runPromise is already settledClean up after the run in onCancel. It cannot stop work in progress.
onFailure gets the error object the task threwA copy rebuilt in the hook's process: the standard error classes, AbortTaskRunError, the name, message, stack and the error's codes and statuses such as code and status. Other fields, which can hold request headers or row values, are left out. Another class arrives as an Error with its nameCheck error.name rather than instanceof for your own error classes, and error.code rather than nested fields.
A hook runs onceA hook runs at least once: a hook run whose worker is lost runs its hooks againMake hooks safe to run twice, for example by keying what they send with ctx.run.id.
A hook registered only when an environment variable is setDeploy finds hooks without your variables, so it misses that one, and it never runs after a failure or cancelRegister hooks every time, and check the variable inside the hook.
Errors thrown in onSuccess, onFailure and onComplete are ignored, and shown in the dashboardThe same: shown in the run's Lifecycle hooks panelNothing.
onWait, onResume, catchError, middleware, locals, and the deprecated init, cleanup and handleErrorNot yet. Deploy refuses each with its file and line.Remove them. Run setup at the top of init.ts.

Not in Bok Joy yet#

  • batchTriggerAndWait from a backend, as above.
  • Batches across tasks. batch.triggerAndWait and batch.triggerByTaskAndWait, with a task per item. A Bok Joy batch starts children of one task, so run one batch per task.
  • onWait, onResume, catchError, middleware and locals, on a task or in init.ts, and the deprecated init, cleanup and handleError. The other lifecycle hooks carry over.
  • TTLs.

Deploy refuses each of these with the file and line, and a task that calls one fails with an error that names it, so nothing runs without the behavior it asked for.

Deploying a Trigger.dev project#

A project laid out for Trigger.dev deploys without moving files. Your trigger.config.ts settings move into the manifest, and the tasks keep their imports of ../../lib, @/ paths and JSON. See Bundle a TypeScript project and Find tasks in folders.

trigger.config.tsBok Joy manifestWhat to change
dirs: ['./src/trigger']build.dirs: ["src/trigger"]Nothing. Deploy finds the tasks each file exports.
Nonebuild.workflows: ["album.thumbnails"]Optional. List a task that should wait as a workflow, freeing its machine. See Waiting as a workflow.
src/trigger/init.tsLoaded before every task, in each folder of build.dirs, and before a task's failure hooksNothing. Keep setup such as Sentry.init() and tasks.onFailure there.
import ... from '@trigger.dev/sdk'import ... from '@bokjoy/sdk/trigger'The import. Deploy refuses a file that still imports @trigger.dev/*, with its line.
build.externalbuild.externalNothing.
prismaExtension({ schema, mode: 'legacy' })build.prisma: {schema, mode: "legacy"}Nothing. Bok Joy generates the client in the image, for the image's platform.
legacy-peer-deps=true in .npmrcdependencies.node.legacy_peer_deps: trueAdd it beside your lockfile.
aptGet({ packages })dependencies.aptNothing. See System packages.
ffmpeg()dependencies.apt: ["ffmpeg"]Debian's ffmpeg, on PATH. Set FFMPEG_PATH and FFPROBE_PATH as variables if your code reads them. ffmpeg({ version }) has no equivalent.
puppeteer()dependencies.apt: ["chromium", "fonts-liberation"]Launch /usr/bin/chromium with --no-sandbox, for example by setting the variable PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium.
syncEnvVars(...)NoneSet each variable with the CLI, as below.
maxDurationdefaults.timeout_ms, in milliseconds, up to 24 hoursMultiply by 1,000. A task's own maxDuration replaces it. Without either, an attempt gets 30 seconds.
retries.defaultdefaults.retry, with the same fieldsMove it. A task's own retry replaces it as a whole. Without either, a task gets 3 attempts.
onStartAttempt, onSuccess, onFailure and the other hookstasks.onStartAttempt and the others in init.tsMove them into init.ts, as tasks.onFailure(fn) and so on.
runtime: 'node'"runtime": "node" on each taskNothing.
projectNoneRemove it. Each Bok Joy project has its own environments, and deploy names the project.

Bok Joy has no syncEnvVars. Set the variables once per environment from a shell where they are set, reading each value from standard input:

Terminal
for name in SIMPHONY_SFTP_HOST SIMPHONY_SFTP_USER SIMPHONY_SFTP_PASSWORD; do  printenv "$name" > /dev/null || continue  printenv "$name" | durable-compute variables set "$name" --env proddone

printenv fails for a name that is not set, so the loop skips it, as syncEnvVars skips a missing value. Without that check, variables set would store an empty value. See Variables.

Convert a project with the codemod#

The Bok Joy checkout has a codemod for a Trigger.dev v4 project. Run it with --dry-run first, and read its report:

Terminal
node /path/to/bokjoy/scripts/trigger-codemod/index.mjs <project root> --dry-runnode /path/to/bokjoy/scripts/trigger-codemod/index.mjs <project root>
  • It rewrites the imports in every .ts, .tsx, .js, .jsx, .mjs and .cjs file. @trigger.dev/sdk and @trigger.dev/sdk/v3 become @bokjoy/sdk/trigger, and @trigger.dev/react-hooks becomes @bokjoy/sdk/react. Imports, re-exports, import(), require() and jest or vitest mocks all change.
  • It writes the manifest. It runs trigger.config.ts and writes bokjoy.manifest.json beside it, with the settings mapped as the table above maps them. It never changes the config. Delete it once the move is done.
  • It copies the SDK from the checkout into sdk/node in your project, which deploy bundles. Pass --no-vendor-sdk to skip it.
  • It reports what it could not convert, such as an extension with no equivalent or a name the SDK does not export. It also lists code that deploys but behaves differently, such as a batch over 1,000 items. --json <file> writes the report as JSON too.

It never edits package.json, the lockfile or tsconfig.json. The config runs in a child Node process that can read only your project and the codemod, and cannot write files, open a network connection or start a process.

Import dashboard schedules#

Schedules made in Trigger.dev's dashboard, or with schedules.create, live only in Trigger.dev. The schedule import script in the checkout makes them again on Bok Joy. First export them, once per Trigger.dev environment: save the answer of schedules.list() as a JSON file. The script never calls Trigger.dev.

Terminal
# A dry run, the default: it reads the environment's schedules, prints the plan and writes nothing.BOKJOY_API_URL=https://api.bokjoy.dev BOKJOY_API_KEY=bjk_staging_... \  node /path/to/bokjoy/scripts/import-trigger-schedules/index.mjs staging-schedules.json --trigger-env STAGING# The same with --apply makes the changes.BOKJOY_API_URL=https://api.bokjoy.dev BOKJOY_API_KEY=bjk_staging_... \  node /path/to/bokjoy/scripts/import-trigger-schedules/index.mjs staging-schedules.json --trigger-env STAGING --apply
  • The schedules go to the API key's environment. Deploy first: each schedule's task must be in the environment's current deployment.
  • Running it again changes nothing twice. Each schedule keeps its cron, time zone and external ID, and its deduplication key, or trigger:<schedule id> without one. A schedule whose cron, time zone, task or external ID changed is updated in place. --task-map old=new renames a task.
  • Paused schedules are skipped, unless you pass --include-inactive: then each is made and paused at once. A schedule you paused on Bok Joy stays paused, unless you pass --sync-active.
  • Declared schedules are skipped, since deploy makes them from your code.
  • It checks before it sends. A schedule Bok Joy would refuse is skipped and reported: a cron with seconds, a nickname such as @hourly, or L, W, # or ?, and a key or external ID over 128 bytes. An import that would take the environment past 1,000 schedules sends nothing.
  • A schedule Bok Joy refuses anyway, such as one whose task the current deployment lacks, is reported. The rest still import, and the script exits with 1.

Defining tasks#

A task file keeps its definitions. Change the import, and name the folder in build.dirs:

import { task } from '@trigger.dev/sdk'; export const sendEmail = task({  id: 'email.send',  machine: 'small-1x',  retry: { maxAttempts: 5 },  run: async (payload, { ctx }) => {    // ...  },});
Trigger.devBok JoyWhat to change
task({ id, run, machine, maxDuration, retry, queue })The sameThe import. See Queues and concurrency limits.
schemaTask({ id, schema, run })The same, with zod or any parserThe import.
schedules.task({ id, cron, run })The sameThe import. See Scheduled tasks.
retry: { maxAttempts, factor, minTimeoutInMs, maxTimeoutInMs, randomize }The same fields, defaults and backoffNothing. Python's define_task takes the fields in snake case.
maxDuration, in secondsThe same, up to 24 hoursNothing.
A run past maxDuration fails without a retryThe same: an attempt whose handler runs past its maxDuration is stopped, and the run fails without a retryNothing.
A thrown error is not retried unless retries.default or the task's retry is setA failed attempt retries until its attempts are used (3 unless set), with Trigger.dev's backoffSet retry: { maxAttempts: 1 } on a task that must never retry.
throw new AbortTaskRunError(message)The same, imported from @bokjoy/sdk/trigger. In Python, from bokjoy import AbortTaskRunError.The import. An error named AbortTaskRunError from Trigger.dev's SDK also works.
retry: { outOfMemory: { machine: 'large-1x' } }The same: an attempt that runs out of memory moves the run to that machine, with Trigger.dev's backoff, counting against maxAttempts. Without it, the run fails at once. See Out of memory.Nothing.
throw new OutOfMemoryError()The same, imported from @bokjoy/sdk/trigger. In Python, from bokjoy import OutOfMemoryError, and Python's MemoryError counts too. Another Python library's error of that name, such as the Redis client's, does not.The import. An error named OutOfMemoryError from Trigger.dev's SDK also works.
An attempt killed with SIGKILL counts as out of memoryOnly an attempt the kernel stopped for its own memory counts. An attempt stopped because another on its machine used more than it reserved, and a kill -9 for another reason, are ordinary failures and are retried. When Bok Joy is less sure, such as when a process the task started was stopped, the run still moves to retry.outOfMemory.machine but never fails without one. See How it is detected.Nothing. A task that ends a child process for memory itself should throw OutOfMemoryError.
ctx.machine, with name, cpu and memoryThe same, with Trigger.dev's names, plus cpuMillis and memoryMibNothing.
run(payload, { ctx }), with ctx.run, ctx.task, ctx.attempt and ctx.environmentThe same fields. ctx.environment has the environment's slug, its type, such as PRODUCTION, and Bok Joy's kind, such as production. Bok Joy's own context is ctx.bokjoy.Nothing.
A Date in a task's output arrives as a DateIt arrives as its ISO 8601 string, as JSON.stringify writes itWrap it, as in new Date(run.output.sentAt).
metadata.set, get, current, increment, decrement, appendThe same, kept with the run. A retry reads what earlier attempts stored. Values go as JSON: an undefined field is left out and a Date becomes its ISO string.Nothing. del, replace, remove and streams are refused.
logger.info and its levelsThe same, one line per call in the attempt's logsNothing.
tags.add and ctx.run.tagsThe same. See Tags and run lists.Nothing.
tasks.trigger, myTask.trigger and batchTrigger inside a runThe same, and the child is linked to the run. Payloads go as JSON, as Trigger.dev sends them: an undefined field is left out and a Date becomes its ISO string. NaN, Infinity, a BigInt or a cycle fails the trigger. A batch starts all of its children or none.Nothing, apart from the options refused above.
triggerAndWait and batchTriggerAndWait inside a runThe same results. In a plain task the wait holds the task until its children finish, as on self-hosted Trigger.dev. In a task registered as a workflow the attempt ends at the wait.Nothing. See Waiting on child runs.
onStartAttempt, onStart, onSuccess, onFailure, onComplete, onCancelThe same. onFailure, onComplete after a failure, and onCancel run in a process of their own.Nothing, apart from what Lifecycle hooks lists.
onWait, onResume, catchError, middleware, locals, init, cleanup, handleErrorNot yet. Deploy refuses each with its file and line.Remove them.

Tasks has the full mapping of options to manifest fields. A task can also be a plain exported function registered by hand in the manifest, with the same retry and compute.timeout_ms in its definition, and both kinds can sit in one project.

Long waits belong in a workflow, whose sleeps, event waits and waits for children hold no worker.