@mastra/core
Version:
2,080 lines • 80 kB
JavaScript
let zod_v4 = require("zod/v4");
// src/background-tasks/workflow-id.ts
/**
* Workflow id used by the bg-task workflow registered on Mastra.
* Double-underscore prefix marks it as internal — same convention as
* `__batch-scoring-traces`.
*
* Lives in its own file (separate from `./workflow`) so `manager.ts` can
* reference the id without statically pulling in `../workflows/evented`,
* which would create a circular import via `agent → background-tasks →
* workflow → evented → workflows/index → agent`.
*/
const BACKGROUND_TASK_WORKFLOW_ID = "__background-task";
// src/background-tasks/manager.ts
const TOPIC_DISPATCH = "background-tasks";
const TOPIC_RESULT = "background-tasks-result";
const WORKER_GROUP = "background-task-workers";
const SHUTDOWN_GRACE_PERIOD_MS = 5e3;
const SHUTDOWN_ABORT_MESSAGE = "Background task manager is shutting down";
const TASK_OWNERSHIP_LOST_MESSAGE = "Background task execution ownership was taken over by another worker";
function workflowRunError(result) {
if (result.error !== void 0) return result.error;
if (result.tripwire?.reason) return new Error(result.tripwire.reason);
return /* @__PURE__ */ new Error(`Background task workflow run ended with status '${result.status}'`);
}
function toTaskError(err) {
if (err && typeof err === "object" && typeof err.message === "string") {
const { message, stack } = err;
return typeof stack === "string" ? {
message,
stack
} : { message };
}
return { message: String(err) };
}
/** Pending rows each lapsed-pin sweep reads; later pages are read on later ticks. */
const PIN_SWEEP_PAGE_SIZE = 100;
/** Test-only lower lease minimum; only ever lowers the default 3s. Read per manager, not at import. */
function minLeaseOverride() {
const value = Number(process.env.MASTRA_BACKGROUND_TASKS_MIN_LEASE_MS);
return Number.isFinite(value) && value > 0 && value < 3e3 ? value : void 0;
}
/**
* Runs, persists, and recovers background tasks for one Mastra process.
*
* Several managers (processes or replicas) may share one storage backend.
* Execution is owned through a lease persisted on each task record:
*
* - Identity: each manager has a random `ownerId` (`workerId`), so a restarted
* process is a new owner.
* - Acquisition: `handleDispatch` claims a task with a compare-and-set on the
* observed status/owner/lease, writing `ownerId` and
* `leaseExpiresAt = now + leaseDurationMs`. Losers of a race skip the task.
* - Renewal: the heartbeat renews owned leases every `leaseDurationMs / 3`,
* fenced on `running` + this owner. Workflow terminal writes carry the same
* fence, so a superseded owner cannot commit results.
* - Expiry and adoption: `recoverStaleTasks` only reclaims a `running` task
* once its lease has expired (or was released on shutdown), fenced on the
* owner/lease it read so one manager wins. It re-runs when the earliest live
* lease lapses. `restart()` is the one deliberate takeover of a live lease.
* - Loss: a failed renewal aborts the local run's signal when another owner
* holds the task or it was cancelled.
*
* Guarantee: at most one owner can commit a task's state at a time, except
* for the shutdown rollback of an interrupted resume in `handleResume`, which is
* conditional on status only. The tool
* itself may still run more than once (stalled owner past its lease, crash
* before the result is saved, explicit restart), so external side effects need
* idempotency. Assumes storage applies `updateTask` conditions atomically and
* that clock skew between managers is well below `leaseDurationMs`, since
* `leaseExpiresAt` is written by the owner's clock and read by others'.
*/
var BackgroundTaskManager = class {
pubsub;
workerId = globalThis.crypto.randomUUID();
processAffineDispatchTopic = `${TOPIC_DISPATCH}:${this.workerId}`;
config;
#mastra;
/** @internal — read by the workflow-engine step bodies in workflow.ts */
taskContexts = /* @__PURE__ */ new Map();
staticExecutors = /* @__PURE__ */ new Map();
/** @internal — read by the workflow-engine step bodies in workflow.ts */
activeAbortControllers = /* @__PURE__ */ new Map();
localReservations = /* @__PURE__ */ new Map();
localPendingTaskIds = /* @__PURE__ */ new Set();
localPendingResumes = /* @__PURE__ */ new Map();
inFlightPortableResumes = /* @__PURE__ */ new Map();
drainingPending = false;
ownedLeases = /* @__PURE__ */ new Set();
pinnedPendingLeases = /* @__PURE__ */ new Set();
heartbeatInterval;
#timingFloorMs;
staleRecoveryTimeout;
pinSweepInterval;
sweepingPins = false;
pinSweepPage = 0;
#settlingRuns = /* @__PURE__ */ new Set();
workerCallback;
resultCallback;
shuttingDown = false;
cleanupInterval;
initPromise;
shutdownPromise;
shutdownDeadline;
constructor(config = { enabled: false }) {
const leaseDurationMs = config.leaseDurationMs ?? 3e4;
const minLeaseMs = minLeaseOverride() ?? 3e3;
this.#timingFloorMs = minLeaseMs / 3;
if (!Number.isFinite(leaseDurationMs) || leaseDurationMs < minLeaseMs) throw new Error(`BackgroundTaskManager leaseDurationMs must be a finite number of at least ${minLeaseMs}ms (received: ${leaseDurationMs})`);
for (const [owner, limit] of Object.entries(config.perOwnerConcurrency ?? {})) if (!Number.isFinite(limit) || limit < 1) throw new Error(`BackgroundTaskManager perOwnerConcurrency["${owner}"] must be a finite number of at least 1 (received: ${limit})`);
this.config = {
...config,
globalConcurrency: config.globalConcurrency ?? 10,
perAgentConcurrency: config.perAgentConcurrency ?? 5,
backpressure: config.backpressure ?? "queue",
defaultTimeoutMs: config.defaultTimeoutMs ?? 3e5,
recoverStaleTasksOnStart: config.recoverStaleTasksOnStart ?? true,
leaseDurationMs
};
}
__registerMastra(mastra) {
this.#mastra = mastra;
}
/**
* @internal — execution-lease owner identity for this manager process.
* Persisted when a task is claimed so recovery can distinguish a live owner
* from a dead one, and used by the workflow step bodies to fence their
* terminal writes against a superseded owner.
*/
get ownerId() {
return this.workerId;
}
async getStorage() {
const storage = this.#mastra?.getStorage();
if (!storage) throw new Error("Storage is not initialized");
const bgStore = await storage.getStore("backgroundTasks");
if (!bgStore) throw new Error("Background tasks storage is not available");
return bgStore;
}
async init(pubsub) {
if (this.shuttingDown) throw new Error("BackgroundTaskManager is shutting down, cannot initialize");
if (this.initPromise) return this.initPromise;
this.initPromise = this.#doInit(pubsub);
return this.initPromise;
}
async #doInit(pubsub) {
this.pubsub = pubsub;
const isProducerOnly = this.config.mode === "producer";
this.resultCallback = async (event, ack) => {
if (event.type === "task.completed" || event.type === "task.failed") {
try {
await this.handleResult(event);
} finally {
await ack?.();
}
return;
}
if (event.type === "task.cancelled") {
try {
await this.handleRemoteCancel(event.data.taskId);
} finally {
await ack?.();
}
return;
}
await ack?.();
};
if (!isProducerOnly) {
this.workerCallback = async (event, ack) => {
if (this.shuttingDown) return;
let handled = true;
if (event.type === "task.dispatch" || event.type === "task.restart") handled = await this.handleDispatch(event);
else if (event.type === "task.resume") {
const resuming = this.handleResume(event);
this.#trackSettlingRun(resuming);
handled = await resuming;
} else if (event.type === "task.cancel") this.handleCancel(event);
if (handled) await ack?.();
};
if (this.#mastra) {
const { buildBackgroundTaskWorkflow } = await Promise.resolve().then(() => require("./workflow-ClUOk1U9.cjs"));
const workflow = buildBackgroundTaskWorkflow(this);
if (!this.#mastra.__hasInternalWorkflow("__background-task")) this.#mastra.__registerInternalWorkflow(workflow);
}
await this.pubsub.subscribe(TOPIC_DISPATCH, this.workerCallback, { group: WORKER_GROUP });
await this.pubsub.subscribe(this.processAffineDispatchTopic, this.workerCallback);
if (this.shuttingDown) {
await this.#releaseLateInitSubscriptions([[TOPIC_DISPATCH, this.workerCallback], [this.processAffineDispatchTopic, this.workerCallback]]);
return;
}
if (this.config.recoverStaleTasksOnStart) {
await this.recoverStaleTasks();
this.#startPinSweep();
}
}
await this.pubsub.subscribe(TOPIC_RESULT, this.resultCallback);
if (this.shuttingDown) {
const lateSubscriptions = [];
if (this.workerCallback) {
lateSubscriptions.push([TOPIC_DISPATCH, this.workerCallback]);
lateSubscriptions.push([this.processAffineDispatchTopic, this.workerCallback]);
}
lateSubscriptions.push([TOPIC_RESULT, this.resultCallback]);
await this.#releaseLateInitSubscriptions(lateSubscriptions);
return;
}
const cleanupConfig = this.config.cleanup;
if (cleanupConfig && !this.shuttingDown) {
const intervalMs = cleanupConfig.cleanupIntervalMs ?? 6e4;
this.cleanupInterval = setInterval(() => {
this.cleanup().catch((error) => {
this.#mastra?.getLogger?.()?.warn("Background task cleanup failed:", error);
});
}, intervalMs);
}
if (!this.shuttingDown) this.#startLeaseHeartbeat();
}
/**
* Register per-task hooks (executor, stream emitter, result injector).
* Called internally by createBackgroundTask or directly for advanced usage.
*/
registerTaskContext(taskId, context) {
this.taskContexts.set(taskId, context);
}
/**
* Remove per-task hooks. Called after task reaches terminal state.
*/
deregisterTaskContext(taskId) {
this.taskContexts.delete(taskId);
}
/** @internal — called by the workflow step immediately before executor invocation. */
registerActiveAbortController(taskId, controller) {
if (this.shuttingDown) {
controller.abort(/* @__PURE__ */ new Error(SHUTDOWN_ABORT_MESSAGE));
return false;
}
this.activeAbortControllers.set(taskId, controller);
return true;
}
/** @internal — read by workflow error classification during graceful shutdown. */
isShuttingDown() {
return this.shuttingDown;
}
/**
* Register a tool executor by tool name. Used for cross-process dispatch:
* when a worker in a different process picks up a `task.dispatch` event,
* it has no per-task closure (`taskContexts`) for that taskId, but it can
* resolve the executor by tool name via this registry.
*/
registerStaticExecutor(toolName, executor) {
if (this.staticExecutors.has(toolName)) this.#mastra?.getLogger?.()?.debug?.(`Overwriting existing static executor for tool "${toolName}"`);
this.staticExecutors.set(toolName, executor);
}
/**
* Symmetric to `registerStaticExecutor`. Called when a tool is removed
* from `Mastra`.
*/
unregisterStaticExecutor(toolName) {
this.staticExecutors.delete(toolName);
}
/**
* Look up an executor by tool name. Read by the workflow-step body in
* `workflow.ts:runAttemptStep` as a fallback when no per-task `TaskContext`
* is registered (cross-process path).
*/
getStaticExecutor(toolName) {
return this.staticExecutors.get(toolName);
}
/**
* Enqueue a task for background execution.
* Prefer `createBackgroundTask()` which returns a self-contained handle.
*/
async enqueue(payload, context, options) {
if (this.shuttingDown) throw new Error("BackgroundTaskManager is shutting down, cannot enqueue new tasks");
const pinned = options?.pinToWorker === true;
if (pinned && !context) throw new Error("pinToWorker requires a task context");
if (this.initPromise) await this.initPromise;
const createdAt = /* @__PURE__ */ new Date();
const task = {
id: this.#mastra?.generateId() ?? globalThis.crypto.randomUUID(),
status: "pending",
toolName: payload.toolName,
toolCallId: payload.toolCallId,
args: payload.args,
agentId: payload.agentId,
threadId: payload.threadId,
resourceId: payload.resourceId,
runId: payload.runId,
retryCount: 0,
maxRetries: payload.maxRetries ?? this.config.defaultRetries?.maxRetries ?? 0,
timeoutMs: payload.timeoutMs ?? this.config.defaultTimeoutMs,
createdAt,
...payload.expiresAt ? { expiresAt: payload.expiresAt } : {},
...payload.metadata ? { metadata: payload.metadata } : {},
...pinned ? {
ownerId: this.workerId,
leaseExpiresAt: new Date(createdAt.getTime() + this.config.leaseDurationMs)
} : {}
};
if (context) this.registerTaskContext(task.id, context);
const storage = await this.getStorage();
await storage.createTask(task);
if (pinned) this.pinnedPendingLeases.add(task.id);
if (Boolean(context) ? this.reserveLocalSlot(task) : await this.checkConcurrency(task.agentId)) {
try {
await this.dispatch(task);
} catch (error) {
this.pinnedPendingLeases.delete(task.id);
if (await storage.updateTask(task.id, {
status: "failed",
error: { message: error instanceof Error ? error.message : String(error) },
completedAt: /* @__PURE__ */ new Date(),
...pinned ? {
ownerId: void 0,
leaseExpiresAt: void 0
} : {}
}, { expectedStatus: "pending" })) {
this.releaseLocalSlot(task.id);
this.deregisterTaskContext(task.id);
this.drainPending();
}
throw error;
}
return { task };
}
switch (this.config.backpressure) {
case "reject":
this.pinnedPendingLeases.delete(task.id);
this.deregisterTaskContext(task.id);
await storage.deleteTask(task.id);
throw new Error(`Concurrency limit reached, cannot enqueue task for tool "${task.toolName}"`);
case "fallback-sync":
this.pinnedPendingLeases.delete(task.id);
this.deregisterTaskContext(task.id);
await storage.deleteTask(task.id);
return {
task,
fallbackToSync: true
};
default:
this.localPendingTaskIds.add(task.id);
return { task };
}
}
async cancel(taskId) {
if (this.initPromise) await this.initPromise;
const storage = await this.getStorage();
let task = await storage.getTask(taskId);
if (!task) throw new Error(`Task not found: ${taskId}`);
while (true) {
if (task.status === "completed" || task.status === "failed" || task.status === "cancelled" || task.status === "timed_out") return;
const previousStatus = task.status;
const isProcessAffine = this.taskContexts.has(taskId);
if (!await storage.updateTask(taskId, {
status: "cancelled",
completedAt: /* @__PURE__ */ new Date(),
ownerId: void 0,
leaseExpiresAt: void 0
}, { expectedStatus: previousStatus })) {
task = await storage.getTask(taskId);
if (!task) return;
continue;
}
this.ownedLeases.delete(taskId);
this.pinnedPendingLeases.delete(taskId);
this.localPendingResumes.delete(taskId);
if (previousStatus === "pending") {
this.localPendingTaskIds.delete(taskId);
this.releaseLocalSlot(taskId);
}
if (previousStatus === "running") {
const controller = this.activeAbortControllers.get(taskId);
if (controller) {
controller.abort(/* @__PURE__ */ new Error("Task cancelled"));
this.activeAbortControllers.delete(taskId);
}
}
if (previousStatus === "running" || previousStatus === "suspended") {
if (this.#mastra) try {
await (await this.#mastra.__getInternalWorkflow(BACKGROUND_TASK_WORKFLOW_ID).createRun({ runId: taskId })).cancel();
} catch (err) {
this.#mastra?.getLogger?.()?.warn(`background-task workflow cancel failed for ${taskId}:`, err);
}
}
const cancelledTask = await storage.getTask(taskId);
if (cancelledTask) {
await this.publishLifecycleEvent("task.cancelled", cancelledTask);
try {
await this.config.onTaskCancelled?.(cancelledTask);
} catch (error) {
this.#mastra?.getLogger?.()?.warn(`background-task cancellation callback failed for ${taskId}:`, error);
}
if (previousStatus === "suspended") await this.runLocalExecutionHook(cancelledTask);
}
this.deregisterTaskContext(taskId);
if (previousStatus === "running") {
const dispatchTopic = isProcessAffine ? this.processAffineDispatchTopic : TOPIC_DISPATCH;
await this.pubsub.publish(dispatchTopic, {
type: "task.cancel",
data: { taskId },
runId: taskId
});
}
return;
}
}
/**
* Resume a suspended task. The tool executor must be re-registered via
* `registerTaskContext(taskId, ...)` before calling this if the original
* registration is gone (e.g. process restart) — the manager doesn't
* rehydrate executor closures from storage.
*
* `resumeData` is forwarded to the tool's `execute` options on the
* resumed run.
*/
async resume(taskId, resumeData, options) {
if (this.shuttingDown) throw new Error("BackgroundTaskManager is shutting down, cannot resume tasks");
if (!this.#mastra) throw new Error("Mastra is not registered with this manager");
if (this.initPromise) await this.initPromise;
const task = await (await this.getStorage()).getTask(taskId);
if (!task) throw new Error(`Task not found: ${taskId}`);
if (task.status !== "suspended") throw new Error(`Cannot resume task in status '${task.status}' (expected 'suspended')`);
if (options?.suspendedAt !== void 0 && new Date(options.suspendedAt).getTime() !== suspensionToken(task)) throw new Error(`Cannot resume task "${taskId}": its suspension has changed since it was read`);
const isProcessAffine = this.taskContexts.has(taskId);
if (!(isProcessAffine ? this.reserveLocalSlot(task) : await this.checkConcurrency(task.agentId))) {
if (options?.onNoSlot === "queue") {
this.localPendingResumes.set(taskId, {
resumeData,
suspendedAt: suspensionToken(task)
});
return task;
}
throw new Error(`Concurrency limit reached, cannot resume task "${taskId}" — retry once a slot is available`);
}
this.localPendingResumes.delete(taskId);
await this.#publishResume(task, resumeData, isProcessAffine);
return task;
}
async #publishResume(task, resumeData, isProcessAffine) {
const taskId = task.id;
if (this.shuttingDown) {
if (isProcessAffine) this.releaseLocalSlot(taskId);
throw new Error("BackgroundTaskManager is shutting down, cannot resume tasks");
}
await this.#ensureExecutionWorkersStarted();
const dispatchTopic = isProcessAffine ? this.processAffineDispatchTopic : TOPIC_DISPATCH;
try {
await this.pubsub.publish(dispatchTopic, {
type: "task.resume",
data: {
taskId,
resumeData,
suspendedAt: suspensionToken(task)
},
runId: taskId
});
} catch (error) {
if (isProcessAffine) this.releaseLocalSlot(taskId);
throw error;
}
if (!isProcessAffine) this.inFlightPortableResumes.set(taskId, {
agentId: task.agentId,
suspendedAt: suspensionToken(task),
until: Date.now() + this.config.leaseDurationMs
});
}
/**
* Re-dispatches a previously pending or running task. The tool executor is
* re-registered via `registerTaskContext(taskId, ...)` because the original
* registration is gone (e.g. process restart) — the manager doesn't
* rehydrate executor closures from storage.
*
* Restarting a `running` task is an explicit takeover: the claim is fenced on
* status only, so it succeeds even while another manager holds a live lease.
* The previous owner's next renewal fails and aborts its run, but that run
* may overlap this one until then.
*/
async restart(taskId, context) {
if (this.shuttingDown) throw new Error("BackgroundTaskManager is shutting down, cannot restart tasks");
if (!this.#mastra) throw new Error("Mastra is not registered with this manager");
if (this.initPromise) await this.initPromise;
const task = await (await this.getStorage()).getTask(taskId);
if (!task) throw new Error(`Task not found: ${taskId}`);
if (task.status !== "pending" && task.status !== "running") throw new Error(`Cannot restart task in status '${task.status}' (expected 'pending' or 'running')`);
const isRestart = task.status === "running";
if (context) this.registerTaskContext(task.id, context);
const isProcessAffine = this.taskContexts.has(taskId);
if (!(isProcessAffine ? this.reserveLocalSlot(task) : await this.checkConcurrency(task.agentId))) throw new Error(`Concurrency limit reached, cannot restart task "${taskId}" — retry once a slot is available`);
try {
await this.dispatch(task, isRestart);
} catch (error) {
if (isProcessAffine) this.releaseLocalSlot(taskId);
throw error;
}
return task;
}
async getTask(taskId) {
return (await this.getStorage()).getTask(taskId);
}
async listTasks(filter = {}) {
return (await this.getStorage()).listTasks(filter);
}
/**
* Deletes old completed/failed/cancelled/timed_out task records from storage.
*/
async cleanup() {
const completedTtlMs = this.config.cleanup?.completedTtlMs ?? 36e5;
const failedTtlMs = this.config.cleanup?.failedTtlMs ?? 864e5;
const now = Date.now();
const storage = await this.getStorage();
if (!storage.supportsTaskExpiry) {
await storage.deleteTasks({
status: ["completed"],
toDate: new Date(now - completedTtlMs),
dateFilterBy: "completedAt"
});
await storage.deleteTasks({
status: [
"failed",
"cancelled",
"timed_out"
],
toDate: new Date(now - failedTtlMs),
dateFilterBy: "completedAt"
});
return;
}
await storage.deleteTasks({
status: [
"completed",
"failed",
"cancelled",
"timed_out"
],
toDate: new Date(now),
dateFilterBy: "expiresAt"
});
await storage.deleteTasks({
status: ["completed"],
hasExpiresAt: false,
toDate: new Date(now - completedTtlMs),
dateFilterBy: "completedAt"
});
await storage.deleteTasks({
status: [
"failed",
"cancelled",
"timed_out"
],
hasExpiresAt: false,
toDate: new Date(now - failedTtlMs),
dateFilterBy: "completedAt"
});
}
/**
* Returns a promise that resolves when the next task from the given set
* reaches a terminal state.
*/
async waitForNextTask(taskIds, options) {
const storage = await this.getStorage();
const isTerminal = (status) => status === "completed" || status === "failed" || status === "cancelled" || status === "timed_out";
for (const id of taskIds) {
const task = await storage.getTask(id);
if (task && isTerminal(task.status)) return task;
}
return new Promise((resolve, reject) => {
const startTime = Date.now();
let timeout;
let progressInterval;
let pollInterval;
const cleanup = () => {
if (pollInterval) clearInterval(pollInterval);
if (timeout) clearTimeout(timeout);
if (progressInterval) clearInterval(progressInterval);
options?.abortSignal?.removeEventListener("abort", handleAbort);
};
const handleAbort = () => {
cleanup();
reject(options?.abortSignal?.reason ?? /* @__PURE__ */ new Error("Background task wait aborted"));
};
if (options?.abortSignal?.aborted) {
handleAbort();
return;
}
options?.abortSignal?.addEventListener("abort", handleAbort, { once: true });
timeout = options?.timeoutMs ? setTimeout(() => {
cleanup();
reject(/* @__PURE__ */ new Error("Timed out waiting for background task"));
}, options.timeoutMs) : void 0;
progressInterval = options?.onProgress ? setInterval(() => {
options.onProgress(Date.now() - startTime);
}, options.progressIntervalMs ?? 3e3) : void 0;
pollInterval = setInterval(async () => {
for (const id of taskIds) {
const task = await storage.getTask(id);
if (task && isTerminal(task.status)) {
cleanup();
resolve(task);
return;
}
}
}, 50);
});
}
/**
* Returns a ReadableStream of all background task lifecycle events,
* filtered by optional criteria. Intended to be piped directly to an SSE response.
*
* On connection, emits the current state of all non-terminal tasks as a snapshot,
* then subscribes to live pubsub events for subsequent updates.
*
* Events include:
* - `task.running` (status: 'running') — task picked up by a worker
* - `task.completed` (status: 'completed') — task finished successfully
* - `task.failed` (status: 'failed' or 'timed_out') — task errored or timed out
* - `task.cancelled` (status: 'cancelled') — task was cancelled
* - `task.suspended` (status: 'suspended') — task paused via `suspend()` from
* inside its tool executor; resume with `manager.resume(taskId, data)`
* - `task.resumed` (status: 'running') — suspended task resumed
*
* The stream stays open until the caller's AbortSignal fires (client disconnect).
*
* Events are scoped to a resource: when `resourceId` is omitted, only tasks without a
* `resourceId` are delivered. Pass `allResources: true` to receive events for every
* resource (privileged consumers only — payloads include task args and results).
*/
stream(options) {
const manager = this;
const pubsub = this.pubsub;
const { agentId, runId, threadId, resourceId, abortSignal, taskId, includeExisting = true, allResources = false } = options ?? {};
const matchesResource = (taskResourceId) => {
if (resourceId !== void 0) return taskResourceId === resourceId;
return allResources || taskResourceId == null;
};
const EVENT_STATUS_MAP = {
"task.running": "running",
"task.output": "running",
"task.completed": "completed",
"task.failed": "failed",
"task.cancelled": "cancelled",
"task.suspended": "suspended",
"task.resumed": "running"
};
const CHUNK_EVENT_MAP = {
"task.running": "background-task-running",
"task.output": "background-task-output",
"task.completed": "background-task-completed",
"task.failed": "background-task-failed",
"task.cancelled": "background-task-cancelled",
"task.suspended": "background-task-suspended",
"task.resumed": "background-task-resumed"
};
return new ReadableStream({ async start(controller) {
const handler = async (event) => {
if (!EVENT_STATUS_MAP[event.type]) return;
const data = event.data;
if (agentId && data.agentId !== agentId) return;
if (runId && data.runId !== runId) return;
if (threadId && data.threadId !== threadId) return;
if (!matchesResource(data.resourceId)) return;
if (taskId && data.taskId !== taskId) return;
const payload = {
taskId: data.taskId,
toolName: data.toolName,
toolCallId: data.toolCallId,
agentId: data.agentId,
runId: data.runId
};
switch (event.type) {
case "task.running":
payload.startedAt = data.startedAt;
payload.args = data.args;
break;
case "task.completed":
payload.completedAt = data.completedAt;
payload.result = data.result;
break;
case "task.failed":
payload.completedAt = data.completedAt;
payload.error = data.error;
break;
case "task.cancelled":
payload.completedAt = data.completedAt;
break;
case "task.output":
payload.payload = data.chunk;
break;
case "task.suspended":
payload.suspendPayload = data.suspendPayload;
payload.suspendedAt = data.suspendedAt;
payload.args = data.args;
break;
case "task.resumed":
payload.startedAt = data.startedAt;
payload.args = data.args;
}
try {
controller.enqueue({
type: CHUNK_EVENT_MAP[event.type],
payload
});
} catch {}
};
await pubsub.subscribe(TOPIC_RESULT, handler);
const close = () => {
pubsub.unsubscribe(TOPIC_RESULT, handler);
try {
controller.close();
} catch {}
};
if (abortSignal?.aborted) {
close();
return;
}
abortSignal?.addEventListener("abort", close, { once: true });
if (!includeExisting) return;
try {
const storage = await manager.getStorage();
if (taskId) {
const task = await storage.getTask(taskId);
if (task && task.status === "running" && matchesResource(task.resourceId)) controller.enqueue({
type: "background-task-running",
payload: {
taskId: task.id,
toolName: task.toolName,
toolCallId: task.toolCallId,
agentId: task.agentId,
runId: task.runId,
startedAt: task.startedAt,
args: task.args
}
});
} else {
const { tasks: existing } = await storage.listTasks({
agentId,
runId,
threadId,
resourceId,
status: ["running"]
});
for (const task of existing) {
if (abortSignal?.aborted) break;
if (!matchesResource(task.resourceId)) continue;
try {
controller.enqueue({
type: "background-task-running",
payload: {
taskId: task.id,
toolName: task.toolName,
toolCallId: task.toolCallId,
agentId: task.agentId,
runId: task.runId,
startedAt: task.startedAt,
args: task.args
}
});
} catch {
break;
}
}
}
} catch {}
} });
}
/**
* @param options.deadline - Absolute wall-clock deadline (ms since epoch) to
* bound teardown by. `Mastra.shutdown()` passes the deadline shared with
* its workflow drain so the two do not stack. Defaults to
* `SHUTDOWN_GRACE_PERIOD_MS` from now when called standalone.
*/
shutdown(options) {
if (this.shutdownPromise) return this.shutdownPromise;
this.shuttingDown = true;
this.shutdownDeadline = options?.deadline ?? Date.now() + SHUTDOWN_GRACE_PERIOD_MS;
this.shutdownPromise = this.#shutdown();
return this.shutdownPromise;
}
async #shutdown() {
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval);
this.cleanupInterval = void 0;
}
if (this.initPromise) await this.#waitForShutdownStep("background task manager initialization", this.initPromise.catch(() => {}));
const leasesToRelease = new Set(this.ownedLeases);
const activeTaskIds = [...this.activeAbortControllers.keys()];
this.#abortActiveControllers();
(await this.#waitForShutdownStep("background task cancellation", Promise.allSettled(activeTaskIds.map((taskId) => this.#cancelTaskForShutdown(taskId)))))?.forEach((result, index) => {
if (result.status === "rejected") this.#mastra?.getLogger?.()?.warn(`Failed to cancel background task ${activeTaskIds[index]} during shutdown:`, result.reason);
});
const awaitedRuns = /* @__PURE__ */ new Set();
for (;;) {
const pending = [...this.#settlingRuns].filter((run) => !awaitedRuns.has(run));
if (pending.length === 0) break;
pending.forEach((run) => awaitedRuns.add(run));
if (!await this.#waitForShutdownStep("background task run settlement", Promise.allSettled(pending))) break;
}
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval);
this.cleanupInterval = void 0;
}
const subscriptions = [];
if (this.workerCallback) {
subscriptions.push([TOPIC_DISPATCH, this.workerCallback]);
subscriptions.push([this.processAffineDispatchTopic, this.workerCallback]);
}
if (this.resultCallback) subscriptions.push([TOPIC_RESULT, this.resultCallback]);
(await this.#waitForShutdownStep("background task subscription cleanup", Promise.allSettled(subscriptions.map(([topic, callback]) => this.pubsub.unsubscribe(topic, callback)))))?.forEach((result, index) => {
if (result.status === "rejected") this.#mastra?.getLogger?.()?.warn(`Failed to unsubscribe from ${subscriptions[index]?.[0]} during background task shutdown:`, result.reason);
});
this.#abortActiveControllers();
this.taskContexts.clear();
this.localReservations.clear();
this.localPendingTaskIds.clear();
this.localPendingResumes.clear();
this.inFlightPortableResumes.clear();
this.staticExecutors.clear();
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
this.heartbeatInterval = void 0;
}
if (this.staleRecoveryTimeout) {
clearTimeout(this.staleRecoveryTimeout);
this.staleRecoveryTimeout = void 0;
}
if (this.pinSweepInterval) {
clearInterval(this.pinSweepInterval);
this.pinSweepInterval = void 0;
}
for (const taskId of this.ownedLeases) leasesToRelease.add(taskId);
this.ownedLeases.clear();
if (leasesToRelease.size > 0) {
const ownedTaskIds = [...leasesToRelease];
try {
const storage = await this.getStorage();
await this.#waitForShutdownStep("background task lease release", Promise.allSettled(ownedTaskIds.map((taskId) => storage.updateTask(taskId, {
ownerId: void 0,
leaseExpiresAt: void 0
}, { expectedOwnerId: this.workerId }))));
} catch {}
}
if (this.pinnedPendingLeases.size > 0) {
const pinnedTaskIds = [...this.pinnedPendingLeases];
this.pinnedPendingLeases.clear();
try {
const storage = await this.getStorage();
await this.#waitForShutdownStep("background task pinned lease release", Promise.allSettled(pinnedTaskIds.map((taskId) => storage.updateTask(taskId, { leaseExpiresAt: /* @__PURE__ */ new Date() }, {
expectedStatus: "pending",
expectedOwnerId: this.workerId
}))));
} catch {}
}
if (this.initPromise) await this.#waitForShutdownStep("background task pubsub flush", this.pubsub.flush());
}
async #cancelTaskForShutdown(taskId) {
const task = await (await this.getStorage()).getTask(taskId);
if (task?.status === "running" && task.maxRetries > 0) return;
await this.cancel(taskId);
}
#abortActiveControllers() {
for (const controller of this.activeAbortControllers.values()) controller.abort(/* @__PURE__ */ new Error(SHUTDOWN_ABORT_MESSAGE));
this.activeAbortControllers.clear();
}
/**
* Await one teardown step against the shutdown-wide deadline. Callers pass an
* already-started promise, so a step that finds the budget spent still runs —
* it just stops blocking the rest of teardown, which keeps cleanup
* best-effort while bounding `#shutdown()` as a whole.
*/
async #waitForShutdownStep(description, promise) {
const remainingMs = this.#remainingShutdownBudgetMs();
if (remainingMs <= 0) {
promise.catch(() => {});
this.#mastra?.getLogger?.()?.warn(`${description} left running in the background: the shutdown budget is spent`);
return;
}
let timeoutHandle;
let outcome;
try {
outcome = await Promise.race([promise.then((value) => ({
status: "settled",
value
})), new Promise((resolve) => {
timeoutHandle = setTimeout(() => resolve({ status: "timed-out" }), remainingMs);
})]);
} catch (error) {
this.#mastra?.getLogger?.()?.warn(`${description} failed during shutdown:`, error);
return;
} finally {
if (timeoutHandle) clearTimeout(timeoutHandle);
}
if (outcome.status === "timed-out") {
this.#mastra?.getLogger?.()?.warn(`${description} exhausted the remaining ${remainingMs}ms of the graceful shutdown budget`);
return;
}
return outcome.value;
}
#remainingShutdownBudgetMs() {
if (this.shutdownDeadline === void 0) return SHUTDOWN_GRACE_PERIOD_MS;
return this.shutdownDeadline - Date.now();
}
async #releaseLateInitSubscriptions(subscriptions) {
(await this.#waitForShutdownStep("late background task subscription cleanup", Promise.allSettled(subscriptions.map(([topic, callback]) => this.pubsub.unsubscribe(topic, callback)))))?.forEach((result, index) => {
if (result.status === "rejected") this.#mastra?.getLogger?.()?.warn(`Failed to release late ${subscriptions[index]?.[0]} subscription after shutdown:`, result.reason);
});
}
/**
* Lazily start Mastra's execution workers before publishing. In "library
* mode" nothing ever calls `mastra.startWorkers()`, so the evented
* `__background-task` workflow started by `handleDispatch` would publish
* to the `workflows` topic with no consumer and the task would sit at
* `running` forever (#19339). A no-op once workers are running; honors the
* `workers: false` / `MASTRA_WORKERS` opt-outs.
*
* Startup failures are logged but don't abort the publish — in distributed
* topologies a remote worker on the shared broker can still pick the task
* up, and throwing here would also abort `drainPending()` /
* `recoverStaleTasks()` loops.
*/
async #ensureExecutionWorkersStarted() {
if (this.shuttingDown) return;
if (!this.#mastra) return;
try {
await this.#mastra.__ensureExecutionWorkersStarted();
} catch (err) {
this.#mastra.getLogger?.()?.error("Failed to start execution workers for background task", err);
}
}
async dispatch(task, isRestart) {
if (this.shuttingDown) return;
await this.#ensureExecutionWorkersStarted();
const dispatchTopic = this.taskContexts.has(task.id) ? this.processAffineDispatchTopic : TOPIC_DISPATCH;
await this.pubsub.publish(dispatchTopic, {
type: "task.dispatch",
data: {
taskId: task.id,
toolName: task.toolName,
toolCallId: task.toolCallId,
args: task.args,
agentId: task.agentId,
threadId: task.threadId,
resourceId: task.resourceId,
timeoutMs: task.timeoutMs,
maxRetries: task.maxRetries,
runId: task.runId,
isRestart
},
runId: task.id
});
}
/**
* Handles a task.dispatch and task.restart events.
* Both events are similar, but the latter is used to restart a running task.
*/
async handleDispatch(event) {
if (this.shuttingDown) return false;
const { taskId, isRestart } = event.data;
const deliveryAttempt = event.deliveryAttempt ?? 1;
const storage = await this.getStorage();
if (this.shuttingDown) return false;
const task = await storage.getTask(taskId);
if (this.shuttingDown) return false;
if (!task || task.status === "cancelled") {
this.releaseLocalSlot(taskId);
this.deregisterTaskContext(taskId);
return true;
}
const isRunningRedelivery = task.status === "running" && deliveryAttempt > 1;
if (!(isRestart ? task.status === "running" : task.status === "pending" || isRunningRedelivery)) return true;
if (isRunningRedelivery && task.leaseExpiresAt && task.leaseExpiresAt.getTime() > Date.now()) return task.ownerId === this.workerId;
if (task.status === "pending" && task.ownerId && task.ownerId !== this.workerId) return true;
const pinnedHere = task.status === "pending" && task.ownerId === this.workerId;
const retryCount = task.status === "running" ? deliveryAttempt - 1 : task.retryCount;
const now = /* @__PURE__ */ new Date();
if (!await storage.updateTask(taskId, {
status: "running",
startedAt: now,
retryCount,
ownerId: this.workerId,
leaseExpiresAt: new Date(now.getTime() + this.config.leaseDurationMs)
}, isRestart ? { expectedStatus: task.status } : pinnedHere ? {
expectedStatus: "pending",
expectedOwnerId: this.workerId
} : {
expectedStatus: task.status,
expectedOwnerId: task.ownerId ?? null,
expectedLeaseExpiresAt: task.leaseExpiresAt ?? null
})) return true;
this.pinnedPendingLeases.delete(taskId);
this.ownedLeases.add(taskId);
if (this.shuttingDown) return false;
const runningTask = await storage.getTask(taskId);
if (!runningTask || runningTask.status !== "running") return true;
await this.publishLifecycleEvent("task.running", runningTask);
if (this.shuttingDown) return false;
if (!this.#mastra) {
this.releaseLocalSlot(taskId);
this.ownedLeases.delete(taskId);
if (await storage.updateTask(taskId, {
status: "failed",
error: { message: "Mastra is not registered with this background task manager" },
completedAt: /* @__PURE__ */ new Date(),
ownerId: void 0,
leaseExpiresAt: void 0
}, {
expectedStatus: "running",
expectedOwnerId: this.workerId
})) {
const failedTask = await storage.getTask(taskId);
if (failedTask?.status === "failed") await this.publishLifecycleEvent("task.failed", failedTask);
}
this.drainPending();
return true;
}
try {
if (runningTask) this.runLocalExecutionHook(runningTask);
const workflow = this.#mastra.__getInternalWorkflow(BACKGROUND_TASK_WORKFLOW_ID);
const prevWorkflowRun = isRestart ? await workflow.getWorkflowRunById(taskId) : void 0;
if (this.shuttingDown) return false;
const shouldRestart = isRestart && prevWorkflowRun?.status === "running";
const run = await workflow.createRun({ runId: taskId });
if (this.shuttingDown) return false;
const runPromise = shouldRestart ? run.restart() : run.start({ inputData: { taskId } });
const action = shouldRestart ? "restart" : "start";
this.#trackSettlingRun(runPromise.then((result) => {
if (result.status !== "suspended") this.#deleteSettledRun(workflow, taskId);
if (result.status !== "success" && result.status !== "suspended") return this.failUnsettledTask(taskId, action, workflowRunError(result));
}, (err) => this.failUnsettledTask(taskId, action, err)).finally(() => {
this.ownedLeases.delete(taskId);
this.releaseLocalSlot(taskId);
this.drainPending();
}));
} catch (error) {
this.releaseLocalSlot(taskId);
this.ownedLeases.delete(taskId);
if (await storage.updateTask(taskId, {
status: "failed",
error: { message: error instanceof Error ? error.message : String(error) },
completedAt: /* @__PURE__ */ new Date(),
ownerId: void 0,
leaseExpiresAt: void 0
}, {
expectedStatus: "running",
expectedOwnerId: this.workerId
})) {
const failedTask = await storage.getTask(taskId);
if (failedTask?.status === "failed") await this.publishLifecycleEvent("task.failed", failedTask);
}
this.drainPending();
}
return true;
}
/**
* Handles a task.resume event. Mirrors the workflow branch of handleDispatch
* but resumes an existing run from its suspended snapshot instead of starting
* a fresh one. Concurrency gating, suspended-status validation, and the
* `task.resumed` lifecycle publish all happen here so a different process
* than the one that suspended the task can drive the resume.
*/
async handleResume(event) {
if (this.shuttingDown) return false;
const { taskId, resumeData } = event.data;
const answers = event.data.suspendedAt;
this.inFlightPortableResumes.delete(taskId);
const storage = await this.getStorage();
if (this.shuttingDown) return false;
const task = await storage.getTask(taskId);
if (this.shuttingDown) return false;
if (!task || task.status !== "suspended" || answers !== void 0 && suspensionToken(task) !== answers) {
this.releaseLocalSlot(taskId);
this.drainPending();
return true;
}
if (!await storage.updateTask(taskId, {
status: "running",
startedAt: /* @__PURE__ */ new Date(),
suspendPayload: void 0,
suspendedAt: void 0,
ownerId: this.workerId,
leaseExpiresAt: new Date(Date.now() + this.config.leaseDurationMs)
}, {
expectedStatus: "suspended",
expectedSuspendedAt: task.suspendedAt ?? null
})) {
this.releaseLocalSlot(taskId);
this.drainPending();
return true;
}
this.localPendingResumes.delete(taskId);
this.ownedLeases.add(taskId);
const resumedTask = await storage.getTask(taskId);
if (resumedTask) {
await this.publishLifecycleEvent("task.resumed", resumedTask);
await this.runLocalExecutionHook(resumedTask);
}
if (!this.#mastra) {
this.releaseLocalSlot(taskId);
this.drainPending();
return true;
}
const workflow = this.#mastra.__getInternalWorkflow(BACKGROUND_TASK_WORKFLOW_ID);
const run = await workflow.createRun({ runId: taskId });
if (this.shuttingDown) {
this.ownedLeases.delete(taskId);
this.releaseLocalSlot(taskId);
await storage.updateTask(taskId, {
status: "suspended",
startedAt: task.startedAt,
suspendPayload: task.suspendPayload,
suspendedAt: task.suspendedAt,
ownerId: void 0,
leaseExpiresAt: void 0
}, { expectedStatus: "running" }).catch((error) => {
this.#mastra?.getLogger?.()?.warn(`Failed to restore suspended background task ${taskId} during shutdown:`, error);
});
return false;
}
this.#trackSettlingRun(run.resume({ resumeData }).then((result) => {
if (result.status !== "suspended") this.#deleteSettledRun(workflow, taskId);
if (result.status !== "success" && result.status !== "suspended") return this.failUnsettledTask(taskId, "resume", workflowRunError(result));
}, (err) => this.failUnsettledTask(taskId, "resume", err)).finally(() => {
this.ownedLeases.delete(taskId);
this.releaseLocalSlot(taskId);
this.drainPending();
}));
return true;
}
/** Track a run settlement (or its follow-up delete) so shutdown can drain it before storage closes. */
#trackSettlingRun(promise) {
const tracked = promise.finally(() => this.#settlingRuns.delete(tracked));
this.#settlingRuns.add(tracked);
tracked.catch((error) => {
this.#mastra?.getLogger?.()?.error("Background task workflow run settlement failed:", error);
});
}
#deleteSettledRun(workflow, taskId) {
this.#trackSettlingRun(workflow.deleteWorkflowRunById(taskId).catch((error) => {
this.#mastra?.getLogger?.()?.warn(`Failed to delete workflow run for background task ${taskId}:`, error);
}));
}
/**
* Settles a task whose background-task workflow run ended in a non-success,
* non-suspended state (or rejected). On the ordinary failure path
* classify-outcome has already moved the task to `failed`, so the CAS below
* is a no-op. It only takes effect when a step threw before persisting a
* terminal status (e.g. the `completed` write failed), which would otherwise
* leave the task `running` forever.
*/
async failUnsettledTask(taskId, action, err) {
const errorInfo = toTaskError(err);
try {
const storage = await this.getStorage();
if (!await storage.updateTask(taskId, {
status: "failed",
error: errorInfo,
completedAt: /* @__PURE__ */ new Date(),
ownerId: void 0,
leaseExpiresAt: void 0
}, {
expectedStatus: "running",
expectedOwnerId: this.workerId
})) return;
this.#mastra?.getLogger?.()?.error(`background-task workflow ${action} failed for ${taskId}:`, err);
const failedTask = await storage.getTask(taskId);
if (failedTask?.status === "failed") {
await this.runLocalCompletionHooks(failedTask, "failed", { error: failedTask.error ?? errorInfo });
await this.publishLifecycleEvent("task.failed", failedTask);
}
} catch (settleError) {
this.#mastra?.getLogger?.()?.error(`background-task workflow ${action} failed for ${taskId} and the task could not be marked failed:`, {
error: err,
settleError
});
this.deregisterTaskContext(taskId);
}
}
/**
* Run per-task hooks (onChunk, onResult, onComplete/onFailed) locally in the
* worker path, before publishing the terminal lifecycle event. Ensures
* memory / stream state is consistent by the time any pubsub subscriber is
* notified. After running, the task context is deregistered so
* `handleResult` (which also fires from pubsub) becomes a no-op for this
* task in the same process.
*
* In distributed deployments where the worker runs in a different process
* from the dispatcher, `this.taskContexts` won't contain an entry for
* `task.id` — this method is a no-op there, and `handleResult` in the
* dispatching process runs the hooks instead.
*/
/**
* Terminal-state hooks only. Called when a task reaches `'completed'` or
* `'failed'`. Suspend is non-terminal — see `runLocalSuspendHooks` for that
* path.
*
* @internal — also called by the workflow-engine step bodies in workflow.ts
*/
async runLocalCompletionHooks(task, status, extras) {
const ctx = this.taskContexts.get(task.id);
if (!ctx) return;
try {
if (status === "completed") {
ctx.onChunk?.({
type: "background-task-completed",
payload: {
taskId: task.id,
toolName: task.toolName,
toolCallId: task.toolCallId,
runId: task.runId,
result: extras.result,
completedAt: task.completedAt,
agentId: task.agentId
}
});
await ctx.onResult?.({
runId: task.runId,
taskId: task.id,
toolCallId: task.toolCallId,
toolName: task.toolName,
agentId: task.agentId,
threadId: task.threadId,
resourceId: task.resourceId,
result: extras.result,
status: "completed",
completedAt: task.completedAt,
startedAt: task.startedAt
});
await ctx.onComplete?.(task);
} else {
ctx.onChunk?.({
type: "background-task-failed",
payload: {
taskId: task.id,
toolName: task.toolName,
toolCallId: task.toolCallId,
runId: task.runId,
error: extras.error ?? { message: "Unknown error" },
completedAt: task.completedAt,
agentId: task.agentId
}
});
await ctx.onResult?.({
runId: task.runId,
taskId: task.id,
toolCallId: task.toolCallId,
toolName: task.toolName,
agentId: task.agentId,
threadId: task.threadId,
resourceId: task.resourceId,
error: extras.error,
status: "failed",
completedAt: task.completedAt,
startedAt: task.startedAt
});
await ctx.onFailed?.(task);
}
} catch (hookError) {
this.#mastra?.getLogger?.()?.warn(`background-task ${status} hooks threw for ${task.id}:`, hookError);
} finally {
this.deregisterTaskContext(task.id);
}
}
/**
* Per-task suspend hooks. Fires `ctx.onExecution({ suspendedAt, suspendPayload, ... })`
* so the message list / memory record the open suspension on the tool
* call. Does NOT deregister the task context — resume needs the executor
* closure intact.
*
* @internal — called by the workflow-engine step bodies in workflow.ts
*/
async runLocalSuspendHooks(task) {
const ctx = this.taskContexts.get(task.id);
if (!ctx) return;
await ctx.onExecution?.({
runId: task.runId,
taskId: task.id,
toolCallId: task.toolCallId,
toolName: task.toolName,
agentId: task.agentId,
threadId: task.threadId,
resourceId: task.resourceId,
startedAt: task.startedAt,
suspendedAt: task.suspendedAt,
suspendPayload: task.suspendPayload
});
}
/** @internal — also called by the workflow-engine step bodies in workflow.ts */
async runLocalExecutionHook(task) {
const ctx = this.taskContexts.get(task.id);
if (!ctx) return;
try {
await ctx.onExecution?.({
runId: task.runId,
taskId: task.id,
toolCallId: task.toolCallId,
toolName: task.toolName,
agentId: task.agentId,
threadId: task.threadId,
resourceId: task.resourceId,
startedAt: task.startedAt
});
} catch {}
}
/**
* Another process cancelled a task this one dispatched. Run its execution
* hook, so the dispatcher drops an open request it recorded for the task,
* and release the task's context. A cancel made here has already done both.
*/
async handleRemoteCancel(taskId) {
if (!this.taskContexts.has(taskId)) return;
const task = await (await this.getStorage()).getTask(taskId);
if (task?.status !== "cancelled") return;
await this.runLocalExecutionHook(task);
this.deregisterTaskContext(taskId);
}
async handleResult(event) {
const { taskId, toolName, toolCallId, threadId, resourceId, runId } = event.data;
const task = await (await this.getStorage()).getTask(taskId);
if (!task?.completedAt) return;
const ctx = this.taskContexts.get(taskId);
try {
if (event.type === "task.completed") {
ctx?.onChunk?.({
type: "background-task-completed",
payload: {
taskId,
toolName,
toolCallId,
runId,
result: event.data.result,
completedAt: task.completedAt,
agentId: task.agentId
}
});
await ctx?.onResult?.({
runId,
taskId,
toolCallId,
toolName,
agentId: event.data.agentId,
threadId,
resourceId,
result: event.data.result,
status: "completed",
completedAt: task.completedAt,
startedAt: task.startedAt
});
await Promise.all([ctx?.onComplete?.(task), (async () => {
try {
await this.config.onTaskComplete?.(task);
} catch (error) {
this.#mastra?.getLogger?.()?.warn(`background-task completion callback failed for ${taskId}:`, error);
}
})()]);
}
if (event.type === "task.failed") {
ctx?.onChunk?.({
type: "background-task-failed",
payload: {
taskId,
toolName,
toolCallId,
runId,
error: event.data.error,
completedAt: task.completedAt,
agentId: task.agentId
}
});
await ctx?.onResult?.({
runId,
taskId,
toolCallId,
toolName,
agentId: event.data.agentId,
threadId,
resourceId,
error: event.data.error,
status: "failed",
completedAt: task.completedAt,
startedAt: task.startedAt
});
await Promise.all([ctx?.onFailed?.(task), (async () => {
try {
await this.config.onTaskFailed?.(task);
} catch (error) {
this.#mastra?.getLogger?.()?.warn(`background-task failure callback failed for ${taskId}:`, error);
}
})()]);
}
} finally {
this.deregisterTaskContext(taskId);
this.drainPending();
}
}
handleCancel(event) {
const { taskId } = event.data;
const controller = this.activeAbortControllers.get(taskId);
if (controller) {
controller.abort(/* @__PURE__ */ new Error("Task cancelled"));
this.activeAbortControllers.delete(taskId);
}
this.deregisterTaskContext(taskId);
}
/** @internal — also called by the workflow-engine step bodies in workflow.ts */
async publishLifecycleEvent(type, task) {
await this.pubsub.publish(TOPIC_RESULT, {
type,
data: {
taskId: task.id,
toolName: task.toolName,
toolCallId: task.toolCallId,
runId: task.runId,
agentId: task.agentId,
threadId: task.threadId,
resourceId: task.resourceId,
args: type === "task.output" ? void 0 : task.args,
result: task.result,
error: task.error,
chunk: task.chunk,
completedAt: task.completedAt,
startedAt: task.startedAt,
suspendPayload: task.suspendPayload,
suspendedAt: task.suspendedAt
},
runId: task.id
});
}
/**
* Renew every lease this manager holds, at `leaseDurationMs / 3`. Called on
* an interval so a live owner keeps proving liveness; a task whose renewal
* fails has left `running` (completed/failed/suspended/cancelled) or been
* reclaimed by another owner, so it is dropped from the tracking set.
*/
async #renewOwnedLeases() {
if (this.ownedLeases.size === 0 && this.pinnedPendingLeases.size === 0) return;
let storage;
try {
storage = await this.getStorage();
} catch {
return;
}
for (const taskId of [...this.ownedLeases]) try {
if (!await storage.updateTask(taskId, { leaseExpiresAt: new Date(Date.now() + this.config.leaseDurationMs) }, {
expectedStatus: "running",
expectedOwnerId: this.workerId
})) {
this.ownedLeases.delete(taskId);
await this.#abortSupersededRun(taskId);
}
} catch {}
for (const taskId of [...this.pinnedPendingLeases]) try {
if (!await storage.updateTask(taskId, { leaseExpiresAt: new Date(Date.now() + this.config.leaseDurationMs) }, {
expectedStatus: "pending",
expectedOwnerId: this.workerId
})) this.pinnedPendingLeases.delete(taskId);
} catch {}
}
/**
* Called when a lease renewal loses its compare-and-set. Renewal normally
* fails because the task left `running` (it completed, failed or suspended),
* which needs no action. Two cases still have a local executor to stop:
* - The task was *cancelled*, possibly by another process whose `task.cancel`
* event never reached this one. The local run is aborted the same way a
* local `cancel()` aborts it, so it settles as cancelled.
* - The task is *still running under a different owner*: another worker has
* taken it over. Its fenced terminal writes would be rejected anyway;
* aborting just stops the wasted run.
*/
async #abortSupersededRun(taskId) {
try {
const current = await (await this.getStorage()).getTask(taskId);
if (current?.status === "cancelled") {
const controller = this.activeAbortControllers.get(taskId);
if (!controller) return;
controller.abort(/* @__PURE__ */ new Error("Task cancelled"));
this.activeAbortControllers.delete(taskId);
this.deregisterTaskContext(taskId);
return;
}
if (current?.status !== "running") return;
if (current.ownerId === this.workerId || !current.ownerId) return;
const controller = this.activeAbortControllers.get(taskId);
if (!controller) return;
controller.abort(/* @__PURE__ */ new Error(TASK_OWNERSHIP_LOST_MESSAGE));
} catch {}
}
#startLeaseHeartbeat() {
if (this.heartbeatInterval) return;
const intervalMs = Math.max(this.#timingFloorMs, Math.floor(this.config.leaseDurationMs / 3));
this.heartbeatInterval = setInterval(() => {
this.#renewOwnedLeases();
if (this.localPendingResumes.size > 0) this.drainPending();
}, intervalMs);
this.heartbeatInterval.unref?.();
}
reserveLocalSlot(task) {
if (this.localReservations.has(task.id)) return true;
if (this.localReservations.size >= this.config.globalConcurrency) return false;
let agentRunning = 0;
for (const agentId of this.localReservations.values()) if (agentId === task.agentId) agentRunning++;
if (agentRunning >= this.#ownerLimit(task.agentId)) return false;
this.localReservations.set(task.id, task.agentId);
return true;
}
#ownerLimit(agentId) {
const overrides = this.config.perOwnerConcurrency;
return overrides && Object.hasOwn(overrides, agentId) ? overrides[agentId] : this.config.perAgentConcurrency;
}
releaseLocalSlot(taskId) {
this.localReservations.delete(taskId);
}
async checkConcurrency(agentId) {
const storage = await this.getStorage();
await this.#pruneInFlightResumes();
let inFlightForAgent = 0;
for (const entry of this.inFlightPortableResumes.values()) if (entry.agentId === agentId) inFlightForAgent++;
if (await storage.getRunningCount() + this.inFlightPortableResumes.size >= this.config.globalConcurrency) return false;
if (await storage.getRunningCountByAgent(agentId) + inFlightForAgent >= this.#ownerLimit(agentId)) return false;
return true;
}
async #pruneInFlightResumes() {
if (this.inFlightPortableResumes.size === 0) return;
const storage = await this.getStorage();
const now = Date.now();
for (const [taskId, entry] of [...this.inFlightPortableResumes]) {
if (entry.until <= now) {
this.inFlightPortableResumes.delete(taskId);
continue;
}
const task = await storage.getTask(taskId);
if (!task || task.status !== "suspended" || suspensionToken(task) !== entry.suspendedAt) this.inFlightPortableResumes.delete(taskId);
}
}
async drainPending() {
if (this.drainingPending || this.shuttingDown) return;
this.drainingPending = true;
try {
const storage = await this.getStorage();
for (const [taskId, entry] of [...this.localPendingResumes]) {
const task = await storage.getTask(taskId);
if (!task || task.status !== "suspended" || suspensionToken(task) !== entry.suspendedAt) {
this.localPendingResumes.delete(taskId);
continue;
}
const isProcessAffine = this.taskContexts.has(taskId);
if (!(isProcessAffine ? this.reserveLocalSlot(task) : await this.checkConcurrency(task.agentId))) continue;
if (this.shuttingDown) return;
this.localPendingResumes.delete(taskId);
try {
await this.#publishResume(task, entry.resumeData, isProcessAffine);
} catch (error) {
this.localPendingResumes.set(taskId, entry);
this.#mastra?.getLogger?.()?.warn(`background-task resume failed while draining ${taskId}:`, error);
return;
}
}
for (const taskId of [...this.localPendingTaskIds]) {
const task = await storage.getTask(taskId);
if (!task || task.status !== "pending") {
this.localPendingTaskIds.delete(taskId);
continue;
}
const isProcessAffine = this.taskContexts.has(taskId);
if (!(isProcessAffine ? this.reserveLocalSlot(task) : await this.checkConcurrency(task.agentId))) continue;
this.localPendingTaskIds.delete(taskId);
try {
await this.dispatch(task);
} catch (error) {
if (isProcessAffine) this.releaseLocalSlot(taskId);
this.localPendingTaskIds.add(taskId);
this.#mastra?.getLogger?.()?.warn(`background-task dispatch failed while draining ${taskId}:`, error);
return;
}
}
} catch (error) {
this.#mastra?.getLogger?.()?.warn("background-task queue drain failed:", error);
} finally {
this.drainingPending = false;
}
}
/**
* Recovers tasks left in 'running' or 'pending' state from a previous process.
*
* Running tasks are only reclaimed once their execution lease has lapsed, so
* one whose owner died moments before this scan is still protected. When that
* happens the scan reschedules itself for the moment the earliest such lease
* expires — see `#scheduleStaleRecovery`.
*/
async recoverStaleTasks() {
if (this.shuttingDown) return;
try {
const storage = await this.getStorage();
const now = Date.now();
const { tasks: staleTasks } = await storage.listTasks({ status: "running" });
let nextSweepAt;
for (const task of staleTasks) {
if (task.ownerId && task.leaseExpiresAt && task.leaseExpiresAt.getTime() > now) {
const leaseExpiry = task.leaseExpiresAt.getTime();
nextSweepAt = nextSweepAt === void 0 ? leaseExpiry : Math.min(nextSweepAt, leaseExpiry);
continue;
}
const fence = {
expectedStatus: "running",
expectedOwnerId: task.ownerId ?? null,
expectedLeaseExpiresAt: task.leaseExpiresAt ?? null
};
if (task.maxRetries > 0) await storage.updateTask(task.id, {
status: "pending",
startedAt: void 0,
ownerId: void 0,
leaseExpiresAt: void 0
}, fence);
else await storage.updateTask(task.id, {
status: "failed",
error: { message: "Worker process terminated before task completed" },
completedAt: /* @__PURE__ */ new Date(),
ownerId: void 0,
leaseExpiresAt: void 0
}, fence);
}
const { tasks: pendingTasks } = await storage.listTasks({
status: "pending",
orderBy: "createdAt",
orderDirection: "asc"
});
for (const task of pendingTasks) {
if (task.ownerId) {
const leaseExpiry = task.leaseExpiresAt?.getTime();
if (leaseExpiry !== void 0 && leaseExpiry > now) nextSweepAt = nextSweepAt === void 0 ? leaseExpiry : Math.min(nextSweepAt, leaseExpiry);
if (await this.#recoverLapsedPinWhenFree(storage, task, now)) await this.#dispatchRecoveredPin(task);
continue;
}
if (await this.checkConcurrency(task.agentId)) await this.dispatch(task);
}
this.#scheduleStaleRecovery(nextSweepAt);
} catch (error) {
const logger = this.#mastra?.getLogger();
if (logger) logger.error("Failed to recover stale background tasks", error);
}
}
/**
* Accounts for a `pinToWorker` row whose owner stopped renewing its lease.
* A pin means work for the row was in flight on its owner, so a lapsed pin
* is a lost attempt, handled like a `running` row whose lease lapsed: it
* consumes a retry and is unpinned, or it fails. Returns `true` when the row
* was unpinned and should be dispatched; `false` when the lease is still
* live, the row was failed, or another worker got to it first.
*/
async #recoverLapsedPin(storage, task, now) {
if (task.leaseExpiresAt && task.leaseExpiresAt.getTime() > now) return false;
const fence = {
expectedStatus: "pending",
expectedOwnerId: task.ownerId ?? null,
expectedLeaseExpiresAt: task.leaseExpiresAt ?? null
};
const retry = task.retryCount < task.maxRetries;
const recovered = retry ? await storage.updateTask(task.id, {
retryCount: task.retryCount + 1,
ownerId: void 0,
leaseExpiresAt: void 0
}, fence) : await storage.updateTask(task.id, {
status: "failed",
error: { message: "Worker process terminated before task completed" },
completedAt: /* @__PURE__ */ new Date(),
ownerId: void 0,
leaseExpiresAt: void 0
}, fence);
if (recovered) this.#mastra?.getLogger()?.warn(`Background task ${task.id} lost its pin: worker ${task.ownerId} stopped renewing its lease. ${retry ? "Retrying it on another worker." : "Marking it failed."}`);
return retry && recovered;
}
/**
* {@link #recoverLapsedPin}, but a row that would be retried is only unpinned
* while a slot is free: an unpinned pending row is no longer seen by the pin
* sweep, so unpinning it without dispatching would spend the retry and leave
* it waiting for a restart. Without a slot the pin stays lapsed and a later
* sweep tries again. A row out of retries is failed either way.
*/
async #recoverLapsedPinWhenFree(storage, task, now) {
if ((!task.leaseExpiresAt || task.leaseExpiresAt.getTime() <= now) && task.retryCount < task.maxRetries && !await this.checkConcurrency(task.agentId)) return false;
return this.#recoverLapsedPin(storage, task, now);
}
/**
* Dispatches a row just unpinned by {@link #recoverLapsedPin}. The row is now
* unowned, so the pin sweep no longer sees it: if publishing fails, queue it
* locally so `drainPending()` (also run by every pin sweep) retries it.
*/
async #dispatchRecoveredPin(task) {
try {
await this.dispatch(task);
} catch (error) {
this.localPendingTaskIds.add(task.id);
this.#mastra?.getLogger?.()?.warn(`background-task dispatch failed after recovering pin ${task.id}:`, error);
}
}
/**
* Periodically recovers lapsed `pinToWorker` rows. The startup scan only
* sees rows that existed when this worker started, so without this a pin
* enqueued later by a worker that then died would wait for a restart.
* Unpinned pending rows are left alone: they are dispatched by their own
* worker and by startup recovery, as before.
*/
async #sweepLapsedPins() {
if (this.shuttingDown || this.sweepingPins) return;
this.sweepingPins = true;
try {
if (this.localPendingTaskIds.size > 0) await this.drainPending();
const storage = await this.getStorage();
const now = Date.now();
const { tasks } = await storage.listTasks({
status: "pending",
orderBy: "createdAt",
orderDirection: "asc",
page: this.pinSweepPage,
perPage: PIN_SWEEP_PAGE_SIZE
});
this.pinSweepPage = tasks.length < PIN_SWEEP_PAGE_SIZE ? 0 : this.pinSweepPage + 1;
for (const task of tasks) {
if (!task.ownerId || this.shuttingDown) continue;
if (await this.#recoverLapsedPinWhenFree(storage, task, now)) await this.#dispatchRecoveredPin(task);
}
} catch (error) {
this.#mastra?.getLogger()?.error("Failed to recover lapsed pinned background tasks", error);
} finally {
this.sweepingPins = false;
}
}
#startPinSweep() {
if (this.shuttingDown || this.pinSweepInterval) return;
this.pinSweepInterval = setInterval(() => void this.#sweepLapsedPins(), this.config.leaseDurationMs);
this.pinSweepInterval.unref?.();
}
/**
* Re-runs the stale-task scan once the earliest still-valid lease lapses.
* Rescheduling is harmless while an owner stays alive: its heartbeat keeps
* pushing the expiry out, so each pass simply schedules the next one.
*/
#scheduleStaleRecovery(nextSweepAt) {
if (this.staleRecoveryTimeout) {
clearTimeout(this.staleRecoveryTimeout);
this.staleRecoveryTimeout = void 0;
}
if (nextSweepAt === void 0 || this.shuttingDown) return;
const floor = this.#timingFloorMs;
const delay = Math.min(Math.max(nextSweepAt - Date.now() + floor, floor), Math.max(this.config.leaseDurationMs, floor));
this.staleRecoveryTimeout = setTimeout(() => {
this.staleRecoveryTimeout = void 0;
this.recoverStaleTasks();
}, delay);
this.staleRecoveryTimeout.unref?.();
}
};
function suspensionToken(task) {
return task.suspendedAt?.getTime() ?? null;
}
// src/background-tasks/create.ts
/**
* Creates a self-contained background task handle.
*
* Bundles the task payload with per-stream hooks (executor, onChunk, onResult)
* so each dispatch is fully isolated — no shared mutable state on the manager.
*
* @example
* ```ts
* const bgTask = createBackgroundTask(manager, {
* toolName: 'research',
* toolCallId: 'call-1',
* args: { query: 'solana' },
* agentId: 'agent-1',
* runId: 'run-1',
* context: {
* executor: { execute: (args, opts) => tool.execute(args, opts) },
* onChunk: (chunk) => controller.enqueue(chunk),
* onResult: (params) => messageList.addToolResult(params),
* },
* });
*
* const { task, fallbackToSync } = await bgTask.dispatch();
* const completed = await bgTask.waitForCompletion();
* await bgTask.cancel();
* ```
*/
function createBackgroundTask(manager, options) {
const { context, ...payload } = options;
let taskId;
return {
get task() {
if (!taskId) throw new Error("Task has not been dispatched yet");
return { id: taskId };
},
async dispatch() {
const result = await manager.enqueue(payload, context);
taskId = result.task.id;
return result;
},
async checkIfSuspended(args) {
const result = await manager.listTasks({
toolCallId: args.toolCallId,
runId: args.runId,
agentId: args.agentId,
threadId: args.threadId,
resourceId: args.resourceId,
toolName: args.toolName,
status: "suspended"
});
if (result.total > 0) {
const task = result.tasks[0];
if (task) {
taskId = task.id;
return true;
}
}
return false;
},
async checkIfExisting(args) {
const result = await manager.listTasks({
toolCallId: args.toolCallId,
runId: args.runId,
agentId: args.agentId,
threadId: args.threadId,
resourceId: args.resourceId,
toolName: args.toolName
});
if (result.total > 1) throw new Error(`Multiple background tasks found for run "${args.runId}" and tool call "${args.toolCallId}"`);
const task = result.tasks[0];
if (task) {
taskId = task.id;
if (task.status === "pending" || task.status === "running" || task.status === "suspended") manager.registerTaskContext(task.id, context);
}
return task;
},
async checkIfRunning(args) {
const result = await manager.listTasks({
toolCallId: args.toolCallId,
runId: args.runId,
agentId: args.agentId,
threadId: args.threadId,
resourceId: args.resourceId,
toolName: args.toolName,
status: "running"
});
if (result.total > 0) {
const task = result.tasks[0];
if (task) {
taskId = task.id;
return true;
}
}
return false;
},
async resume(resumeData, resumeOptions) {
if (!taskId) throw new Error("Task has not been dispatched yet");
manager.registerTaskContext(taskId, context);
try {
return resumeOptions ? await manager.resume(taskId, resumeData, resumeOptions) : await manager.resume(taskId, resumeData);
} catch (error) {
manager.deregisterTaskContext(taskId);
throw error;
}
},
async restart() {
if (!taskId) throw new Error("Task has not been dispatched yet");
return manager.restart(taskId, context);
},
async cancel() {
if (!taskId) throw new Error("Task has not been dispatched yet");
return manager.cancel(taskId);
},
async waitForCompletion(waitOptions) {
if (!taskId) throw new Error("Task has not been dispatched yet");
return manager.waitForNextTask([taskId], waitOptions);
}
};
}
// src/background-tasks/resolve-config.ts
/**
* Resolves whether a tool call should run in the background, and with what config.
*
* Resolution order (highest to lowest priority):
* 1. LLM per-call override (`_background` field in tool args)
* 2. Agent-level backgroundTasks.tools config
* 3. Tool-level background config
* 4. Default for eligible tools: the configured `defaultDisposition`
* (deferred when unset); non-eligible tools always run foreground
*
* Strips the `_background` field from args (mutates the args object).
*/
function resolveBackgroundConfig({ llmBgOverrides, toolName, toolConfig, agentConfig, managerConfig }) {
const llmOverride = llmBgOverrides;
if (agentConfig?.disabled) return {
runInBackground: false,
disposition: "foreground",
timeoutMs: managerConfig?.defaultTimeoutMs ?? 3e5,
maxRetries: managerConfig?.defaultRetries?.maxRetries ?? 0
};
const agentToolConfig = resolveAgentToolConfig(toolName, agentConfig);
const baseEnabled = agentToolConfig?.enabled ?? toolConfig?.enabled ?? false;
const defaultDisposition = resolveDefaultDisposition({
toolName,
toolConfig,
agentConfig
});
const requestedDisposition = llmOverride?.disposition ?? (llmOverride?.enabled === false ? "foreground" : llmOverride?.enabled === true ? "deferred" : defaultDisposition);
const disposition = baseEnabled ? requestedDisposition : "foreground";
const timeoutMs = llmOverride?.timeoutMs ?? agentToolConfig?.timeoutMs ?? toolConfig?.timeoutMs ?? managerConfig?.defaultTimeoutMs ?? 3e5;
const maxRetries = llmOverride?.maxRetries ?? toolConfig?.maxRetries ?? managerConfig?.defaultRetries?.maxRetries ?? 0;
return {
runInBackground: disposition !== "foreground",
disposition,
timeoutMs,
maxRetries
};
}
/**
* Whether a tool is background-eligible: i.e. whether `resolveBackgroundConfig`
* could ever dispatch it to the background. This is the same base-enabled
* expression the runtime resolver uses (the LLM `_background` override is a
* modifier only, never a standalone opt-in — see issue #16783), so advertising
* paths (schema injection, system prompt) and dispatch cannot disagree.
*/
function isToolBackgroundEligible({ toolName, toolConfig, agentConfig }) {
if (agentConfig?.disabled) return false;
return resolveAgentToolConfig(toolName, agentConfig)?.enabled ?? toolConfig?.enabled ?? false;
}
/**
* The disposition an eligible tool resolves to when a call carries no
* `_background` override. Mirrors the fallback chain in
* `resolveBackgroundConfig` so advertising paths (system prompt) and dispatch
* cannot disagree.
*/
function resolveDefaultDisposition({ toolName, toolConfig, agentConfig }) {
return resolveAgentToolConfig(toolName, agentConfig)?.defaultDisposition ?? toolConfig?.defaultDisposition ?? "deferred";
}
function resolveAgentToolConfig(toolName, agentConfig) {
if (!agentConfig?.tools) return void 0;
if (agentConfig.tools === "all") return { enabled: true };
if (toolName.startsWith("agent-")) toolName = toolName.substring(6);
else if (toolName.startsWith("workflow-")) toolName = toolName.substring(9);
const entry = agentConfig.tools[toolName];
if (entry === void 0) return void 0;
if (typeof entry === "boolean") return { enabled: entry };
return entry;
}
// src/background-tasks/schema-injection.ts
/**
* JSON Schema definition for the `_background` override field.
* Injected into background-eligible tool schemas so the LLM can override behavior per-call.
*/
const backgroundOverrideJsonSchema = {
type: "object",
description: "Optional: override how this specific call executes (foreground, deferred, or awaited). When omitted, the tool's configured default disposition applies. The enabled boolean remains supported for compatibility.",
properties: {
enabled: {
type: "boolean",
description: "Force deferred (true) or foreground (false) execution for this call."
},
disposition: {
type: "string",
enum: [
"foreground",
"deferred",
"awaited"
],
description: "Choose foreground, deferred, or awaited execution for this call."
},
timeoutMs: {
type: "number",
description: "Override timeout in milliseconds for this call."
},
maxRetries: {
type: "number",
description: "Override maximum retry attempts for this call."
}
},
additionalProperties: false
};
const backgroundOverrideZodSchema = zod_v4.z.object({
enabled: zod_v4.z.boolean().optional().describe("Force deferred (true) or foreground (false) execution for this call."),
disposition: zod_v4.z.enum([
"foreground",
"deferred",
"awaited"
]).optional().describe("Choose foreground, deferred, or awaited execution for this call."),
timeoutMs: zod_v4.z.number().optional().describe("Override timeout in milliseconds for this call."),
maxRetries: zod_v4.z.number().optional().describe("Override maximum retry attempts for this call.")
}).optional().describe("Optional: override how this specific call executes (foreground, deferred, or awaited). When omitted, the tool's configured default disposition applies. The enabled boolean remains supported for compatibility.");
// src/background-tasks/system-prompt.ts
/**
* Generates the system prompt section that tells the LLM about background task capabilities.
*
* Only tools that `resolveBackgroundConfig` could actually dispatch to the
* background are listed (agent-level opt-in, falling back to tool-level
* config — see `isToolBackgroundEligible`). Returns undefined if no tools are
* background-eligible (nothing to inject).
*/
function generateBackgroundTaskSystemPrompt(tools, agentConfig) {
const eligibleTools = [];
for (const [toolName, tool] of Object.entries(tools)) {
const toolConfig = tool.backgroundConfig ?? tool.background;
if (isToolBackgroundEligible({
toolName,
toolConfig,
agentConfig
})) eligibleTools.push({
toolName,
defaultDisposition: resolveDefaultDisposition({
toolName,
toolConfig,
agentConfig
})
});
}
if (eligibleTools.length === 0) return;
return `You have the ability to run certain tools in the background while continuing the conversation. The following tools support background execution:
${eligibleTools.map(({ toolName, defaultDisposition }) => defaultDisposition === "deferred" ? `- ${toolName} (default: background)` : `- ${toolName} (default: foreground — opt in with "_background")`).join("\n")}
For any of these tools, you can include a "_background" field in the tool arguments to override the default:
"_background": { "disposition": "foreground" | "deferred" | "awaited", "timeoutMs": number, "maxRetries": number }
All fields in "_background" are optional. Only include what you want to override. Tools listed with "default: background" run in the background unless you set "disposition": "foreground". Tools listed with "default: foreground" run inline unless you explicitly request "deferred" or "awaited" — for those tools, omitting "_background" never starts background work.
Dispositions:
- "deferred": the tool runs in the background while you continue; you receive a placeholder result with a task ID and are notified when the task completes.
- "awaited": the tool runs as a durable background task but your run waits for its result before continuing.
- "foreground": the tool runs inline and returns its real result immediately.
Guidelines:
- Use background execution when the user doesn't need the result immediately, or when you're launching multiple independent tasks.
- Use foreground execution when the user is directly waiting for the result and the conversation can't continue without it.
- When a tool runs deferred, you'll receive a placeholder result with a task ID. You can reference this in your response to the user.
IMPORTANT: "_background" field is always an object. The fields in the _background field should be inside the _background object, not outside of it.`;
}
Object.defineProperty(exports, "BACKGROUND_TASK_WORKFLOW_ID", {
enumerable: true,
get: function() {
return BACKGROUND_TASK_WORKFLOW_ID;
}
});
Object.defineProperty(exports, "BackgroundTaskManager", {
enumerable: true,
get: function() {
return BackgroundTaskManager;
}
});
Object.defineProperty(exports, "backgroundOverrideJsonSchema", {
enumerable: true,
get: function() {
return backgroundOverrideJsonSchema;
}
});
Object.defineProperty(exports, "backgroundOverrideZodSchema", {
enumerable: true,
get: function() {
return backgroundOverrideZodSchema;
}
});
Object.defineProperty(exports, "createBackgroundTask", {
enumerable: true,
get: function() {
return createBackgroundTask;
}
});
Object.defineProperty(exports, "generateBackgroundTaskSystemPrompt", {
enumerable: true,
get: function() {
return generateBackgroundTaskSystemPrompt;
}
});
Object.defineProperty(exports, "isToolBackgroundEligible", {
enumerable: true,
get: function() {
return isToolBackgroundEligible;
}
});
Object.defineProperty(exports, "resolveBackgroundConfig", {
enumerable: true,
get: function() {
return resolveBackgroundConfig;
}
});
//# sourceMappingURL=background-tasks-CVddYnZ1.cjs.map