import { AgentRunContext, ResolvedGenerationResponse } from "../agent-types.js";
import { IncrementalStreamParser } from "../../stream/IncrementalStreamParser.js";
import { StreamTextResult, ToolSet } from "ai";

//#region src/domains/run/agents/streaming/stream-handler.d.ts

/**
 * Orchestrate the consumption of a streamText result for the live-wire path.
 *
 * For structured-output generation we drive two cooperating sources into the same parser:
 *   - `fullStream`: raw text-delta events (we parse the JSON tokens ourselves and emit object
 *     deltas at per-text-delta granularity — see `processStreamEvents`).
 *   - `partialOutputStream`: the SDK's pre-parsed object deltas. These arrive at coarser
 *     boundaries but give us a safety net: if our JSON parse ever lags or misclassifies, the
 *     partial stream will still drive the parser. The parser dedupes by length, so whichever
 *     path delivers a given text prefix first wins and the other is a no-op.
 *
 * Abort wiring: fullStream and partialOutputStream share the same underlying SDK source, so an
 * error on fullStream terminates partialOutputStream shortly after. The AbortController is a
 * belt-and-braces cancellation: if fullStream throws, we signal the partialOutput consumer to
 * bail at its next iteration rather than continue processing deltas on a parser whose caller
 * already considers the stream finished.
 */
declare function handleStreamGeneration(ctx: AgentRunContext, streamResult: StreamTextResult<ToolSet, any>, sessionId: string, contextId: string, hasStructuredOutput: boolean): Promise<ResolvedGenerationResponse>;
/**
 * Iterate `fullStream` and forward events to the parser.
 *
 * In `structuredOutputMode` we classify each step on its first non-whitespace text-delta char
 * so one generation can interleave free-form reasoning and JSON output across steps:
 *   - JSON (`{` or `[`): accumulate text-deltas into a per-step buffer, repair-parse on each
 *     update via `parsePartialJson`, and feed the resulting cumulative object to the parser.
 *     This is the fine-grained-streaming path — it turns paragraph-sized SDK text-delta chunks
 *     into per-token object updates that the parser can diff and stream out smoothly.
 *   - Plain text (anything else): forward to `parser.processTextChunk` so intermediate
 *     reasoning like "Let me search..." still reaches the client before a tool call.
 *
 * The JSON buffer and step classification are reset on both `finish-step` (AI SDK v6 per-step
 * event) and `finish` (end of generation). Resetting between steps is load-bearing: without it,
 * step 2's JSON concatenates onto step 1's already-closed JSON, `parsePartialJson` fails, and
 * step 2's content never streams.
 */
declare function processStreamEvents(streamResult: StreamTextResult<ToolSet, any>, parser: IncrementalStreamParser, signal?: AbortSignal, structuredOutputMode?: boolean): Promise<void>;
//#endregion
export { handleStreamGeneration, processStreamEvents };