@mastra/core
Version:
125 lines • 7.01 kB
TypeScript
import type { BackgroundTaskManager } from '../../background-tasks/manager.js';
import type { MastraMemory } from '../../memory/memory.js';
import { RequestContext } from '../../request-context/index.js';
export declare const TERMINAL_BG_CHUNKS: Set<string>;
export interface ResolvedScope {
threadId: string | undefined;
resourceId: string | undefined;
scopeKey: string | null;
}
/**
* Resolve memory / thread / resource for this call, matching `#execute`
* semantics (RequestContext-scoped keys override caller-supplied memory
* args). Returns `null` when no memory backend is configured — caller
* falls through to a plain stream in that case.
*/
export declare function resolveScope(agent: {
getMemory: (opts?: any) => Promise<MastraMemory | undefined>;
getScopes?: (opts?: any) => Promise<string[]>;
}, mergedOptions: Record<string, any>): Promise<ResolvedScope | null>;
/**
* Build the ephemeral system-context text that tells the LLM which tool-call
* IDs just completed / failed / canceled. The directive stops the LLM from (a) re-processing
* results already handled on a prior continuation and (b) mimicking the
* prior assistant ack text ("I'm running it in the background") and
* re-dispatching the same tool.
*/
export declare function buildContinuationDirective(batch: Array<Record<string, unknown>>): string;
/**
* Wrap the continuation directive into a stream-options object suitable for
* a recursive `agent.stream([], ...)` call. `context` messages are visible
* to the LLM but NOT persisted to memory, so the directive doesn't pollute
* future turns.
*/
export declare function buildContinuationOpts(baseContinuationOpts: Record<string, any>, callerContext: any[] | undefined, batch: Array<Record<string, unknown>>): Record<string, any>;
export declare function releaseContinuationToolCallIds(requestContext: RequestContext | undefined, toolCallIds: string[]): void;
/** Return the active untilIdle wrapper registered for a caller-visible run ID. */
export declare function getRunStreamSlot(activeStreams: Map<string, () => void>, runId: string): (() => void) | undefined;
/** Return the active scope wrapper when it still belongs to the expected caller-visible run. */
export declare function getScopeStreamSlot(activeStreams: Map<string, () => void>, scopeKey: string, expectedRunId?: string): (() => void) | undefined;
/**
* Why a wrapper is closed by a newer one: `replaced` when another stream takes its memory
* scope, `sameRun` when another wrapper (e.g. a resume) takes over the same run.
*/
type StreamSlotCloseReason = 'replaced' | 'sameRun';
/** Closes a wrapper. A newer wrapper passes `takeTasks` to receive the tasks the closed one was waiting for. */
type StreamSlotCloser = (reason?: StreamSlotCloseReason, takeTasks?: Set<string>) => void;
/** Register the active wrapper for a memory scope, aborting the prior wrapper for that scope. */
export declare function acquireStreamSlot(activeStreams: Map<string, StreamSlotCloser>, scopeKey: string | null, closer: StreamSlotCloser, takeTasks?: Set<string>): void;
/** Register the active wrapper under its caller-visible run ID, replacing an older wrapper for that ID. */
export declare function acquireRunStreamSlot(activeStreams: Map<string, StreamSlotCloser>, runId: string | undefined, closer: StreamSlotCloser, takeTasks?: Set<string>): void;
/**
* Remove `closer` from its scope and caller-visible run slots iff it is still
* the registered wrapper. A later wrapper that took over either slot is left intact.
*/
export declare function releaseStreamSlot(activeStreams: Map<string, () => void>, scopeKey: string | null, runId: string | undefined, closer: () => void): void;
/**
* Whether a finished background task is already handled by an `untilIdle`
* stream on this agent: one is open for the thread and runs its own follow-up
* turn, or the caller stopped the stream that was waiting for the task.
*/
export declare function untilIdleHandlesBackgroundTask(activeStreams: Map<string, unknown>, threadId: string, resourceId: string, taskId: string): boolean;
export interface IdleLoopDeps {
activeStreams: Map<string, () => void>;
bgManager: BackgroundTaskManager | undefined;
}
/**
* Called after each inner stream result (first turn + continuations).
* Durable agents use this to track cleanup/abort handles.
*/
export interface PostPipeHooks {
/** Durable readers own their subscription, not the underlying execution. */
detachOnCancel?: boolean;
/** Called with each inner result after `firstTurn` or continuation. */
onInnerResult?: (inner: any) => void;
/** Abort the currently active inner stream before the wrapper closes. */
onAbortActive?: () => void;
/** Extra teardown to run inside `forceClose`. */
onForceClose?: () => void;
}
/**
* Everything the `buildResult` callback needs to construct the
* caller-specific return type.
*/
export interface IdleLoopContext {
combinedStream: ReadableStream<any>;
forceClose: () => void;
abort: () => void;
threadId: string | undefined;
resourceId: string | undefined;
}
/**
* Generic idle-loop wrapper. Drives the full lifecycle:
* 1. Merge options + resolve scope (early-return if no bgManager / no memory)
* 2. Acquire stream slot
* 3. Run first turn via `firstTurn(opts)`
* 4. Subscribe to `bgManager.stream()` for bg-task events
* 5. On terminal bg events, queue and process continuations via `streamForContinuation`
* 6. Idle timer fires `forceClose` if nothing happens for `maxIdleMs`
*
* @param agent Must expose `.id`, `.getDefaultOptions(...)`, `.getMemory(...)`.
* @param streamOptions Caller-supplied stream options (may include `maxIdleMs`).
* @param deps `{ activeStreams, bgManager }`.
* @param firstTurn Callback for the initial turn. Returns the first result.
* @param streamForContinuation Callback to create a continuation stream.
* Returns an inner result (any shape); the `.fullStream` field is piped.
* @param buildResult Callback to construct the final return value from the
* first-turn result + idle-loop context.
* @param hooks Optional durable-specific hooks for cleanup/abort tracking.
*/
export declare function runIdleLoop<TAgent extends {
id: string;
getDefaultOptions: (opts?: any) => any | Promise<any>;
getMemory: (opts?: any) => Promise<MastraMemory | undefined>;
abortRunStream?: (runId: string) => boolean;
}, TFirstResult extends {
fullStream: any;
runId?: string;
}, TReturn>(agent: TAgent, streamOptions: (Record<string, any> & {
maxIdleMs?: number;
}) | undefined, deps: IdleLoopDeps, firstTurn: (opts: Record<string, any>) => Promise<TFirstResult>, streamForContinuation: (opts: Record<string, any>) => Promise<{
fullStream: ReadableStream<any>;
runId?: string;
}>, buildResult: (first: TFirstResult, ctx: IdleLoopContext) => TReturn, hooks?: PostPipeHooks): Promise<TReturn>;
export {};
//# sourceMappingURL=stream-until-idle-helpers.d.ts.map