/** * Propagates per-turn stream callbacks and cancellation through model and * action execution, using Node AsyncLocalStorage. */ import type { StreamChunkCallback } from "./types/components.js"; import type { StreamingContextEventPayload, StreamingEvaluationPayload, StreamingEventHooks, StreamingToolCallPayload, StreamingToolResultPayload } from "./types/streaming.js"; /** Trusted execution policy, bound to an actor and incoming turn, never tool arguments. */ export interface TurnActionConstraint { messageId: string; roomId: string; actorId: string; action: string; operations: readonly string[]; disposition: "allow" | "deny"; reason: string; } /** A host-verified text tariff. Unknown routes and non-text billing are refused. */ export interface ModelAttemptTariff { provider: string; model: string; route: string; inputNanoUsdPerToken: number; outputNanoUsdPerToken: number; /** Conservative reservation bound, not measured prompt tokens. */ inputTokenUpperBound: number; } export interface ModelAttemptLease { readonly messageId: string; readonly maxOutputTokens: number; reserve(provider: string, model: string, route: string | undefined, serialized: string, outputTokens: number | undefined): void; close(): void; } /** Host-only, in-memory trial allowance. Reservations are never refunded. */ export interface ModelAttemptAllowance { openTurn(messageId: string, signal: AbortSignal, assertCurrent?: () => void): ModelAttemptLease; close(): void; readonly remainingMicroUsd: number; } export declare function createModelAttemptAllowance(options: { signal: AbortSignal; budgetMicroUsd: number; maxAttempts: number; maxOutputTokens: number; expiresAt: number; tariffs: readonly ModelAttemptTariff[]; }): ModelAttemptAllowance; /** Model parameters and UI metadata cannot mint a trusted lease. */ export declare function getModelAttemptLease(): ModelAttemptLease | undefined; /** * Streaming context containing callbacks for streaming lifecycle. */ export interface StreamingContext extends StreamingEventHooks { /** * Called for each chunk of streamed content. Omitted when a scope exists * only to carry cancellation or structured hooks: a context without a chunk * consumer must not put nested `useModel` calls on the streaming path. */ onStreamChunk?: StreamChunkCallback; /** Called when a useModel streaming call completes (allows reset between calls) */ onStreamEnd?: () => void; reportError?: (scope: string, error: unknown, context?: Record) => void; messageId?: string; /** Optional abort signal to cancel streaming */ abortSignal?: AbortSignal; /** Shared by nested model/action scopes; policy producers own writes. */ actionConstraints?: Map; /** Opaque host-created policy; never reconstructed from request/model metadata. */ modelAttemptLease?: ModelAttemptLease; /** Original incoming user turn, separate from the assistant streaming ID. */ modelAttemptTurnId?: string; } export interface StreamingHookPayloads { onToolCall: StreamingToolCallPayload; onToolResult: StreamingToolResultPayload; onEvaluation: StreamingEvaluationPayload; onContextEvent: StreamingContextEventPayload; } /** * Safely emit an optional streaming event hook. * Missing hooks are no-ops, and hook failures are isolated from runtime flow. */ export declare function emitStreamingHook(context: StreamingContext | undefined, hook: K, payload: StreamingHookPayloads[K]): Promise; /** * Interface for streaming context managers. * AsyncLocalStorage isolates concurrent turns across asynchronous work. */ export interface IStreamingContextManager { /** * Run a function with a streaming context. * The context will be available to all nested async calls via `active()`. */ run(context: StreamingContext | undefined, fn: () => T): T; /** * Get the currently active streaming context. * Returns undefined if no context is active. */ active(): StreamingContext | undefined; } /** * Set the global streaming context manager. * Can be used to override the auto-detected manager. * * @param manager - The context manager to use globally */ export declare function setStreamingContextManager(manager: IStreamingContextManager): void; /** * Get the global streaming context manager, creating it on first access. * * The shared global slot is the single source of truth (no module-local * cache): under a duplicated core bundle every copy must observe the same * manager, and `setStreamingContextManager` must be visible everywhere. */ export declare function getStreamingContextManager(): IStreamingContextManager; /** * Run a function with a streaming context. * All useModel calls within this function will automatically use streaming. * * @example * ```typescript * await runWithStreamingContext( * { onStreamChunk: async (chunk) => sendSSE(chunk), messageId }, * async () => { * // All useModel calls here will stream automatically * await runtime.processMessage(message); * } * ); * ``` * * @param context - The streaming context with onStreamChunk callback * @param fn - The function to run with streaming context * @returns The result of the function */ export declare function runWithStreamingContext(context: StreamingContext | undefined, fn: () => T): T; /** Register validated policy on the ambient turn before asynchronous selection. */ export declare function setTurnActionConstraint(constraint: TurnActionConstraint): void; /** Read only the policy for this exact actor, turn, action and operation. */ export declare function getTurnActionConstraint(identity: Pick, operation: string): TurnActionConstraint | undefined; /** * Run `fn` with the ambient visible-token stream detached. * * Any `useModel` call inside still inherits the active streaming context's * abort signal and structured tool/evaluation hooks, but its raw tokens no * longer reach the turn's visible reply channel — `onStreamChunk` becomes a * no-op. This is the seam that keeps an action handler's *internal* model * calls off the user-visible reply: only the top-level response * generation streams raw tokens, while an action delivers its own output * through the HandlerCallback. The visible stream would otherwise surface an * action's intermediate model output as though it were the action's final * reply. An action that * genuinely wants to stream can still opt in with an explicit `onStreamChunk` * in its `useModel` params, which `useModel` honors independently of the * ambient context. The planner and evaluator model calls apply the same * override inline. * * A straight pass-through (no added scope) when no streaming context is active * or when the active context has no chunk consumer to detach. Installing the * discarding callback in that second case would make the context look like a * stream consumer to `useModel` and move otherwise non-streaming internal calls * onto the streaming path. */ export declare function runWithSuppressedModelStream(fn: () => T): T; /** * Get the currently active streaming context. * Called by useModel to check if automatic streaming should be enabled. * * @returns The current streaming context or undefined */ export declare function getStreamingContext(): StreamingContext | undefined; /** * While `> 0`, the runtime is inside `useModel`'s delivery of one `textStream` chunk to * `paramsChunk` / `ctxChunk` (after `model_stream_chunk` with `source: "use_model"`). * `DefaultMessageService` skips its own `model_stream_chunk` (`source: "message_service"`) in * this window so the same raw token is not processed twice. */ export declare function getModelStreamChunkDeliveryDepth(): number; /** Wrap `paramsChunk` / `ctxChunk` invocations from `useModel`'s stream loop. */ export declare function runInsideModelStreamChunkDelivery(fn: () => T | Promise): T | Promise;