@mastra/core
Version:
209 lines • 11.5 kB
TypeScript
import type { LanguageModelRequestMetadata } from '../../_types/@internal_ai-sdk-v5@0.0.98/dist/index.js';
import type { PubSub } from '../../events/pubsub.js';
import type { IMastraLogger } from '../../logger/index.js';
import type { TracingContext } from '../../observability/index.js';
import type { OutputProcessorOrWorkflow, ProcessorState } from '../../processors/index.js';
import type { RequestContext } from '../../request-context/index.js';
import { MastraModelOutput } from '../../stream/base/output.js';
import type { ChunkType, MastraOnFinishCallback, MastraStreamTransformOptions, ToolCallChunk } from '../../stream/types.js';
import type { Agent } from '../agent.js';
import type { AgentExecutionOptionsBase } from '../agent.types.js';
import { MessageList } from '../message-list/index.js';
import type { StructuredOutputOptions } from '../types.js';
import type { AgentStreamEvent, DurableAgentStepFinishResult, AgentSuspendedEventData, AgentAbortEventData, AgentIterationCompleteEventData } from './types.js';
/**
* Decides which run-stream events a reader keeps once another execution may
* have taken the run over. Events tagged with a generation older than the
* newest one seen come from an execution that lost the run and are dropped;
* untagged events, from runs fenced by a pubsub lease, are always kept.
*
* `minGeneration` and `rereadMinGeneration` work as on
* {@link DurableAgentStreamOptions}. The result is a boolean, so event order is
* kept, except while a failed claim read must be retried before a stream-ending
* event, which is the only time it is a promise.
*/
export declare function createRunGenerationFilter({ minGeneration, rereadMinGeneration, }: Pick<DurableAgentStreamOptions, 'minGeneration' | 'rereadMinGeneration'>): (event: AgentStreamEvent) => boolean | Promise<boolean>;
/** Drop only the uncheckpointed tail superseded by a later recovery. Earlier generations' committed steps remain. */
export declare function createSupersededEventFilter(history: AgentStreamEvent[]): (event: AgentStreamEvent) => boolean;
/**
* Options for creating a durable agent stream
*/
export interface DurableAgentStreamOptions<OUTPUT = undefined> {
/** Signal chunks to hide from this caller's stream. */
hideSignals?: AgentExecutionOptionsBase<OUTPUT>['hideSignals'];
/** Pubsub instance to subscribe to */
pubsub: PubSub;
/** Run identifier */
runId: string;
/** Message ID for this execution */
messageId: string;
/** Tool calls emitted before a resumed stream segment started. */
initialToolCalls?: ToolCallChunk[];
/** Text the run streamed before the suspension a resumed stream segment continues. */
resumedText?: {
priorText: string;
stepText: string;
};
/** Model information for the output */
model: {
modelId: string | undefined;
provider: string | undefined;
version: 'v2' | 'v3' | 'v4';
};
/** Thread ID for memory */
threadId?: string;
/** Resource ID for memory */
resourceId?: string;
/**
* Inclusive, zero-based PubSub event index, or `latest` to live-tail. Numeric indexes count all
* cached run-topic events, including lifecycle events, not chunks. Omit it to replay all available
* cached events; transports without numeric offsets live-tail numeric values instead. Skipping earlier
* text deltas produces partial text and may make structured output fail to parse; beyond retained
* history, a number also skips lower-index live events on numeric-offset transports. See
* https://mastra.ai/reference/agents/durable-agent#observerunid-options.
*/
offset?: number | 'latest';
/**
* Claim generation of the execution this stream follows. Events tagged with
* an older generation come from an execution that has since lost the run and
* are dropped. Newer generations seen on the topic raise the bar further.
*/
minGeneration?: number;
/**
* Reads the run's current claim generation. Pass it when `minGeneration`
* couldn't be read: until a read succeeds, the stream reads the claim again
* before an event from a claimed execution can end it, so the terminal event
* of a superseded execution doesn't close the stream.
*/
rereadMinGeneration?: () => Promise<number | undefined>;
/** Reject events in uncheckpointed tails superseded before this reader attached. */
keepReplayEvent?: (event: AgentStreamEvent) => boolean | Promise<boolean>;
/** Refresh takeover ranges after replay attachment and before delivering cached events. */
refreshReplayFilter?: () => Promise<unknown>;
/**
* If set, terminate the stream when no pubsub event arrives for this many ms
* AND the run is not alive (see `isAlive`). A durable run whose driving process
* crashed stops emitting but never publishes a terminal event, so `observe()`
* would otherwise hang forever on a producerless topic. Absent ⇒ no idle bound
* (current behavior).
*/
idleTimeoutMs?: number;
/**
* Optional liveness probe consulted when the idle timeout fires. Returns true
* while some process is still driving the run (e.g. a fresh run-liveness
* heartbeat), in which case the stream keeps waiting; false ⇒ terminate. When
* omitted, a bare `idleTimeoutMs` terminates on pure silence. A transient throw
* is treated as alive (keep waiting), so a momentary dependency blip never ends
* a live stream.
*/
isAlive?: () => boolean | Promise<boolean>;
/** Callback when chunk is received */
onChunk?: (chunk: ChunkType<OUTPUT>) => void | Promise<void>;
/** Callback when step finishes */
onStepFinish?: (result: DurableAgentStepFinishResult) => void | Promise<void>;
/** Callback when execution finishes — routed through MastraModelOutput for rich step data */
onFinish?: MastraOnFinishCallback<OUTPUT>;
/** Only owning stream/resume/recovery readers receive this hook; observers never settle records. */
onTerminalEvent?: (status: 'suspended' | 'finished', generation: number | undefined) => void | Promise<void>;
/** Lifecycle hook called after the FINISH event closes the stream (for cleanup scheduling) */
onStreamFinished?: () => void | Promise<void>;
/** Callback on error */
/**
* Callback on error. `runDead` is only set for idle-timeout terminations:
* `true` when `isAlive` confirmed the run is dead, `false` when the stream
* went quiet but the run may still be alive (bare timeout).
*/
onError?: ({ error, runDead }: {
error: Error | string;
runDead?: boolean;
}) => void | Promise<void>;
/** Callback when workflow suspends */
onSuspended?: (data: AgentSuspendedEventData) => void | Promise<void>;
/** Callback when execution is aborted via abortSignal */
onAbort?: (data: AgentAbortEventData) => void | Promise<void>;
/** Callback fired after each agentic-loop iteration */
onIterationComplete?: (data: AgentIterationCompleteEventData) => void | Promise<void>;
/** Optional logger for structured logging */
logger?: IMastraLogger;
/**
* If true, close the underlying ReadableStream when a SUSPENDED event is
* received so `getFullOutput()`/`fullStream` resolve on suspend instead of
* hanging. The durable agent derives this from the public `closeOnSuspend`
* stream option (default `false`, keeping the stream open for a later
* same-reader resume).
*/
closeOnSuspend?: boolean;
/**
* Structured output configuration with live schema. When provided,
* `MastraModelOutput` pipes LLM text through `createObjectStreamTransformer`
* to produce `object-result` chunks.
*/
structuredOutput?: StructuredOutputOptions<OUTPUT>;
/** Output processors to run in MastraModelOutput's stream pipeline */
outputProcessors?: OutputProcessorOrWorkflow[];
/** Processor state map shared with the durable workflow's producer-side processing. */
processorStates?: Map<string, ProcessorState>;
/** The agent running this run, passed to output processors as `agent`. */
agent?: Agent<any, any, any, any>;
/** When true, `getFullOutput()` includes `scoringData` assembled from the MessageList. */
returnScorerData?: boolean;
/** Run context passed to output processors for every streamed chunk. */
requestContext?: RequestContext;
/** @internal Only fresh in-process callers can read private provider request metadata. */
readLocalRequest?: () => LanguageModelRequestMetadata | undefined;
/** Tracing context whose current span is the run's AGENT_RUN span; parents per-chunk processor spans. */
tracingContext?: TracingContext;
/** Experimental transforms applied whenever the returned full stream is consumed. */
experimentalTransform?: MastraStreamTransformOptions<OUTPUT>;
/**
* With a numeric `offset`, first rebuild the run's response messages from the
* events before it, since step-finish events carry only the messages that
* changed. Costs one read of the run's log.
*/
replayResponseMessagesBeforeOffset?: boolean;
/**
* Optional external MessageList to use instead of creating a fresh empty one.
* When provided (e.g. the registry's live MessageList), MastraModelOutput can
* resolve step content from messages added during the workflow execution.
*/
messageList?: MessageList;
}
/**
* Result from creating a durable agent stream
*/
export interface DurableAgentStreamResult<OUTPUT = undefined> {
/** The MastraModelOutput that streams from pubsub events */
output: MastraModelOutput<OUTPUT>;
/** Cleanup function to unsubscribe from pubsub */
cleanup: () => void;
/**
* Stop consuming: close the stream (pending reads resolve as done) and
* unsubscribe. Idempotent. Does not affect the run itself.
*/
detach: () => void;
/**
* End only this reader's stream with `error` (rejecting or as an error
* chunk, like a published ERROR event) and unsubscribe. Nothing is published,
* so other readers of the run are unaffected.
*/
fail: (error: Error) => Promise<void>;
/**
* Wait until this adapter has received every event the run's log held when
* called (bounded), then for those deliveries to finish processing.
*/
waitForEventDelivery: () => Promise<void>;
/** Accepted deliveries, including hidden ownership markers, for observation reconciliation. */
readonly activityVersion: number;
/** Promise that resolves when subscription is established */
ready: Promise<void>;
}
/**
* Create a MastraModelOutput that streams from pubsub events.
*
* This adapter subscribes to the agent stream pubsub channel and converts
* pubsub events into a ReadableStream that MastraModelOutput can consume.
* Callbacks are invoked as events arrive.
*/
export declare function createDurableAgentStream<OUTPUT = undefined>(options: DurableAgentStreamOptions<OUTPUT>): DurableAgentStreamResult<OUTPUT>;
export { createStepStartChunk, emitAbortEvent, emitChunkEvent, emitErrorEvent, emitFinishEvent, emitIterationCompleteEvent, emitIterationStartEvent, emitOwnershipClaimedEvent, emitStepFinishEvent, emitStepStartEvent, emitSuspendedEvent, publishStepStartChunk, } from '../streams/events.js';
//# sourceMappingURL=stream-adapter.d.ts.map