UNPKG

@mastra/core

Version:
126 lines • 7.05 kB
import type { BackgroundTaskManager } from '../../../background-tasks/manager.js'; import type { AgentBackgroundConfig, BackgroundExecutionDisposition, BackgroundTaskHandle, BackgroundTaskManagerConfig, CreateBackgroundTaskOptions, ToolBackgroundConfig } from '../../../background-tasks/types.js'; import type { IMastraLogger } from '../../../logger/index.js'; export type BackgroundDispatchOutcome = /** Background execution does not apply (or dispatch fell through) — run the tool synchronously. */ { status: 'sync'; } /** The tool call is now owned by a background task; engines return the * placeholder as the tool result so the LLM can continue — unless the * resolved `disposition` is `awaited`, in which case engines block the turn * on `waitForCompletion()` and return the authoritative result instead. */ | { status: 'started' | 'resumed' | 'restarted' | 'reattached' | 'reconciled'; taskId: string; placeholder: string; /** The resolved execution disposition (never `foreground` here — that * resolves to `runInBackground: false` and returns `sync` above). */ disposition: BackgroundExecutionDisposition; /** Blocks until the dispatched task reaches a terminal state. Engines * use this to honor the `awaited` disposition. */ waitForCompletion: BackgroundTaskHandle['waitForCompletion']; }; /** Per-dispatch info the ladder passes to the engine's lazy `taskContext` * builder so engine hooks can see the resolved disposition and the task id * (which only exists once the ladder has created/dispatched the task). */ export interface BackgroundTaskContextInfo { disposition: BackgroundExecutionDisposition; getTaskId: () => string | undefined; } /** * Shared background dispatch ladder: decide whether a tool * call runs as a background task and, if so, resume/restart/dispatch it. * Engines own the per-task context hooks (executor, onChunk, onResult, * onExecution — they close over engine transport and message-list state) and * how the placeholder projects onto their step output. * * The mechanics are shared; two rungs are per-engine policy (both required * params, so every call site's choice is explicit): * * - `existingRunningTask`: `'restart'` (durable) probes * `checkIfRunning` before dispatching and restarts an already-running task * for this toolCallId to reattach hooks — durable step redelivery * legitimately re-enters dispatch for the same toolCallId after a crash, * and dispatching again would duplicate background work on every * recovery. `'dispatch-duplicate'` (default engine) skips the probe * entirely and goes straight to `dispatch()` — the released in-process * contract; default dispatch is only re-entered by caller action, never * by transport redelivery, so the dedup problem doesn't exist and the * probe would add a storage read per dispatch that the released path * never made. * - `dispatchFailure`: `'fallback-to-sync'` (durable) degrades any * ladder failure (task creation, storage lookups, dispatch) to * synchronous execution — durable dispatch crosses transport/store * boundaries where transient failure is expected, and sync fallback * preserves forward progress. `'propagate'` (default engine) rethrows so * the failure surfaces as a tool error — the released contract; a tool * may be background *because* synchronous execution is unsafe, slow, or * process-affine, and an in-process dispatch failure indicates a * config/programmer error that silent sync execution would mask. * * Unconditional on both policies (each with pre-PR provenance on its own * engine): * - Started-chunk emission is best-effort: previously the durable engine * awaited its pubsub publish inside the ladder, so a transport failure * *after* dispatch fell back to sync and executed the tool twice. * - The suspended-task lookup only runs when a resume payload is present * (durable's gating; the main loop looked it up unconditionally but only * consumed the answer when resuming, so this is observably identical). * Nullish, not truthy: a tool with a primitive resumeSchema can be resumed * with `false` / `0` / `''`, and treating those as "no resume data" would * fall through to `dispatch()`, stranding the suspended task and starting * a second one. * - The `adoptPersistedTask` replay-adoption block (durable-only via its * existing flag, #24418) and the concurrency-limit `fallbackToSync` rung * (both engines' released contract). */ export declare function dispatchBackgroundTool(deps: { backgroundTaskManager: BackgroundTaskManager | undefined; agentBackgroundConfig: AgentBackgroundConfig | undefined; managerConfig: BackgroundTaskManagerConfig | undefined; toolBackgroundConfig: ToolBackgroundConfig | undefined; /** The LLM's per-call `_background` override (already stripped from args). */ llmBgOverrides: unknown; /** Tool args with `_background` removed. Non-object args never dispatch. */ args: unknown; toolName: string; toolCallId: string; agentId: string; threadId: string | undefined; resourceId: string | undefined; runId: string; /** Resume payload for a previously-suspended background task; engines pass * their own pre-gated value (undefined when this leg is not a resume). */ resumeData: unknown; /** Per-task hooks: executor + stream/result/execution injectors. Lazy: only * built once background dispatch is actually chosen (the main loop's * executor resolution can throw for tools its bg lookup can't see, which * now degrades to sync execution instead of failing the call). Receives the * resolved disposition and a task-id accessor so hooks can stamp background * work context / terminal notifications. */ taskContext: (info: BackgroundTaskContextInfo) => CreateBackgroundTaskOptions['context']; /** Emit the background-task-started chunk over engine transport. */ emitTaskStarted: (task: { id: string; }) => void | Promise<void>; /** Durable workflow steps may replay after the task reached persisted storage. */ adoptPersistedTask?: boolean; /** * What to do when a task for this toolCallId is already running: * `'restart'` (durable: redelivery dedup) probes * `checkIfRunning` and restarts to reattach hooks; `'dispatch-duplicate'` * (default engine: released contract) skips the probe entirely. */ existingRunningTask: 'restart' | 'dispatch-duplicate'; /** * What to do when the dispatch ladder throws: * `'fallback-to-sync'` (durable: forward progress across transport/store * failures) degrades to synchronous execution; `'propagate'` (default * engine: released contract) rethrows so the failure surfaces as a tool * error. */ dispatchFailure: 'fallback-to-sync' | 'propagate'; logger?: IMastraLogger; }): Promise<BackgroundDispatchOutcome>; //# sourceMappingURL=background-dispatch-core.d.ts.map