{"version":3,"file":"use-stream.cjs","names":["ClientCtor","StreamController"],"sources":["../src/use-stream.ts"],"sourcesContent":["/* __LC_ALLOW_ENTRYPOINT_SIDE_EFFECTS__ */\n\n\"use client\";\n\nimport { useEffect, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport type { BaseMessage } from \"@langchain/core/messages\";\nimport type { Client, Interrupt } from \"@langchain/langgraph-sdk\";\nimport {\n  applyHeadlessToolResumeCommand,\n  filterOutHeadlessToolInterrupts,\n  flushPendingHeadlessToolInterrupts,\n} from \"@langchain/langgraph-sdk\";\nimport {\n  Client as ClientCtor,\n  type ClientConfig,\n  type ThreadStream,\n} from \"@langchain/langgraph-sdk/client\";\nimport {\n  StreamController,\n  type AgentServerAdapter,\n  type AgentServerOptions as StreamAgentServerOptions,\n  type ChannelRegistry,\n  type CustomAdapterOptions as StreamCustomAdapterOptions,\n  type InferStateType,\n  type InferSubagentStates,\n  type InferToolCalls,\n  type RootSnapshot,\n  type RunCompletedInfo,\n  type RunExecutionInfo,\n  type StreamRespondAllOptions,\n  type StreamRespondOptions,\n  type StreamStopOptions,\n  type StreamSubmitOptions,\n  type SubagentDiscoverySnapshot,\n  type SubagentMap,\n  type SubgraphByNodeMap,\n  type SubgraphDiscoverySnapshot,\n  type SubgraphMap,\n  type UseStreamOptions as StreamUseStreamOptions,\n  type WidenUpdateMessages,\n} from \"@langchain/langgraph-sdk/stream\";\n\nexport type AgentServerOptions<StateType extends object> =\n  StreamAgentServerOptions<StateType>;\n\nexport type CustomAdapterOptions<StateType extends object> =\n  StreamCustomAdapterOptions<StateType>;\n\nexport type UseStreamOptions<\n  StateType extends object = Record<string, unknown>,\n> = StreamUseStreamOptions<StateType>;\n\n/**\n * Private field on the hook return that carries the\n * {@link StreamController} reference. Selector hooks (`useMessages`,\n * `useToolCalls`, …) read this to reach the shared\n * {@link ChannelRegistry}. Typed as a symbol-keyed field to discourage\n * end-user access — use the selector hooks instead.\n *\n * Exported as a unique symbol so type narrowing works across\n * `useMessages(stream, target)` call sites.\n */\nexport const STREAM_CONTROLLER: unique symbol = Symbol.for(\n  \"@langchain/react/controller\"\n);\n\nexport interface UseStreamReturn<\n  T = Record<string, unknown>,\n  InterruptType = unknown,\n  ConfigurableType extends object = Record<string, unknown>,\n  StateType extends object = InferStateType<T>,\n  SubagentStates = InferSubagentStates<T>,\n> {\n  // ----- always-on root projections -----\n  /**\n   * The most recent `values`-channel snapshot emitted at the root\n   * namespace — i.e. the thread-level state as the server sees it\n   * after each superstep. Updated on every root `values` event, not\n   * on token-level deltas: if you render `values.messages` directly\n   * you'll see full turns appear at once instead of streaming\n   * token-by-token. Use {@link messages} (or `useMessages`) for the\n   * token-streamed view.\n   *\n   * Equivalent to calling `useValues(stream)`.\n   */\n  readonly values: StateType;\n  /**\n   * Type-only: the resolved state shape. Exposed so consumers can\n   * derive companion hook argument types (`useValues<typeof stream>`)\n   * without plumbing `T` through their component hierarchy.\n   *\n   * @internal\n   */\n  readonly \"~stateType\"?: StateType;\n  /**\n   * The root message projection. Assembled from two sources and\n   * merged in real time:\n   *\n   *  1. `messages`-channel deltas — token-level streaming events\n   *     (`message-start`, `content-block-delta`, `message-finish`)\n   *     emitted by the runtime. These drive live, token-by-token\n   *     updates.\n   *  2. `values.messages` snapshots — the authoritative ordering\n   *     and any messages the agent produces without token streaming\n   *     (human turns, tool results, echoes from subagents).\n   *\n   * If the backend only emits `values` events (no `messages`\n   * channel), every message will appear fully-formed on each\n   * values update rather than streaming. This is a backend/runtime\n   * concern — the React layer faithfully renders whatever the\n   * server sends.\n   *\n   * Equivalent to calling `useMessages(stream)` with no target.\n   */\n  readonly messages: BaseMessage[];\n  /**\n   * Root-namespace tool calls assembled from the `tools` channel.\n   * Each entry is a fully parsed {@link AssembledToolCall} with\n   * name, args, and id — suitable for rendering approval UIs or\n   * forwarding to headless tool handlers.\n   *\n   * When the stream is typed with an agent brand or tool list,\n   * entries are narrowed via {@link InferToolCalls}. Equivalent to\n   * calling `useToolCalls(stream)` with no target.\n   */\n  readonly toolCalls: InferToolCalls<T>[];\n  /**\n   * All unresolved protocol interrupts observed on the root\n   * namespace during the active thread. Populated from lifecycle /\n   * input events and seeded on hydration from `thread.getState()`.\n   * Cleared optimistically when a new run starts or an interrupt is\n   * resolved via {@link respond}.\n   */\n  readonly interrupts: Interrupt<InterruptType>[];\n  /**\n   * Convenience alias for {@link interrupts}[0] — the primary\n   * interrupt most UIs should act on when only one is pending.\n   * `undefined` when no interrupt is active.\n   */\n  readonly interrupt: Interrupt<InterruptType> | undefined;\n  /**\n   * `true` while a run is active or being started on the current\n   * thread. Driven by root-namespace lifecycle events (`running` →\n   * `true`, terminal phases → `false`). Use this to disable submit\n   * buttons and show in-flight spinners.\n   */\n  readonly isLoading: boolean;\n  /**\n   * `true` while the initial `thread.getState()` hydration for the\n   * active thread is in flight. Distinct from {@link isLoading} —\n   * thread loading covers the one-time fetch that seeds\n   * {@link values} / {@link messages} before any user submit.\n   */\n  readonly isThreadLoading: boolean;\n  /**\n   * Promise that settles when the current thread's initial hydration\n   * completes. Exposed so Suspense wrappers can `throw` it until the\n   * first {@link StreamController.hydrate} call resolves (or rejects)\n   * for the active thread. A fresh promise is installed on every\n   * `switchThread`/`threadId` change.\n   */\n  readonly hydrationPromise: Promise<void>;\n  /**\n   * The last error observed on the active run or hydration attempt.\n   * `undefined` when no error has occurred. Cleared optimistically\n   * when a new {@link submit} starts.\n   */\n  readonly error: unknown;\n  /**\n   * Id of the thread the controller is bound to. `null` until the\n   * first {@link submit} creates or selects a thread (or until an\n   * explicit `threadId` option is provided and hydrated).\n   */\n  readonly threadId: string | null;\n\n  // ----- always-on discovery -----\n  /**\n   * Subagents discovered on the root run. For DeepAgent-typed\n   * streams the key set is narrowed to the subagent names declared\n   * on the agent brand (`keyof InferSubagentStates<T>`).\n   */\n  readonly subagents: ReadonlyMap<\n    keyof SubagentStates & string extends never\n      ? string\n      : keyof SubagentStates & string,\n    SubagentDiscoverySnapshot\n  >;\n  /**\n   * Subgraphs discovered on the root run.\n   *\n   * A namespace is classified as a subgraph iff at least one\n   * strictly-deeper namespace has been observed with it as a prefix.\n   * This is inferred from the lifecycle event stream — plain function\n   * nodes (`orchestrator`, `writer` in the nested-stategraph example)\n   * never appear here even though the server emits namespaced\n   * lifecycle events for them. Promotion is monotonic and retroactive;\n   * an entry appears as soon as the first descendant event lands.\n   */\n  readonly subgraphs: ReadonlyMap<string, SubgraphDiscoverySnapshot>;\n  /**\n   * Subgraphs indexed by the graph node that produced them\n   * (`addNode(\"visualizer_0\", …)`). Each value is an array because\n   * parallel fan-outs and loops can spawn multiple invocations of\n   * the same node; arrays preserve insertion order. Updates in\n   * lock-step with {@link subgraphs}.\n   */\n  readonly subgraphsByNode: ReadonlyMap<\n    string,\n    readonly SubgraphDiscoverySnapshot[]\n  >;\n\n  // ----- imperatives -----\n  /**\n   * Dispatch a new run on the bound thread.\n   *\n   * `input` is typed as `Partial<StateType>` so IDE autocompletion\n   * surfaces the state keys declared on the root hook.\n   */\n  submit(\n    input: WidenUpdateMessages<Partial<StateType>> | null | undefined,\n    options?: StreamSubmitOptions<StateType, ConfigurableType>\n  ): Promise<void>;\n  /**\n   * Stop the active run on the current thread. By default cancels the\n   * run server-side and disconnects the client; pass `{ cancel: false }`\n   * or use {@link disconnect} for join/rejoin. Sets {@link isLoading} to\n   * `false` immediately; {@link values} and {@link messages} are preserved.\n   */\n  stop(options?: StreamStopOptions): Promise<void>;\n  /**\n   * Disconnect the client without cancelling the run server-side.\n   * Alias for `stop({ cancel: false })`.\n   */\n  disconnect(): Promise<void>;\n  /**\n   * Resume a pending protocol interrupt by sending a response payload\n   * back to the interrupted namespace.\n   *\n   * When `options.interruptId` is omitted, walks `getThread()?.interrupts`\n   * from newest to oldest and resumes the first not yet resolved by a prior\n   * `respond()` call. That may be a root or subgraph interrupt and is\n   * **not** necessarily {@link interrupt} (`interrupts[0]`, root-only).\n   * Safe when exactly one interrupt is pending; otherwise pass an explicit\n   * `options.interruptId` (and `options.namespace` for subgraph\n   * interrupts).\n   *\n   * The server validates `namespace` against the pending interrupt. Root\n   * interrupts use `namespace: []` (default when omitted). For subgraph\n   * interrupts, copy `namespace` from `getThread()?.interrupts`.\n   *\n   * Pass `options.config` / `options.metadata` to fold run-level config\n   * (model, user context, …) and metadata (trigger source, test flags,\n   * …) into the resumed run, mirroring `submit()`.\n   *\n   * @example\n   * ```tsx\n   * // Single pending interrupt\n   * await stream.respond({ approved: true });\n   * ```\n   *\n   * @example\n   * ```tsx\n   * // Resume carrying run config + metadata\n   * await stream.respond({ approved: true }, {\n   *   config: { configurable: { model: \"gpt-4o\" } },\n   *   metadata: { source: \"ui\" },\n   * });\n   * ```\n   *\n   * @example\n   * ```tsx\n   * // Multiple root interrupts — one at a time\n   * stream.interrupts.map((intr) => (\n   *   <button\n   *     key={intr.id}\n   *     onClick={() =>\n   *       void stream.respond({ approved: true }, { interruptId: intr.id! })\n   *     }\n   *   />\n   * ));\n   * ```\n   *\n   * @example\n   * ```tsx\n   * // Subgraph interrupt — namespace from `getThread()`\n   * const thread = stream.getThread();\n   * thread?.interrupts.map((entry) => (\n   *   <button\n   *     key={entry.interruptId}\n   *     onClick={() =>\n   *       void stream.respond(buildResponse(entry.payload), {\n   *         interruptId: entry.interruptId,\n   *         namespace: entry.namespace,\n   *       })\n   *     }\n   *   />\n   * ));\n   * ```\n   *\n   * To resume several interrupts pending at the same checkpoint in one\n   * command, use {@link respondAll}.\n   */\n  respond(\n    response: unknown,\n    options?: StreamRespondOptions<ConfigurableType>\n  ): Promise<void>;\n\n  /**\n   * Resume several pending interrupts at the same checkpoint in a single\n   * command — required when a run pauses on multiple interrupts at once\n   * (e.g. parallel tool-authorization prompts), which sequential\n   * {@link respond} calls cannot handle (the first resume starts a run,\n   * leaving the rest with no interrupted run to respond to).\n   *\n   * `responsesById` maps each pending `interruptId` to its response, so\n   * different interrupts can receive different payloads. To send the same\n   * payload to several interrupts, build the map with that value for each\n   * id, e.g. `Object.fromEntries(ids.map((id) => [id, response]))`.\n   *\n   * Pass `options.config` / `options.metadata` to fold run-level config\n   * and metadata into the single run that services the batched resume,\n   * mirroring `submit()`.\n   *\n   * @example\n   * ```tsx\n   * // Distinct payloads per interrupt\n   * await stream.respondAll({\n   *   [interruptA.id]: { approved: true },\n   *   [interruptB.id]: { approved: false },\n   * });\n   * ```\n   *\n   * @example\n   * ```tsx\n   * // Same payload to every pending interrupt\n   * await stream.respondAll(\n   *   Object.fromEntries(stream.interrupts.map((i) => [i.id!, { approved: true }])),\n   * );\n   * ```\n   */\n  respondAll(\n    responsesById: Record<string, unknown>,\n    options?: StreamRespondAllOptions<ConfigurableType>\n  ): Promise<void>;\n\n  // ----- identity -----\n  /** LangGraph SDK client used to construct thread streams. */\n  readonly client: Client;\n  /** Assistant id the thread is bound to for its lifetime. */\n  readonly assistantId: string;\n\n  /**\n   * Returns the bound {@link ThreadStream}, if one exists (`undefined`\n   * until the thread is hydrated or the first submit completes). Prefer\n   * the projections and selector hooks for UI work; use this for\n   * low-level protocol access (raw subscriptions, state commands, etc.).\n   */\n  getThread(): ThreadStream | undefined;\n\n  /** @internal Used by selector hooks (`useMessages`, `useToolCalls`, …). */\n  readonly [STREAM_CONTROLLER]: StreamController<\n    StateType,\n    InterruptType,\n    ConfigurableType\n  >;\n}\n\n/**\n * Erased stream handle useful as a parameter type for helpers and\n * wrapper components that pass a `stream` through to selector hooks\n * (`useMessages`, `useChannel`, …) without reading `values` directly.\n * Any fully-typed `UseStreamReturn<S, I, C>` is\n * assignable to `AnyStream` because the generic slots are `any`\n * (bivariant), which avoids the `CompiledStateGraph` → `Record<string,\n * unknown>` assignment friction you hit when using the bare\n * `UseStreamReturn` default.\n *\n * @example\n * ```tsx\n * function SubgraphCard({ stream, subgraph }: {\n *   stream: AnyStream;\n *   subgraph: SubgraphDiscoverySnapshot;\n * }) {\n *   const messages = useMessages(stream, subgraph);\n *   return <Feed messages={messages} />;\n * }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyStream = UseStreamReturn<any, any, any>;\n\n/**\n * React binding for the v2-native stream runtime.\n *\n * `useStream` exposes three always-on projections\n * (`values` / `messages` / `toolCalls`) at the thread root plus\n * cheap discovery maps for subagents / subgraphs. Scoped views of\n * subagents, subgraphs, or any namespaced projection are surfaced via\n * the companion selector hooks:\n *\n * ```tsx\n * const stream = useStream({ assistantId: \"deep-agent\" });\n *\n * // Root messages — always on, already class instances.\n * stream.messages.map((m) => <Bubble key={m.id} msg={m} />);\n *\n * // Subagent view — mount = subscribe, unmount = unsubscribe.\n * function SubagentCard({ subagent }) {\n *   const messages = useMessages(stream, subagent);\n *   const toolCalls = useToolCalls(stream, subagent);\n *   return <>{messages.map(...)}</>;\n * }\n * ```\n *\n * The first generic accepts either a plain state type\n * (`useStream<MyState>()`) *or* a compiled graph type\n * (`useStream<typeof agent>()`); in the latter case the\n * state shape is unwrapped from the graph via {@link InferStateType}, so\n * `stream.values` is always typed as the state, never as the graph\n * class itself.\n */\nexport function useStream<\n  T = Record<string, unknown>,\n  InterruptType = unknown,\n  ConfigurableType extends object = Record<string, unknown>,\n>(\n  options: UseStreamOptions<InferStateType<T>>\n): UseStreamReturn<T, InterruptType, ConfigurableType> {\n  type StateType = InferStateType<T>;\n  // Branch-stable narrowings for each code path. The custom-adapter\n  // branch can skip LGP client construction entirely, which keeps\n  // bundles that *only* use a custom adapter free of the default\n  // `sse`/`websocket` transport factories (tree-shaken).\n  // Treat the options as a flat bag here — the discriminated union\n  // exists to give call sites a nice error message, but at runtime\n  // both branches are reachable through the same set of fields.\n  interface OptionsBag {\n    assistantId?: string;\n    threadId?: string | null;\n    client?: Client;\n    apiUrl?: string;\n    apiKey?: string;\n    callerOptions?: ClientConfig[\"callerOptions\"];\n    defaultHeaders?: ClientConfig[\"defaultHeaders\"];\n    transport?: \"sse\" | \"websocket\" | AgentServerAdapter;\n    fetch?: typeof fetch;\n    webSocketFactory?: (url: string) => WebSocket;\n    onThreadId?: (threadId: string) => void;\n    onCreated?: (info: RunExecutionInfo) => void;\n    onCompleted?: (info: RunCompletedInfo) => void;\n    initialValues?: StateType;\n    messagesKey?: string;\n  }\n  const asBag = options as OptionsBag;\n  // Narrow once: a non-string `transport` is a custom adapter; anything\n  // else (`\"sse\"` / `\"websocket\"` / `undefined`) is a built-in.\n  const hasCustomAdapter =\n    asBag.transport != null && typeof asBag.transport !== \"string\";\n  const transport = asBag.transport;\n\n  const client = useMemo<Client>(\n    () =>\n      asBag.client ??\n      (new ClientCtor({\n        apiUrl: asBag.apiUrl,\n        apiKey: asBag.apiKey,\n        callerOptions: asBag.callerOptions,\n        defaultHeaders: asBag.defaultHeaders,\n      }) as unknown as Client),\n    [\n      asBag.client,\n      asBag.apiUrl,\n      asBag.apiKey,\n      asBag.callerOptions,\n      asBag.defaultHeaders,\n    ]\n  );\n\n  // Custom adapters may omit `assistantId`; the controller still\n  // requires one so it has something to forward to `threads.stream`.\n  // `\"_\"` is the well-known sentinel for \"adapter doesn't care\".\n  const sentinel = \"_\";\n  const assistantId =\n    \"assistantId\" in options ? (options.assistantId ?? sentinel) : sentinel;\n\n  // Recreate the controller only on assistantId / client / transport\n  // change; the ThreadStream is bound to one assistant for its\n  // lifetime and we want selector-hook subscriptions to stay stable\n  // across renders.\n  const controller = useMemo(\n    () =>\n      new StreamController<StateType, InterruptType, ConfigurableType>({\n        assistantId,\n        // Cast: the runtime `Client` is state-shape agnostic, but the\n        // controller declares `client: Client<StateType>` so its own\n        // typings line up. Tightening `submit`'s `input` parameter to\n        // `Partial<StateType>` surfaced this variance mismatch that\n        // was previously masked — the cast is equivalent to the\n        // ClientCtor cast above.\n        client: client as unknown as Client<StateType>,\n        threadId: options.threadId ?? null,\n        transport,\n        fetch: hasCustomAdapter ? undefined : asBag.fetch,\n        webSocketFactory: hasCustomAdapter ? undefined : asBag.webSocketFactory,\n        onThreadId: options.onThreadId,\n        onCreated: options.onCreated,\n        onCompleted: options.onCompleted,\n        initialValues: options.initialValues,\n        messagesKey: options.messagesKey,\n      }),\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [client, assistantId, transport]\n  );\n\n  // Rehydrate on threadId change. The initial hydrate is fired\n  // synchronously inside the controller constructor so Suspense\n  // callers don't deadlock waiting for an effect that never runs\n  // (throwing `hydrationPromise` during render unmounts the subtree\n  // before effects fire). We only re-hydrate here when the threadId\n  // prop changes after the controller was already constructed with a\n  // matching id.\n  const lastHydratedRef = useRef<{\n    controller: StreamController<StateType, InterruptType, ConfigurableType>;\n    threadId: string | null;\n  } | null>(null);\n  useEffect(() => {\n    const target = options.threadId ?? null;\n    const last = lastHydratedRef.current;\n    if (last?.controller !== controller) {\n      // Freshly constructed controller already seeded the hydrate in\n      // its constructor — record the id and skip the redundant call.\n      lastHydratedRef.current = { controller, threadId: target };\n      return;\n    }\n    if (last.threadId === target) return;\n    lastHydratedRef.current = { controller, threadId: target };\n    void controller.hydrate(target);\n  }, [controller, options.threadId]);\n\n  // Dispose on unmount / controller swap.\n  //\n  // We use `controller.activate()` instead of a naive\n  // `() => controller.dispose()` cleanup because React 18+\n  // `<StrictMode>` in dev mounts → unmounts → remounts components\n  // synchronously to surface cleanup bugs. A naive cleanup would\n  // permanently tear the controller down on that first synthetic\n  // unmount and turn every subsequent `submit()` into a silent\n  // no-op. `activate()` defers disposal to the next microtask and\n  // cancels it if the effect re-runs — which is exactly the\n  // StrictMode remount pattern.\n  useEffect(() => controller.activate(), [controller]);\n\n  // Headless-tool handling: if the caller supplied `tools`, watch the\n  // root `values.__interrupt__` channel for protocol interrupts that\n  // target a registered tool, invoke the handler, and auto-resume the\n  // run. Ref-tracks the ids we've already handled so the same\n  // interrupt on a subsequent render is never executed twice\n  // (StrictMode safe).\n  const handledToolsRef = useRef<Set<string>>(new Set());\n  useEffect(() => {\n    handledToolsRef.current.clear();\n  }, [options.threadId]);\n  const tools = options.tools;\n  const onTool = options.onTool;\n  // Subscribe to values + interrupt updates via the root store so the\n  // effect re-runs whenever a protocol interrupt lands or the\n  // `__interrupt__` key is projected into values, not only on hook\n  // re-render. Prefer protocol interrupts from `rootStore.interrupts`\n  // (`input.requested` events) because their ids are accepted directly\n  // by `Command({ resume })`; fall back to `values.__interrupt__` for\n  // older streams that only expose interrupts through values.\n  const rootValuesForTools = useSyncExternalStore<StateType>(\n    controller.rootStore.subscribe,\n    () => controller.rootStore.getSnapshot().values,\n    () => controller.rootStore.getSnapshot().values\n  );\n  const rootInterruptsForTools = useSyncExternalStore<\n    readonly Interrupt<InterruptType>[]\n  >(\n    controller.rootStore.subscribe,\n    () => controller.rootStore.getSnapshot().interrupts,\n    () => controller.rootStore.getSnapshot().interrupts\n  );\n  useEffect(() => {\n    if (!tools?.length) return;\n    const valuesBag = rootValuesForTools as unknown as Record<string, unknown>;\n    const protocolInterrupts = rootInterruptsForTools as unknown as Interrupt[];\n    const valuesInterrupts = Array.isArray(valuesBag?.__interrupt__)\n      ? (valuesBag.__interrupt__ as Interrupt[])\n      : [];\n    const headlessInterrupts =\n      protocolInterrupts.length > 0 ? protocolInterrupts : valuesInterrupts;\n    if (headlessInterrupts.length === 0) return;\n    flushPendingHeadlessToolInterrupts(\n      { ...valuesBag, __interrupt__: headlessInterrupts },\n      tools,\n      handledToolsRef.current,\n      {\n        onTool,\n        defer: (run) => {\n          void Promise.resolve().then(run);\n        },\n        resumeSubmit: (command) =>\n          applyHeadlessToolResumeCommand(controller, command),\n      }\n    );\n  }, [controller, tools, onTool, rootValuesForTools, rootInterruptsForTools]);\n\n  const root = useSyncExternalStore<RootSnapshot<StateType, InterruptType>>(\n    controller.rootStore.subscribe,\n    controller.rootStore.getSnapshot,\n    controller.rootStore.getSnapshot\n  );\n  const subagents = useSyncExternalStore<SubagentMap>(\n    controller.subagentStore.subscribe,\n    controller.subagentStore.getSnapshot,\n    controller.subagentStore.getSnapshot\n  );\n  const subgraphs = useSyncExternalStore<SubgraphMap>(\n    controller.subgraphStore.subscribe,\n    controller.subgraphStore.getSnapshot,\n    controller.subgraphStore.getSnapshot\n  );\n  const subgraphsByNode = useSyncExternalStore<SubgraphByNodeMap>(\n    controller.subgraphByNodeStore.subscribe,\n    controller.subgraphByNodeStore.getSnapshot,\n    controller.subgraphByNodeStore.getSnapshot\n  );\n\n  return useMemo<UseStreamReturn<T, InterruptType, ConfigurableType>>(() => {\n    const userFacingInterrupts = filterOutHeadlessToolInterrupts(\n      root.interrupts\n    );\n    return {\n      values: root.values,\n      messages: root.messages,\n      toolCalls: root.toolCalls as InferToolCalls<T>[],\n      interrupts: userFacingInterrupts,\n      interrupt: userFacingInterrupts[0],\n      isLoading: root.isLoading,\n      isThreadLoading: root.isThreadLoading,\n      hydrationPromise: controller.hydrationPromise,\n      error: root.error,\n      threadId: root.threadId,\n      subagents: subagents as UseStreamReturn<\n        T,\n        InterruptType,\n        ConfigurableType\n      >[\"subagents\"],\n      subgraphs,\n      subgraphsByNode,\n      submit: (input, submitOptions) => controller.submit(input, submitOptions),\n      stop: (options) => controller.stop(options),\n      disconnect: () => controller.disconnect(),\n      respond: (response, options) => controller.respond(response, options),\n      respondAll: (responsesById, options) =>\n        controller.respondAll(responsesById, options),\n      getThread: () => controller.getThread(),\n      client,\n      assistantId,\n      [STREAM_CONTROLLER]: controller,\n    } as UseStreamReturn<T, InterruptType, ConfigurableType>;\n  }, [\n    root,\n    subagents,\n    subgraphs,\n    subgraphsByNode,\n    controller,\n    client,\n    assistantId,\n  ]);\n}\n\n/**\n * Convenience alias for the fully-resolved stream handle type.\n */\nexport type UseStreamResult<\n  T = Record<string, unknown>,\n  InterruptType = unknown,\n  ConfigurableType extends object = Record<string, unknown>,\n> = UseStreamReturn<T, InterruptType, ConfigurableType>;\n\n/**\n * Helper used by the selector hooks to reach the underlying\n * {@link ChannelRegistry} from a stream handle. Kept internal —\n * application code should call `useMessages`, `useToolCalls`, etc.\n * instead of reading this directly.\n *\n * @internal\n */\nexport function getRegistry(\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  stream: UseStreamReturn<any, any, any>\n): ChannelRegistry {\n  return stream[STREAM_CON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