@mastra/core
Version:
186 lines • 9.56 kB
TypeScript
import type { MessageList } from '../../../agent/message-list/index.js';
import type { ProviderMetadata } from '../../../stream/types.js';
import type { ModelFacingValidationError } from '../../../tools/validation.js';
/** Minimal span surface for the MAPPING child span; both engines' spans satisfy it. */
interface MappingSpan {
end(options?: unknown): void;
error(options: unknown): void;
}
export interface ToolMappingParentSpan {
createChildSpan(options: unknown): MappingSpan | undefined;
}
/**
* Shared `toModelOutput` computation for the tool-result commit.
*
* Runs the tool's `toModelOutput` mapper under a MAPPING child span, normalizes
* media parts into the AI SDK's LanguageModelV2ToolResultOutput shape, and
* merges the mapped output into `providerMetadata.mastra.modelOutput`.
*
* A validation error Mastra produced for this call (`validationError`) is not
* the tool's output, so it skips the mapper: `toModelOutput` is typed to
* receive only successful output, and the model must see the error to retry.
* Its model-facing form, without the raw values the full error quotes, is
* stored as an `error-json` model output instead. A result that merely has a
* validation error's fields is mapped like any other result.
*
* A nullish mapping result means "no special mapping needed" — the raw result
* is already what the model should see. The key is not written in that case,
* because MessageList keys off its presence and would otherwise override the
* real result with `undefined`, producing a tool message with no output.
*
* Mapping failures propagate so a broken `toModelOutput` fails the run.
*
* A result from a tool an agent built from its `workflows` also gets
* `mastra.workflowTool: true`. Workflow tools can't define `toModelOutput`, so
* this per-call marker is how tracing knows it may show their result in the
* next MODEL_STEP input (#30219). The tool output the model receives is unchanged.
*
* Deliberately NOT consolidated with the background-task path
* (`background-task-result-core.ts`), which always overwrites
* `mastra.modelOutput` (null included) to clear the placeholder-derived value
* and runs without a tracing span. The presence-keyed omit here vs the
* always-overwrite there are both load-bearing; see its docblock.
*/
export declare function computeModelOutputProviderMetadata(deps: {
/** Pre-resolved tool. Engines own the lookup: run-scope stepTools / static
* tools on main, the in-process registry on durable. */
tool: {
toModelOutput?: (output: unknown) => unknown;
} | undefined;
toolName: string;
toolCallId?: string;
result: unknown;
/** Set only when Mastra's own validation rejected this call, read from the
* result in the process that ran the tool (`getModelFacingValidationError`).
* Never derived from the result's shape. */
validationError?: ModelFacingValidationError;
existingProviderMetadata?: Record<string, unknown>;
/** Parent for the MAPPING child span (main: current tracing span; durable:
* the MODEL_STEP span rebuilt from serialized state). */
parentSpan?: ToolMappingParentSpan;
}): Promise<Record<string, unknown> | undefined>;
/**
* Adds `mastra.workflowTool: true` to a result's provider metadata when `tool`
* is one an agent built from its `workflows`; otherwise returns it unchanged.
* Shared by every engine path that records a tool result (#30219). The stored
* tool-invocation part holds call and result together, so prompts carry the
* marker on both the tool-call and tool-result parts, under `providerOptions.mastra`,
* which provider adapters don't read.
*/
export declare function withAgentWorkflowToolMarker<T extends Record<string, any> | undefined>(providerMetadata: T, tool: unknown): T | Record<string, any>;
/** The mapped `toModelOutput` value carried in `providerMetadata.mastra.modelOutput`, if any. */
export declare function readModelOutput(providerMetadata: Record<string, unknown> | undefined): unknown;
/** Whether any output processor (or processor workflow) can run `processToolResult`. */
export declare function hasToolResultProcessor(processors: readonly unknown[] | undefined): boolean;
/**
* A content snapshot of a tool result taken before `processToolResult` runs, so a
* processor that edits the result in place (same object, new contents) is still
* seen as having changed it. Undefined when the result can't be serialized; then
* only a replaced object counts as a change.
*/
export declare function snapshotToolResult(result: unknown): string | undefined;
/**
* The mapped output the next `processToolResult` should see: the one an earlier
* processor committed in `providerMetadata.mastra.modelOutput` (undefined when it
* cleared it), otherwise `fallback`, the output mapped before the hook.
*/
export declare function latestProcessedModelOutput(messageList: MessageList, toolCallId: string, fallback: unknown): unknown;
/**
* Resolve the model output after `processToolResult` ran.
*
* Processors rewrite a tool result by committing a `result`-state part through
* `messageList.updateToolInvocation`. That part may carry a replacement
* `providerMetadata.mastra.modelOutput` (e.g. resized or removed images); it
* then replaces the mapped output. A processor that only replaces the raw
* `result` gets it re-mapped through `toModelOutput`, so the model never sees
* the mapping of the value the processor replaced. Without either, the output
* mapped before the hook stands and `toModelOutput` is not called again. A
* result edited in place counts as replaced when its contents differ from
* `resultSnapshotBeforeProcessors`.
*
* When the tool resolved with Mastra's own validation error (`validationError`),
* a rewrite that is still a validation error (say, a redaction pass over every
* result) skips the mapper and sends the model-facing error, as the mapping
* before the hook did. A processor that replaced the error with any other value
* made that value the tool's output, so it is mapped.
*/
export declare function resolveModelOutputAfterToolResultProcessors(deps: {
messageList: MessageList;
tool: {
toModelOutput?: (output: unknown) => unknown;
} | undefined;
toolName: string;
toolCallId: string;
/** The result the processors were given. */
resultBeforeProcessors: unknown;
/** `snapshotToolResult(resultBeforeProcessors)`, taken before the processors ran. */
resultSnapshotBeforeProcessors?: string;
/** Metadata computed before the processors ran, including the mapped output. */
providerMetadata: Record<string, unknown> | undefined;
/** Mastra's validation error for `resultBeforeProcessors`, read from the live
* result in the process that ran the tool (`getModelFacingValidationError`).
* A processor's rewrite is a copy without the marker, so it cannot be read
* from the processed result. */
validationError?: ModelFacingValidationError;
parentSpan?: ToolMappingParentSpan;
}): Promise<Record<string, unknown> | undefined>;
/** Resolved terminal state for one tool call, as recorded to the transcript. */
export type ToolResultCommitOutcome = {
kind: 'denied';
approval: {
id: string;
approved: false;
reason?: string;
};
}
/** `result` on an error outcome carries a structured payload alongside the
* error text — e.g. a failed sub-agent's partial result — so the model can
* read what the delegate produced before it failed, not just the message. */
| {
kind: 'error';
errorText?: string;
result?: unknown;
} | {
kind: 'result';
result: unknown;
};
/**
* Shared per-result transcript commit: record one resolved
* tool call on the MessageList as `output-denied`, `output-error`, or
* `result`. Returns whether a matching invocation was found and updated.
*
* Adjudications:
* - `sanitizeToolName` on every commit: main-only since #13633 (Bedrock
* rejects unsanitized hallucinated names on replay); dated drift — durable
* adopts via this core.
* - `errorText` fallback to 'Tool execution failed': same drift class — an
* empty error message otherwise persists a failure with no explanation.
* - `fallbackAppend` (durable true / main false): after a process hop the
* merge step may operate on a MessageList rebuilt from serialized state
* where the original call part is missing — losing a completed result is
* worse than appending a standalone tool message. In main the list is the
* same live object that recorded the call, so a miss indicates corruption
* and appending would mask the real bug. C1-forced deliberate difference,
* not drift.
*/
export declare function commitToolResult(deps: {
messageList: MessageList;
outcome: ToolResultCommitOutcome;
toolCallId: string;
toolName: string;
toolArgs: unknown;
/** Approval decision for an approved approval-gated tool, preserved so it
* round-trips on recall (denied outcomes carry their own decision). */
approval?: {
id: string;
approved: boolean;
reason?: string;
};
/** Fully-merged metadata for the commit. Engines own the merging: main
* layers transform metadata on top from the live chunk; durable layers it
* from the `transformMetadata` carried on the serialized step output (L18b). */
providerMetadata?: ProviderMetadata;
fallbackAppend?: boolean;
}): boolean;
export {};
//# sourceMappingURL=tool-result-commit-core.d.ts.map