{"version":3,"file":"types.cjs","names":[],"sources":["../../src/stream/types.ts"],"sourcesContent":["/**\n * Core type definitions for the v2 streaming interface.\n *\n * Channel event data types (`MessagesEventData`, `ToolsEventData`,\n * `UpdatesEventData`, `UsageInfo`, `Checkpoint`, `CheckpointSource`) are\n * re-exported from `@langchain/protocol` — the generated TypeScript\n * bindings for the canonical CDDL schema.  Stream-specific types\n * (`StreamTransformer`, `ChatModelStream`, `ToolCallStream`,\n * `InterruptPayload`) are defined here.\n */\n\nimport type { ChatModelStream as CoreChatModelStream } from \"@langchain/core/language_models/stream\";\nimport type { ChatModelStreamEvent as CoreChatModelStreamEvent } from \"@langchain/core/language_models/event\";\nimport type { StreamMode } from \"../pregel/types.js\";\n\n/**\n * Re-exports from `@langchain/protocol`.\n *\n * These are the canonical wire-format types generated from `protocol.cddl`.\n * They are re-exported with local aliases so that consumers of this module\n * do not need a direct dependency on `@langchain/protocol`.\n */\nexport type {\n  MessagesData as MessagesEventData,\n  ToolsData as ToolsEventData,\n  UpdatesData as UpdatesEventData,\n  UsageInfo,\n  MessageStartData,\n  ContentBlockStartData,\n  ContentBlockDeltaData,\n  ContentBlockFinishData,\n  MessageFinishData,\n  MessageErrorData,\n  ToolStartedData,\n  ToolOutputDeltaData,\n  ToolFinishedData,\n  ToolErrorData,\n  Checkpoint,\n  CheckpointSource,\n  AgentStatus,\n  LifecycleData,\n  LifecycleCause,\n} from \"@langchain/protocol\";\n\n/**\n * Hierarchical path identifying a position in the agent tree.\n *\n * Each element is one segment; longer arrays mean deeper nesting (e.g.\n * subgraph or multi-agent scopes).\n */\nexport type Namespace = string[];\n\n/**\n * Channels that can appear on a protocol event.  Beyond the raw\n * {@link StreamMode} channels emitted by the Pregel stream, the v2\n * protocol layer synthesizes additional channels (e.g. `lifecycle`,\n * `input`) via built-in {@link StreamTransformer}s and exposes\n * user-defined channels created with {@link StreamChannel}.\n */\nexport type ProtocolMethod = StreamMode | \"lifecycle\" | \"input\" | (string & {});\n\n/**\n * Single envelope for a streaming protocol emission: sequence, channel\n * (`method`), and payload (`params`).\n */\nexport interface ProtocolEvent {\n  /** Discriminator; always `\"event\"` for this shape. */\n  readonly type: \"event\";\n\n  /** Monotonic sequence number for ordering and deduplication within a run. */\n  readonly seq: number;\n\n  /**\n   * Logical stream channel.  Built-in channels match {@link StreamMode}\n   * (e.g. `messages`, `updates`); transformer-synthesized channels\n   * include `lifecycle` and `input`; user-defined channels carry their\n   * {@link StreamChannel.channelName}.\n   */\n  readonly method: ProtocolMethod;\n\n  /** Channel-specific payload and routing metadata. */\n  readonly params: {\n    /** Namespace of the node or scope that emitted this event. */\n    readonly namespace: Namespace;\n\n    /** Wall-clock or logical timestamp for the emission (milliseconds). */\n    readonly timestamp: number;\n\n    /**\n     * Graph node id when the engine can attribute the event to a single node;\n     * omitted for run-level or ambiguous emissions.\n     */\n    readonly node?: string;\n\n    /** Opaque channel payload; shape depends on `method`. */\n    readonly data: unknown;\n  };\n}\n\n/**\n * Infers the merged extensions type from a tuple of transformer factory functions.\n *\n * Given `[() => StreamTransformer<{ a: number }>, () => StreamTransformer<{ b: string }>]`,\n * produces `{ a: number } & { b: string }`.\n */\nexport type InferExtensions<\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  T extends ReadonlyArray<() => StreamTransformer<any>>,\n> = T extends readonly []\n  ? Record<string, never>\n  : T extends readonly [\n        () => StreamTransformer<infer P>,\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        ...infer Rest extends ReadonlyArray<() => StreamTransformer<any>>,\n      ]\n    ? P & InferExtensions<Rest>\n    : Record<string, unknown>;\n\n/**\n * Observes {@link ProtocolEvent}s during a graph run and builds typed derived\n * projections (secondary event logs, promises, etc.).\n *\n * Data is surfaced to consumers through **projections** returned from\n * `init()`.  Projections are merged into `GraphRunStream.extensions` for\n * in-process consumers.  Use {@link StreamChannel.local} for local streaming\n * values, {@link StreamChannel.remote} for values that should also be visible\n * to remote clients, or `Promise<T>` for final values.\n *\n * To make projection data available to **remote** clients (SDK consumers\n * over WebSocket / SSE), create a named channel with\n * `StreamChannel.remote(name)`.  The {@link StreamMux} detects named\n * `StreamChannel` instances in the `init()` return and auto-forwards every\n * `push()` as a {@link ProtocolEvent} on `custom:<name>`.  Remote clients\n * subscribe via `session.subscribe(\"custom:<name>\")`.\n *\n * `finalize` and `fail` are optional.  When a transformer uses\n * `StreamChannel`, the mux auto-closes/fails the channels on run\n * completion — no manual lifecycle management needed.  Implement\n * `finalize`/`fail` only for non-channel teardown (e.g. resolving a\n * `Promise`).\n *\n * @typeParam TProjection - Shape returned by {@link init}, merged into\n *   `GraphRunStream.extensions`.\n */\nexport interface StreamTransformer<TProjection = unknown> {\n  /**\n   * Called once before the run starts.\n   *\n   * @returns Initial projection merged into `GraphRunStream.extensions`.\n   *   Any named {@link StreamChannel} instances in the return value are\n   *   automatically wired to the protocol event stream by the mux. Unnamed\n   *   channels stay in-process-only.\n   */\n  init(): TProjection;\n\n  /**\n   * Optional hook invoked by {@link StreamMux.addTransformer} immediately\n   * after the transformer is attached to the mux. Receives a limited\n   * handle that exposes only {@link StreamEmitter.push} — enough for\n   * the transformer to emit synthesized {@link ProtocolEvent}s on any\n   * namespace it chooses (e.g. a deepagents `SubagentTransformer`\n   * fabricating `lifecycle`/`messages`/`values` events under a\n   * `[\"tools:<tool_call_id>\"]` namespace when a `task` tool starts).\n   *\n   * Transformers that do not synthesize events can omit this hook.\n   *\n   * The {@link StreamEmitter} handle is only safe to call *from within*\n   * {@link StreamTransformer.process}. Emitting from an unrelated async\n   * context (e.g. after `process` has returned, from a `setTimeout`,\n   * etc.) races with the mux's close/fail cycle and may land events in\n   * an already-closed log.\n   */\n  onRegister?(emitter: StreamEmitter): void;\n\n  /**\n   * Called for each {@link ProtocolEvent} before it is appended to the main log.\n   *\n   * @param event - Next protocol envelope for this run.\n   * @returns `false` to drop the original event from the main log (use\n   *   sparingly; prefer keeping events visible and adding derived data\n   *   alongside).\n   */\n  process(event: ProtocolEvent): boolean;\n\n  /**\n   * Called once when the underlying Pregel run completes without throwing.\n   * Optional — only needed for non-channel teardown (e.g. resolving promises).\n   *\n   * May return a `PromiseLike<void>` to defer the main event log close\n   * until the async work (e.g. emitting terminal lifecycle events) has\n   * completed.  The mux awaits all returned promises before closing its\n   * event log.\n   */\n  finalize?(): void | PromiseLike<void>;\n\n  /**\n   * Called once when the run fails; `err` is the rejection or error value.\n   * Optional — only needed for non-channel teardown (e.g. rejecting promises).\n   *\n   * @param err - Failure reason from the engine or user code.\n   */\n  fail?(err: unknown): void;\n}\n\n/**\n * Narrow capability handle passed to\n * {@link StreamTransformer.onRegister}. Exposes only the minimal mux\n * surface required for synthetic event emission — intentionally does\n * not expose close/fail/register/etc. to keep the transformer contract\n * small and tamper-resistant.\n */\nexport interface StreamEmitter {\n  /**\n   * Injects a new {@link ProtocolEvent} into the mux pipeline. The\n   * event is routed through every registered transformer (including\n   * the emitting transformer — implementers must guard against\n   * re-entrant self-processing) and, if not suppressed, appended to\n   * the main event log.\n   *\n   * @param ns - Target namespace for the synthetic event.\n   * @param event - The event envelope to inject. ``event.seq`` is\n   *   overwritten by the mux; callers can pass any placeholder.\n   */\n  push(ns: Namespace, event: ProtocolEvent): void;\n}\n\nexport type ChatModelStream = Omit<\n  CoreChatModelStream,\n  typeof Symbol.asyncIterator\n> & {\n  /** Namespace of the graph node that produced this stream. */\n  readonly namespace: Namespace;\n\n  /** Graph node id for this stream, if the runtime attributed it. */\n  readonly node: string | undefined;\n\n  /**\n   * Low-level async iteration over message lifecycle events.\n   *\n   * @returns Iterator yielding Core-compatible chat model stream events.\n   */\n  [Symbol.asyncIterator](): AsyncIterator<CoreChatModelStreamEvent>;\n};\n\n/**\n * Public view yielded by `run.messages`.\n *\n * `ChatModelStream` is PromiseLike to mirror Core, but TypeScript applies\n * `Awaited<T>` to values produced by `for await`. Exposing a non-thenable view\n * keeps loop variables typed as the streaming handle instead of `AIMessage`.\n */\nexport type ChatModelStreamHandle = Omit<ChatModelStream, \"then\">;\n\n/**\n * High-level outcome of a single tool call for UI or aggregators.\n */\nexport type ToolCallStatus =\n  /** Invocation in flight or output still streaming. */\n  | \"running\"\n  /** Completed without error. */\n  | \"finished\"\n  /** Failed or aborted; see {@link ToolCallStream.error}. */\n  | \"error\";\n\n/**\n * Stable handle for one tool call: name, arguments, and async results.\n *\n * Emitted when `content-block-finish` delivers a finalized `tool_call` block.\n *\n * @typeParam TName - Registered tool name.\n * @typeParam TInput - Parsed or raw input type for the call.\n * @typeParam TOutput - Successful result type after the tool returns.\n */\nexport interface ToolCallStream<\n  TName extends string = string,\n  TInput = unknown,\n  TOutput = unknown,\n> {\n  /** Tool identifier as registered on the graph or model schema. */\n  readonly name: TName;\n\n  /** Correlates with protocol `toolCallId` when the runtime provides one. */\n  readonly callId: string;\n\n  /** Arguments passed to the tool (finalized when the call is observable). */\n  readonly input: TInput;\n\n  /**\n   * Resolves to the tool return value on success.\n   *\n   * @remarks\n   * Rejection or hang semantics depend on the runner; pairing with\n   * {@link ToolCallStream.status} and {@link ToolCallStream.error} is recommended.\n   */\n  readonly output: Promise<TOutput>;\n\n  /**\n   * Resolves to {@link ToolCallStatus} when the call leaves the running state.\n   */\n  readonly status: Promise<ToolCallStatus>;\n\n  /**\n   * Resolves to an error message string if {@link ToolCallStream.status} is\n   * `\"error\"`, otherwise `undefined`.\n   */\n  readonly error: Promise<string | undefined>;\n}\n\n/**\n * Marker interface for transformers provided by internal LangChain products\n * (e.g. ReactAgent's ToolCallTransformer, DeepAgent's SubagentTransformer).\n *\n * Native transformers differ from user-defined extension transformers in\n * where their projection lands on the run stream:\n *\n *   - **Native** — projections become direct getters on a\n *     `GraphRunStream` subclass (e.g. `run.toolCalls`, `run.subagents`).\n *     They emit events on protocol-defined channels (`tools`, `lifecycle`,\n *     `tasks`, etc.).\n *\n *   - **Extension** (user-defined) — projections are merged into\n *     `run.extensions`.  Events emitted via `emit()` use an\n *     application-chosen method name (e.g. `emit(\"a2a\", data)`) and are\n *     accessible to remote clients via `session.subscribe(\"custom:<name>\")`.\n *\n * The `__native` brand is used by downstream stream factory functions\n * to distinguish native transformers from extension transformers at\n * registration time.  See `docs/native-stream-transformers.md` for the\n * full pattern.\n */\nexport interface NativeStreamTransformer<\n  TProjection = unknown,\n> extends StreamTransformer<TProjection> {\n  readonly __native: true;\n}\n\n/**\n * Type guard that tests whether a transformer is a {@link NativeStreamTransformer}.\n */\nexport function isNativeTransformer(\n  t: StreamTransformer<unknown>\n): t is NativeStreamTransformer {\n  return \"__native\" in t && (t as NativeStreamTransformer).__native === true;\n}\n\n/**\n * Human-in-the-loop interrupt: stable id plus opaque payload for resume UIs.\n */\nexport interface InterruptPayload<TPayload = unknown> {\n  /** Idempotent key for this interrupt instance within the run. */\n  interruptId: string;\n\n  /** Arbitrary data supplied by the graph (e.g. questions, draft state). */\n  payload: TPayload;\n}\n"],"mappings":";;;;AAmVA,SAAgB,oBACd,GAC8B;AAC9B,QAAO,cAAc,KAAM,EAA8B,aAAa"}