UNPKG

@mastra/core

Version:
153 lines • 9.23 kB
import type { Agent } from '../agent/index.js'; import type { SpanChunk } from '../agent/message-list/message-part-spans.js'; import { MessagePartSpans } from '../agent/message-list/message-part-spans.js'; import type { MastraDBMessage } from '../agent/message-list/state/types.js'; import type { AgentThreadSubscription } from '../agent/types.js'; import type { RequestContext } from '../request-context/index.js'; import type { Session, SessionMachinery } from './session.js'; type StreamChunkBase<TType extends string> = { type: TType; runId?: string | null; metadata?: unknown; }; type StreamPayloadChunk<TType extends string> = StreamChunkBase<TType> & { payload?: unknown; }; type StreamObjectChunk<TType extends string> = StreamChunkBase<TType> & { object?: unknown; }; type StreamDataChunk<TType extends `data-${string}`> = StreamChunkBase<TType> & { data?: unknown; }; type StreamIgnoredChunk = StreamPayloadChunk<'start'> | StreamPayloadChunk<'thread-history'> | StreamPayloadChunk<'abort'> | StreamPayloadChunk<'response-metadata'> | StreamPayloadChunk<'reasoning-signature'> | StreamPayloadChunk<'source'> | StreamPayloadChunk<'file'> | StreamPayloadChunk<'reasoning-file'> | StreamPayloadChunk<'custom'> | StreamPayloadChunk<'raw'> | StreamPayloadChunk<'step-start'> | StreamPayloadChunk<'tool-output'> | StreamPayloadChunk<'tool-call-resumed'> | StreamPayloadChunk<'step-output'> | StreamPayloadChunk<'watch'> | StreamPayloadChunk<'background-task-started'> | StreamPayloadChunk<'background-task-completed'> | StreamPayloadChunk<'background-task-failed'> | StreamPayloadChunk<'background-task-progress'> | StreamPayloadChunk<'background-task-running'> | StreamPayloadChunk<'background-task-cancelled'> | StreamPayloadChunk<'background-task-output'> | StreamPayloadChunk<'background-task-suspended'> | StreamPayloadChunk<'background-task-resumed'> | StreamObjectChunk<'object'> | StreamObjectChunk<'object-result'>; type StreamChunk = StreamIgnoredChunk | SpanChunk | StreamPayloadChunk<'tool-call-input-streaming-start'> | StreamPayloadChunk<'tool-call-delta'> | StreamPayloadChunk<'tool-call-input-streaming-end'> | StreamPayloadChunk<'tool-call'> | StreamPayloadChunk<'tool-result'> | StreamPayloadChunk<'tool-error'> | StreamPayloadChunk<'tool-output-denied'> | StreamPayloadChunk<'tool-call-approval'> | StreamPayloadChunk<'tool-call-suspended'> | StreamPayloadChunk<'error'> | StreamPayloadChunk<'tripwire'> | StreamPayloadChunk<'step-finish'> | StreamPayloadChunk<'finish'> | StreamPayloadChunk<'goal'> | StreamPayloadChunk<'is-task-complete'> | StreamDataChunk<'data-om-status'> | StreamDataChunk<'data-om-observation-start'> | StreamDataChunk<'data-om-observation-end'> | StreamDataChunk<'data-om-observation-failed'> | StreamDataChunk<'data-om-buffering-start'> | StreamDataChunk<'data-om-buffering-end'> | StreamDataChunk<'data-om-buffering-failed'> | StreamDataChunk<'data-signal'> | StreamDataChunk<'data-user-message'> | StreamDataChunk<'data-system-reminder'> | StreamDataChunk<'data-om-activation'> | StreamDataChunk<'data-om-thread-update'> | StreamDataChunk<'data-mastracode-tool-progress'> | StreamDataChunk<'data-sandbox-stdout'> | StreamDataChunk<'data-sandbox-stderr'> | StreamDataChunk<'data-sandbox-exit'>; type StreamState = { resourceId: string; threadId?: string; currentMessage: MastraDBMessage; lastFinishedMessage?: MastraDBMessage; messageStarted: boolean; isSuspended: boolean; spans: MessagePartSpans; announcedTextSpans: Set<string>; announcedReasoningSpans: Set<string>; messageIdObserved: boolean; toolPartById: Map<string, number>; /** Response ids offered by `step-start` — an id binds to at most one display message. */ offeredResponseIds: Set<string>; completedToolPrelude: boolean; /** * Set when a stream ends on a non-success finish reason (e.g. `content-filter`, * `error`, `length`). Carries the user-facing message so the run finalizes * into an explicit terminal error state instead of silently completing. */ terminalError?: string; terminalFinishReason?: string; }; /** * The per-session agent run engine: it consumes an agent's event stream, folds * each chunk into the session's display messages and token usage, drives tool * approval/suspension, and finalizes the run. In the multi-user host the run * loop, run state, and thread stream are per-session and cannot be shared, so * they live on the Session — this engine is owned by exactly one Session. * * It reaches the host only through the narrow {@link SessionMachinery} it is * constructed with (resolve the agent, build run/stream options, persist usage, * drive tool approval/resume, drain follow-ups). It never reaches back into the * AgentController or another session: all per-run state is read and written on its own * {@link Session}. */ export declare class SessionRunEngine { #private; constructor(session: Session, machinery: SessionMachinery); private createEmptyAssistantMessage; /** * Build a DB-native signal message from a streamed `data-signal` / * `data-user-message` / `data-system-reminder` chunk. The raw data-part is * carried verbatim on `content.parts` and the signal identity is preserved on * `content.metadata.signal` so consumers read the native shape (no flattening). */ private createSignalMessage; private hasCurrentMessageContent; private isCurrentMessageObserved; private setStopReason; private setErrorMessage; private stampResponseModel; private startCurrentMessage; private emitMessagePart; private emitInitialPart; private finishCurrentMessage; private finishCurrentMessageAndRotate; createStreamState(threadId?: string | undefined, resourceId?: string): StreamState; /** * Fold a `tool-result`/`tool-error` chunk into the invocation part and * notify — an errored tool must reach a terminal state or clients spin forever. */ private applyToolOutcome; /** Open an `agent-<key>` delegation in `activeSubagents`, taking its task from the tool call's prompt. */ private startDelegatedSubagent; /** Close an `agent-<key>` delegation once its tool call settles. */ private endDelegatedSubagent; private abortForOmFailure; /** * Process a stream response. Production runs stream through * `processSubscribedThreadStream`; only tests call this entry directly. */ processStream(response: { fullStream: AsyncIterable<StreamChunk>; }, requestContextInput?: RequestContext): Promise<{ message: MastraDBMessage; suspended?: boolean; } | undefined>; /** * Mutates and emits one live accumulated message throughout the assistant turn. * Consumers that require a point-in-time value must copy or serialize at their * ownership boundary. Do not restore producer-side per-delta snapshots: even * selective snapshots retain growing historical text and allocate message/part * shells for every token. */ processStreamChunk(state: StreamState, chunk: StreamChunk, requestContext: RequestContext, agent?: Agent): Promise<{ message: MastraDBMessage; suspended?: boolean; } | undefined>; /** * Settle parked native tool suspensions before aborting their suspended run. * The run cannot emit another chunk after `suspend()`, so update the saved * assistant message directly instead of leaving its tool invocation in * `state: 'call'` forever. * * Each suspension is settled through its own originating binding: the agent * retained on its run scope and the thread/resource it was persisted under. * The session may have been rebound (new thread, resource, or agent) while * the run stayed suspended, so the current binding cannot be assumed. If one * suspension fails to settle, the rest are still attempted and the first * error is rethrown for the caller to surface. */ settleSuspendedToolCallsAsDenied(suspensions: Array<{ toolCallId: string; runId: string; toolName: string; threadId: string; resourceId: string; }>): Promise<void>; /** * Mark a tool call as denied on the in-flight assistant message and notify * subscribers, mirroring what the `tool-output-denied` chunk would do. Used * when the run is torn down before that chunk can be consumed (abort while a * tool-approval gate is parked). */ private settleToolCallAsDenied; private finishStreamState; private finishSubscribedStreamRun; /** * Drop suspensions that a failed run can no longer resume. With `toolCallId`, only that * call's suspension is dropped: the stream reported a failure scoped to one tool call * (for example its own save failed) while the rest of the run is still live. */ private retractFailedRunSuspensions; private emitSuspensionCancelled; private handleSubscribedStreamError; processSubscribedThreadStream(subscription: AgentThreadSubscription<StreamChunk, true>): Promise<void>; } export {}; //# sourceMappingURL=session-run-engine.d.ts.map