@mastra/core
Version:
268 lines • 13.7 kB
TypeScript
import type { AgentBackgroundConfig } from '../../../background-tasks/types.js';
type EagerToolResult = unknown;
/**
* Marker placed on the workflow execution context when `toolCallStep` is invoked
* eagerly from the LLM execution step. Its presence tells the step not to look
* for (and await) an eager execution of itself.
*/
export declare const EAGER_TOOL_EXECUTION_MARKER: unique symbol;
/**
* Carries the coordinator's per-execution abort signal into `toolCallStep`. A dedicated
* key rather than the step's own `abortSignal` argument, so no other caller's behaviour
* changes: the step combines this with the run signal only when it is present.
*/
export declare const EAGER_TOOL_ABORT_SIGNAL: unique symbol;
/**
* Carries a per-dispatch bailout record into `toolCallStep`, so a call that turns out to
* need suspension can mark itself unusable *before* throwing.
*
* The throw alone is not fail-safe: it unwinds through the tool's own body, and a tool
* that wraps its work in try/catch swallows it and returns normally. The step would then
* resolve an ordinary-looking envelope and the foreach would adopt a result for a call
* that asked to suspend. The dispatcher re-reads this record after the step settles and
* converts any marked settlement back into a rejection.
*
* One record per dispatch, so a later attempt reusing the same toolCallId cannot observe
* a previous attempt's bailout.
*/
export declare const EAGER_TOOL_BAILOUT: unique symbol;
/** Set by `toolCallStep` when an eagerly dispatched call bails out. */
/**
* What an eagerly dispatched tool asked for when it called `suspend()` at runtime.
*
* The eager attempt is abandoned before any suspension side effect happens, so this
* intent is what the adopting foreach iteration replays: it raises the real suspension
* from the owning iteration instead of re-running the tool body from the top.
*
* The options are an explicit pick rather than the whole `SuspendOptions`, which is
* `{ resumeLabel?: string | string[] } & Record<string, any>` — carrying it verbatim
* would make the carrier unbounded and let a caller smuggle arbitrary keys across.
*/
export type EagerSuspensionIntent = {
suspendPayload: unknown;
options: {
resumeLabel?: string | string[];
resumeSchema?: unknown;
runId?: string;
requireToolApproval?: boolean | {
toolName?: string;
args?: unknown;
};
};
};
export type EagerToolBailout = {
reason?: string;
/**
* Set when the bailout was caused by a runtime `suspend()` call, carrying what the
* tool asked to suspend with. Recorded before the throw for the same reason `reason`
* is: a tool that catches the throw would otherwise return normally and lose it.
*/
suspension?: EagerSuspensionIntent;
/**
* Set once the eager attempt has run the tool's `onInputAvailable`. The hook is
* announced before `execute`, so a bailout that happens inside the tool body has
* already fired it; the foreach re-runs the same `execute` function and would
* otherwise announce the same `toolCallId` a second time.
*/
inputAvailableCalled?: boolean;
};
/** Brands errors whose eager attempt produced no adoptable result. */
declare const EAGER_NOT_EXECUTED: unique symbol;
/** Brands a bailout whose eager attempt already announced `onInputAvailable`. */
declare const EAGER_INPUT_ANNOUNCED: unique symbol;
/** Carries a runtime suspension's intent out of the attempt that was abandoned for it. */
declare const EAGER_SUSPENSION_INTENT: unique symbol;
/**
* A tool call that ran to completion eagerly but was never adopted, because the model
* attempt it belonged to was thrown away. The side effect already happened, so the
* caller commits this into the conversation rather than letting the replacement
* attempt run the same tool a second time.
*/
export type CompletedEagerWork = {
toolCallId: string;
toolName: string;
args: unknown;
/** The tool's own output, unwrapped from the step's envelope. Absent when it threw. */
result?: unknown;
/** What the tool threw. A failed call is still a call that ran. */
error?: unknown;
/**
* The tool started but had no outcome when the run's cancellation window expired.
* Kept so the aborted run emits and records a cancellation notice as its tool result.
*/
incomplete?: true;
/**
* The order the model emitted this call in. Executions settle in whatever order they
* finish, and history is written in model-call order everywhere else, so the caller
* sorts by this before committing anything.
*/
sequence: number;
};
/**
* Starts eligible server-side tool executions while the model is still streaming,
* and hands the in-flight promise to `toolCallStep` so the existing foreach remains
* the owner of result ordering and history.
*
* The permit limit is read through `getConcurrency` rather than copied, because
* `map-tool-calls` recomputes the effective limit per step (an approval- or
* suspend-capable tool entering the step forces the foreach down to 1). Reading it
* late keeps one source of truth for the limit.
*/
export declare class EagerToolExecutionCoordinator {
#private;
private readonly getConcurrency;
constructor(getConcurrency: () => number);
/**
* Hand over the in-flight eager execution for a tool call, if one was started,
* and forget it. Taking rather than reading keeps adoption exactly-once: a later
* iteration that reuses the same `toolCallId` executes again instead of adopting
* the previous iteration's settled result.
*/
take(toolCallId: string): Promise<unknown> | undefined;
/**
* Start an eager execution keyed by canonical `toolCallId`. Returns false when the
* coordinator is stopped or the id is already in flight, so a replayed or duplicate
* id within the same step can never execute twice.
*/
start(toolCallId: string, execute: (abortSignal: AbortSignal) => Promise<EagerToolResult>, call?: {
toolName: string;
args: unknown;
}): boolean;
/** Number of executions currently running. Exposed for assertions in tests. */
get running(): number;
/**
* Stop dispatching and drop everything that has not started.
*
* Without `cancelRunning`, executions already in flight are left alone: the step that
* follows an unsafe *finish* still runs its foreach, so their results are adopted
* exactly as the default pipeline would have produced them.
*
* With `cancelRunning`, the surrounding model attempt is being thrown away entirely.
* Those executions are aborted *and* forgotten, so nothing downstream can adopt work
* belonging to an attempt that no longer exists — including a retry that happens to
* reuse the same toolCallId, which must execute fresh. Their concurrency permits are
* released at the same moment: abort is cooperative, and a tool that declines to
* observe it must not stall the attempt that replaced it.
*/
stop({ permanent, cancelRunning, keepIncomplete, }?: {
permanent?: boolean;
cancelRunning?: boolean;
keepIncomplete?: boolean;
}): CompletedEagerWork[];
/** Start once at run abort, including when the foreach is already awaiting adoption. */
settleOnAbort(): Promise<void>;
/**
* Wait until every execution that has started has settled, however it settles. Called
* with dispatch already stopped, so nothing new starts meanwhile.
*
* A discarded attempt waits here instead of cancelling: a running tool may already have
* done its side effect, and cancelling it would leave the replacement attempt free to
* call it again. Settled, its outcome is committed and the replacement sees it as done.
* An abort of the run stops the wait; the abort exit then waits the work out itself.
*/
settleRunning(signal?: AbortSignal): Promise<void>;
/**
* Open a new model turn. A stop caused by a bad turn is scoped to that turn — the
* next one is a fresh model call and may dispatch again — but a caller abort is
* permanent. Executions from the previous turn that nothing ever adopted are dropped
* here so the map cannot grow across a long loop.
*/
beginTurn(): void;
/** Whether a call in this attempt has already run up to a runtime `suspend()`. */
get hasSuspendedHandback(): boolean;
/** Ids currently held for adoption. Exposed for assertions in tests. */
get pendingAdoptions(): number;
/**
* Hold a discarded attempt's finished work until a replacement attempt starts. Each
* batch is sorted into model-call order as it arrives, and batches keep the order they
* were discarded in. The dispatch counter happens to be run-global, so sorting the whole
* buffer would agree today — sorting per batch keeps that coincidence from becoming
* load-bearing.
*/
carryDiscardedWork(work: CompletedEagerWork[]): void;
/** Drain the carried work for committing into the conversation. */
takeCarriedWork(): CompletedEagerWork[];
/** Remember what was written where, so a later removal of that message can undo it. */
recordCommittedWork(messageId: string, work: CompletedEagerWork[]): void;
/**
* Undo a commit whose message is being removed: the work goes back into the carry
* buffer so the next replacement attempt writes it again. Without this, a processor
* retry that deletes the attempt's messages would also delete the only record that a
* tool already ran, and the tool would run a second time.
*
* What comes back goes on the end of whatever is already carried, so the resulting
* order is "work already written once, then work never written".
*/
recarryCommittedWork(messageId: string): boolean;
/** Discarded work awaiting a replacement attempt. Exposed for assertions in tests. */
get carriedWork(): readonly CompletedEagerWork[];
}
/**
* Raised when an eager attempt ends without producing an adoptable result, so the
* normal foreach path must handle the call instead of surfacing the failure. That
* happens when the attempt is cancelled while still queued, and when an eager call
* reaches a suspend/bail it should have been excluded from. In the second case the
* tool's body has already started; only its *result* is discarded.
*/
export declare class EagerToolExecutionNotRun extends Error {
readonly [EAGER_NOT_EXECUTED] = true;
readonly [EAGER_INPUT_ANNOUNCED]: boolean;
readonly [EAGER_SUSPENSION_INTENT]?: EagerSuspensionIntent;
constructor(reason: string, options?: {
inputAvailableCalled?: boolean;
suspension?: EagerSuspensionIntent;
});
}
/**
* The suspension intent behind this rejection, when the eager attempt was abandoned
* because the tool called `suspend()` at runtime. The adopting foreach iteration uses
* it to raise the real suspension rather than running the tool body a second time.
*/
export declare function eagerToolCallSuspensionIntent(error: unknown): EagerSuspensionIntent | undefined;
/**
* True when the eager attempt behind this rejection already ran the tool's
* `onInputAvailable`. The foreach re-runs `execute` from the top, so it has to skip
* the announcement it already produced: one call per adoption, the same count the
* call gets without eager dispatch. (An attempt abandoned in flight is a separate
* matter: it is never adopted, so the replacement attempt announces again.)
*/
export declare function eagerToolCallAlreadyAnnouncedInput(error: unknown): boolean;
/**
* True when an eager execution ended without an adoptable result, meaning the normal
* foreach path must handle the call instead of surfacing the failure. The tool body
* may have started (a runtime suspension gets here); only its result is discarded.
*/
export declare function eagerToolCallDidNotExecute(error: unknown): boolean;
/**
* Whitelist deciding what may be executed before the model has finished streaming.
*
* This is deliberately an allow-list rather than a list of exclusions. An eager
* execution that turns out to need approval, suspension or a background dispatch has
* already emitted chunks and written metadata by the time it discovers that, and none
* of it can be taken back — so the only safe posture is to start nothing whose shape
* is not provably a plain server-side call.
*
* Eligible means: a resolved, active, locally-executable Mastra tool, with complete
* arguments, that cannot suspend (mirroring the `isResumableTool` rule in
* `tool-builder/builder.ts`), cannot require approval, and is not being dispatched as
* a background task.
*/
export declare function isEagerlyExecutableToolCall({ toolCall, tool, activeTools, requireToolApproval, autoResumeSuspendedTools, hasPostStreamProcessor, hasToolResultProcessor, isProviderTool, getNeedsApprovalFn, backgroundTaskManager, agentBackgroundConfig, }: {
toolCall: {
toolName: string;
args?: unknown;
providerExecuted?: boolean;
};
tool: unknown;
activeTools: string[] | undefined;
requireToolApproval: unknown;
autoResumeSuspendedTools: boolean | undefined;
hasPostStreamProcessor: boolean;
hasToolResultProcessor: boolean;
isProviderTool: (tool: any) => boolean;
getNeedsApprovalFn: (tool: any) => unknown;
backgroundTaskManager: unknown;
agentBackgroundConfig: AgentBackgroundConfig | undefined;
}): boolean;
export {};
//# sourceMappingURL=eager-tool-execution.d.ts.map