/** * TaskService: the runtime singleton that polls `queue`-tagged tasks and runs * their registered worker when due. Owns the tick loop — a local timer armed * for the earliest due task, a shared task-scheduler daemon, or serverless * `runDueTasks()` — plus repeat-task cadence, failure backoff and auto-pause, * and overlap suppression for blocking runs. Registered by the basic-capabilities plugin and reached * via `runtime.getService(ServiceType.TASK)`. */ import type { UUID } from "../types/primitives.js"; import type { IAgentRuntime } from "../types/runtime.js"; import { Service } from "../types/service.js"; import type { Task, TaskRunStatus } from "../types/task.js"; /** * Runtime setting that overrides the longest sleep (ms, MIN_TICK_MS to * MAX_TIMEOUT_MS). 1000 keeps the old 1 s poll. */ export declare const TASK_TICK_MAX_MS_SETTING = "TASK_TICK_MAX_MS"; /** * The system clock checks the wall clock this often during a long sleep, with * no query. Timers count monotonic time, which stops while the device is * suspended and ignores wall-clock changes; this check keeps an overdue task * within 1 s of resume or of a clock jump, as with the old poll. */ export declare const WALL_CLOCK_CHECK_MS = 1000; /** Opaque handle returned by an injected task-service timer implementation. */ export type TaskServiceTimerHandle = unknown; /** A one-shot timer clock. `setTimeout` fires once, at or after now() + delayMs. */ export interface TaskServiceTimeoutClock { now(): number; setTimeout(callback: () => Promise, delayMs: number): TaskServiceTimerHandle; clearTimeout(handle: TaskServiceTimerHandle): void; } /** @deprecated The old repeating-timer clock shape; give setTimeout/clearTimeout instead. */ export interface TaskServiceIntervalClock { now(): number; setInterval(callback: () => Promise, intervalMs: number): TaskServiceTimerHandle; clearInterval(handle: TaskServiceTimerHandle): void; } /** * Time boundary used by TaskService. Production uses the system clock and * timeout APIs; deterministic hosts can supply a virtual clock without * replacing task persistence, validation, or worker execution. The old * setInterval/clearInterval shape still works and is used one shot at a time. */ export type TaskServiceClock = TaskServiceTimeoutClock | TaskServiceIntervalClock; /** * Fire `callback` once Date.now() reaches now + delayMs. Sleeps in pieces of * at most WALL_CLOCK_CHECK_MS so a suspend or a wall-clock jump forward * delays it by at most one piece. */ export declare const systemTaskServiceClock: TaskServiceTimeoutClock; /** * Each tick validates due `queue` tasks against their worker's `shouldRun`, * then runs `worker.execute`. Repeat tasks reschedule on their interval (with * failure backoff); one-shot tasks are deleted after running. A task paused via * `metadata.paused` (operator or API) is skipped by every tick regardless of * tags — a paused one-shot stays in the store until it is resumed. */ export declare class TaskService extends Service { private timer; private hasTimer; /** Time (ms) the armed timer fires. */ private timerAt; /** True once startTimer() runs the local timer (not serverless, no daemon). */ private localTimer; private maxTickMs; private activeTick; private schedulerDrain; private readonly clock; /** Count overlapping invocations so exclusivity sees every active owner. */ private executingTasks; /** Admitted execution operations include preflight, storage reads and worker settlement. */ private pendingOperations; /** Tracks tasks quarantined for missing workers, preventing repeated diagnostics while pause/delete operations settle. */ private quarantinedOrphans; /** * Service construction time (epoch-ms). A missing worker inside * {@link TaskService.ORPHAN_GRACE_MS} of this moment is treated as "not * registered YET" (boot ordering: the first tick can start before every plugin * has registered its workers), not as an orphan. WHY: without the grace, a * healthy task whose plugin registers a beat later was wrongly quarantined — * repeat tasks auto-paused, one-shots DELETED — and the first tick emitted * the TASK_WORKER_MISSING diagnostic that painted red system lines into the * owner's chat view on every boot. */ private readonly startedAt; /** Closes admission synchronously before runtime teardown; active work still drains. */ private stopped; /** * Boot grace window (ms) during which a missing worker is skipped silently * instead of quarantined. 60s comfortably covers slow plugin boots (remote * capability sync, late schema migrations) while still healing a genuinely * orphaned row within the first minute of steady-state. */ private static readonly ORPHAN_GRACE_MS; static serviceType: "task"; capabilityDescription: string; constructor(runtime?: IAgentRuntime, clock?: TaskServiceClock); /** * Start the TaskService with the given runtime. * @param {IAgentRuntime} runtime - The runtime for the TaskService. * @returns {Promise} A promise that resolves with the TaskService instance. */ static start(runtime: IAgentRuntime): Promise; /** * Start the task poll timer. Call explicitly in daemon mode; not started automatically. * WHY public: initialize() does not start the task service or timer. Daemon entry points * that need scheduled tasks call getService("task") then startTimer(). Edge/ephemeral * runtimes typically do not call this. * Priority: (1) serverless -> no timer, host calls runDueTasks(); (2) daemon present -> register, no local timer; (3) else a local timer. * WHY serverless first: no long-lived process; WHY daemon second: one shared getTasks(agentIds) per tick for all agents. * The local timer sleeps until the earliest due task (at most TASK_TICK_MAX_MS) and markDirty() wakes it. */ startTimer(): void; /** Make sure a tick runs at or before `at`. A later timer is replaced; an earlier one is kept. */ private armTimer; private clearTimer; private onTimer; /** * Next tick time for a non-empty queue: the earliest due task, or now + * MIN_TICK_MS when a task is already due, capped at now + maxTickMs. * Paused, quarantined and invalid tasks never run from a tick, so they are * left out; a resume or fix is a task write, and that calls markDirty(). * The rows are the ones read before this tick runs them, so a task that runs * now is still "due" here and gets one more check MIN_TICK_MS later; that * check sees its new lastRan and sleeps until its next run. */ private nextWakeAt; /** * Validates an array of Task objects. * Skips tasks without IDs or if no worker is found for the task. * Uses worker.shouldRun(runtime, task) when present; otherwise the task passes. * @param {Task[]} tasks - An array of Task objects to validate. * @returns {Promise} - A Promise that resolves with an array of validated Task objects. */ private validateTasks; /** * Self-heal an orphaned task whose worker is not registered in this build. * Repeat orphans are PAUSED (survive a redeploy that re-registers the worker, * and can be un-paused/inspected by an operator); non-repeat orphans are * DELETED (a one-shot with no worker can never run — keeping it would re-fail * every tick with no backoff). Marks the id quarantined and emits the * diagnostic ONCE. WHY once: without the mark, every tick re-emitted * TASK_WORKER_MISSING which the RECENT_ERRORS provider + repeat-escalation * narrated into the owner's chat repeatedly (the observed 9× slop). A best- * effort persistence failure is reported (once) but still marks quarantined * so we don't renarrate on the next tick; the row will simply be re-healed if * it reappears (idempotent pause/delete). */ private quarantineOrphanTask; /** * Resume a repeat task that quarantineOrphanTask paused (orphanedNoWorker * marker) now that its worker is registered again (plugin reloaded / build * redeployed). Clears the pause + marker + lastError and drops the in-memory * quarantine mark so a FUTURE disappearance re-heals and re-diagnoses once. * Best-effort: a failed resume write is logged and retried on the next tick * (the task simply stays paused until the write succeeds). */ private resumeHealedOrphanTask; private invalidScheduleField; /** * Checks tasks with the "queue" tag, validates them, then executes via runTick. * Sets `wake.at` to the next tick time before running. An empty queue sets it to * null: the timer then sleeps until markDirty(). A failed query leaves the caller's * retry time. */ private checkTasks; /** * Validate and execute due tasks. Used by checkTasks (local timer) and by the task-scheduler daemon (batch tick). * Does NOT call getTasks — caller must pass the task list. WHY: daemon does one getTasks(agentIds) then dispatches to N runTicks. * No-op when service is already stopped (daemon may call after unregister). */ runTick(tasks: Task[]): Promise; private runTickInternal; private executeTaskCollectingFailure; private assertAcceptingExecution; private releaseExecution; private withExecutionAdmission; /** * Executes a given task asynchronously. * Tracks execution state to prevent overlapping runs of the same task. * On success: resets failureCount, applies nextInterval if returned, writes updatedAt. Non-repeat tasks are deleted. * On failure: repeat tasks get backoff (using baseInterval so we don't compound), auto-pause after maxFailures; non-repeat tasks are deleted so they don't retry forever. * WHY delete non-repeat on failure: otherwise they stay in DB and run every tick with no backoff (infinite retry loop). * WHY backoff uses baseInterval: after N failures updateInterval is already large; using it again would be exponential-of-exponential. * * @param {Task} task - The task to be executed. */ private executeTask; /** * Called after a task write. Wakes the local timer within MIN_TICK_MS (the old * tick bound) so a new or changed task is seen. When the daemon is running, * notifies it instead. Hosts with their own resume or time-change signal may * call it too; the system clock already re-reads the wall clock each second. */ markDirty(): void; /** * Run due queue tasks once. For serverless: call from cron or on each request. * Does getTasks for this agent's queue tasks then runTick (validate + execute due). * WHY separate from timer: serverless has no long-lived process; host drives execution explicitly. */ runDueTasks(): Promise; /** * Executes a task by ID. Loads the task, then runs it via executeTask. * @param taskId - UUID of the task. */ executeTaskById(taskId: UUID): Promise; /** * Writes a key-level metadata change. The adapter's atomic patch keeps a * concurrent writer's keys intact (an operator pause landing during a run's * bookkeeping, or vice versa); when the adapter has no atomic patch, the * change is merged over the freshest snapshot the caller read and written * whole. `unset` keys are removed in both modes. */ private persistTaskMetadata; /** * Pauses a task. Every scheduler tick AFTER the pause is persisted skips * the task until it is resumed, and a paused task is never deleted by the * tick loop. * * Already-selected-work semantics: Task rows carry no version column, so * pause is not CAS-atomic with tick selection. A tick that captured its * Task snapshot BEFORE the pause landed may execute that one selection to * completion (including the normal one-shot delete). Everything selected * afterwards observes `metadata.paused` and skips. Callers needing * hard at-most-zero execution must gate the worker itself (e.g. check * paused inside worker.execute). * * Preserves existing metadata (updatedAt, updateInterval, etc.). */ pauseTask(taskId: UUID): Promise; /** * Resumes a task. If runImmediately is true, runs the task once after unpausing. * Unpauses before executing so a failed run does not leave the task paused. */ resumeTask(taskId: UUID, runImmediately?: boolean): Promise; /** * Returns run status for a task: task, paused, executing, nextRunAt (repeat only), lastError. */ getTaskStatus(taskId: UUID): Promise; /** * Stops the TASK service in the given agent runtime. * * @param {IAgentRuntime} runtime - The agent runtime containing the service. * @returns {Promise} - A promise that resolves once the service has been stopped. */ static stop(runtime: IAgentRuntime): Promise; /** Stop new ticks before the runtime closes room admissions. */ prepareStop(): void; stop(): Promise; }