diff --git a/.gitattributes b/.gitattributes index 445458ea87ae42c6e2f547ab9b32a8573b36a89c..73949ba865137d7c91cd0e22c746ea3e175c76d6 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4207,3 +4207,26 @@ tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/bin/cuobjd tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/bin/nvdisasm filter=lfs diff=lfs merge=lfs -text tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/bin/ptxas filter=lfs diff=lfs merge=lfs -text tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/bin/ptxas-blackwell filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/lib/libdevice.10.bc filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/lib/cupti/libcheckpoint.so filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so.12 filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so.2025.1.0 filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/lib/cupti/libcupti_static.a filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_host.so filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_host_static.a filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_target.so filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/lib/cupti/libpcsamplingutil.so filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/triton/language/__pycache__/core.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/triton/language/__pycache__/semantic.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/triton/runtime/__pycache__/interpreter.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/_hierarchy.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/_optimal_leaf_ordering.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/_vq.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/convolve.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_dop.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_lsoda.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_odepack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_quadpack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_test_odeint_banded.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_vode.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2140970015d099763797d60a98a3a3b6f4b5f219 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/__init__.py @@ -0,0 +1,14 @@ +""" +Module containing private utility functions +=========================================== + +The ``scipy._lib`` namespace is empty (for now). Tests for all +utilities in submodules of ``_lib`` can be run with:: + + from scipy import _lib + _lib.test() + +""" +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api.py new file mode 100644 index 0000000000000000000000000000000000000000..5e1170ac51ef7a0ee9ca226b41840ace90f7930f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api.py @@ -0,0 +1,931 @@ +"""Utility functions to use Python Array API compatible libraries. + +For the context about the Array API see: +https://data-apis.org/array-api/latest/purpose_and_scope.html + +The SciPy use case of the Array API is described on the following page: +https://data-apis.org/array-api/latest/use_cases.html#use-case-scipy +""" +import contextlib +import dataclasses +import functools +import os +import textwrap + +from collections.abc import Generator, Iterable, Iterator +from contextlib import contextmanager +from contextvars import ContextVar +from types import ModuleType +from typing import Any, Literal, TypeAlias + +import numpy as np +import numpy.typing as npt + +from scipy._lib import array_api_compat +from scipy._lib.array_api_compat import ( + is_array_api_obj, + is_lazy_array, + size as xp_size, + numpy as np_compat, + device as xp_device, + is_numpy_namespace as is_numpy, + is_cupy_namespace as is_cupy, + is_torch_namespace as is_torch, + is_jax_namespace as is_jax, + is_dask_namespace as is_dask, + is_array_api_strict_namespace as is_array_api_strict +) +from scipy._lib._sparse import issparse +from scipy._lib._docscrape import FunctionDoc + +__all__ = [ + '_asarray', 'array_namespace', 'assert_almost_equal', 'assert_array_almost_equal', + 'default_xp', 'eager_warns', 'is_lazy_array', 'is_marray', + 'is_array_api_strict', 'is_complex', 'is_cupy', 'is_jax', 'is_numpy', 'is_torch', + 'SCIPY_ARRAY_API', 'SCIPY_DEVICE', 'scipy_namespace_for', + 'xp_assert_close', 'xp_assert_equal', 'xp_assert_less', + 'xp_copy', 'xp_device', 'xp_ravel', 'xp_size', + 'xp_unsupported_param_msg', 'xp_vector_norm', 'xp_capabilities', + 'xp_result_type', 'xp_promote' +] + + +# To enable array API and strict array-like input validation +SCIPY_ARRAY_API: str | bool = os.environ.get("SCIPY_ARRAY_API", False) +# To control the default device - for use in the test suite only +SCIPY_DEVICE = os.environ.get("SCIPY_DEVICE", "cpu") + +_GLOBAL_CONFIG = { + "SCIPY_ARRAY_API": SCIPY_ARRAY_API, + "SCIPY_DEVICE": SCIPY_DEVICE, +} + + +Array: TypeAlias = Any # To be changed to a Protocol later (see array-api#589) +ArrayLike: TypeAlias = Array | npt.ArrayLike + + +def _compliance_scipy(arrays: Iterable[ArrayLike]) -> Iterator[Array]: + """Raise exceptions on known-bad subclasses. Discard 0-dimensional ArrayLikes + and convert 1+-dimensional ArrayLikes to numpy. + + The following subclasses are not supported and raise and error: + - `numpy.ma.MaskedArray` + - `numpy.matrix` + - NumPy arrays which do not have a boolean or numerical dtype + - Any array-like which is neither array API compatible nor coercible by NumPy + - Any array-like which is coerced by NumPy to an unsupported dtype + """ + for array in arrays: + if array is None: + continue + + # this comes from `_util._asarray_validated` + if issparse(array): + msg = ('Sparse arrays/matrices are not supported by this function. ' + 'Perhaps one of the `scipy.sparse.linalg` functions ' + 'would work instead.') + raise ValueError(msg) + + if isinstance(array, np.ma.MaskedArray): + raise TypeError("Inputs of type `numpy.ma.MaskedArray` are not supported.") + + if isinstance(array, np.matrix): + raise TypeError("Inputs of type `numpy.matrix` are not supported.") + + if isinstance(array, np.ndarray | np.generic): + dtype = array.dtype + if not (np.issubdtype(dtype, np.number) or np.issubdtype(dtype, np.bool_)): + raise TypeError(f"An argument has dtype `{dtype!r}`; " + f"only boolean and numerical dtypes are supported.") + + if is_array_api_obj(array): + yield array + else: + try: + array = np.asanyarray(array) + except TypeError: + raise TypeError("An argument is neither array API compatible nor " + "coercible by NumPy.") + dtype = array.dtype + if not (np.issubdtype(dtype, np.number) or np.issubdtype(dtype, np.bool_)): + message = ( + f"An argument was coerced to an unsupported dtype `{dtype!r}`; " + f"only boolean and numerical dtypes are supported." + ) + raise TypeError(message) + # Ignore 0-dimensional arrays, coherently with array-api-compat. + # Raise if there are 1+-dimensional array-likes mixed with non-numpy + # Array API objects. + if array.ndim: + yield array + + +def _check_finite(array: Array, xp: ModuleType) -> None: + """Check for NaNs or Infs.""" + if not xp.all(xp.isfinite(array)): + msg = "array must not contain infs or NaNs" + raise ValueError(msg) + + +def array_namespace(*arrays: Array) -> ModuleType: + """Get the array API compatible namespace for the arrays xs. + + Parameters + ---------- + *arrays : sequence of array_like + Arrays used to infer the common namespace. + + Returns + ------- + namespace : module + Common namespace. + + Notes + ----- + Thin wrapper around `array_api_compat.array_namespace`. + + 1. Check for the global switch: SCIPY_ARRAY_API. This can also be accessed + dynamically through ``_GLOBAL_CONFIG['SCIPY_ARRAY_API']``. + 2. `_compliance_scipy` raise exceptions on known-bad subclasses. See + its definition for more details. + + When the global switch is False, it defaults to the `numpy` namespace. + In that case, there is no compliance check. This is a convenience to + ease the adoption. Otherwise, arrays must comply with the new rules. + """ + if not _GLOBAL_CONFIG["SCIPY_ARRAY_API"]: + # here we could wrap the namespace if needed + return np_compat + + api_arrays = list(_compliance_scipy(arrays)) + # In case of a mix of array API compliant arrays and scalars, return + # the array API namespace. If there are only ArrayLikes (e.g. lists), + # return NumPy (wrapped by array-api-compat). + if api_arrays: + return array_api_compat.array_namespace(*api_arrays) + return np_compat + + +def _asarray( + array: ArrayLike, + dtype: Any = None, + order: Literal['K', 'A', 'C', 'F'] | None = None, + copy: bool | None = None, + *, + xp: ModuleType | None = None, + check_finite: bool = False, + subok: bool = False, + ) -> Array: + """SciPy-specific replacement for `np.asarray` with `order`, `check_finite`, and + `subok`. + + Memory layout parameter `order` is not exposed in the Array API standard. + `order` is only enforced if the input array implementation + is NumPy based, otherwise `order` is just silently ignored. + + `check_finite` is also not a keyword in the array API standard; included + here for convenience rather than that having to be a separate function + call inside SciPy functions. + + `subok` is included to allow this function to preserve the behaviour of + `np.asanyarray` for NumPy based inputs. + """ + if xp is None: + xp = array_namespace(array) + if is_numpy(xp): + # Use NumPy API to support order + if copy is True: + array = np.array(array, order=order, dtype=dtype, subok=subok) + elif subok: + array = np.asanyarray(array, order=order, dtype=dtype) + else: + array = np.asarray(array, order=order, dtype=dtype) + else: + try: + array = xp.asarray(array, dtype=dtype, copy=copy) + except TypeError: + coerced_xp = array_namespace(xp.asarray(3)) + array = coerced_xp.asarray(array, dtype=dtype, copy=copy) + + if check_finite: + _check_finite(array, xp) + + return array + + +def xp_copy(x: Array, *, xp: ModuleType | None = None) -> Array: + """ + Copies an array. + + Parameters + ---------- + x : array + + xp : array_namespace + + Returns + ------- + copy : array + Copied array + + Notes + ----- + This copy function does not offer all the semantics of `np.copy`, i.e. the + `subok` and `order` keywords are not used. + """ + # Note: for older NumPy versions, `np.asarray` did not support the `copy` kwarg, + # so this uses our other helper `_asarray`. + if xp is None: + xp = array_namespace(x) + + return _asarray(x, copy=True, xp=xp) + + +_default_xp_ctxvar: ContextVar[ModuleType] = ContextVar("_default_xp") + +@contextmanager +def default_xp(xp: ModuleType) -> Generator[None, None, None]: + """In all ``xp_assert_*`` and ``assert_*`` function calls executed within this + context manager, test by default that the array namespace is + the provided across all arrays, unless one explicitly passes the ``xp=`` + parameter or ``check_namespace=False``. + + Without this context manager, the default value for `xp` is the namespace + for the desired array (the second parameter of the tests). + """ + token = _default_xp_ctxvar.set(xp) + try: + yield + finally: + _default_xp_ctxvar.reset(token) + + +def eager_warns(x, warning_type, match=None): + """pytest.warns context manager, but only if x is not a lazy array.""" + import pytest + # This attribute is interpreted by pytest-run-parallel, ensuring that tests that use + # `eager_warns` aren't run in parallel (since pytest.warns isn't thread-safe). + __thread_safe__ = False # noqa: F841 + if is_lazy_array(x): + return contextlib.nullcontext() + return pytest.warns(warning_type, match=match) + + +def _strict_check(actual, desired, xp, *, + check_namespace=True, check_dtype=True, check_shape=True, + check_0d=True): + __tracebackhide__ = True # Hide traceback for py.test + + if xp is None: + try: + xp = _default_xp_ctxvar.get() + except LookupError: + xp = array_namespace(desired) + + if check_namespace: + _assert_matching_namespace(actual, desired, xp) + + # only NumPy distinguishes between scalars and arrays; we do if check_0d=True. + # do this first so we can then cast to array (and thus use the array API) below. + if is_numpy(xp) and check_0d: + _msg = ("Array-ness does not match:\n Actual: " + f"{type(actual)}\n Desired: {type(desired)}") + assert ((xp.isscalar(actual) and xp.isscalar(desired)) + or (not xp.isscalar(actual) and not xp.isscalar(desired))), _msg + + actual = xp.asarray(actual) + desired = xp.asarray(desired) + + if check_dtype: + _msg = f"dtypes do not match.\nActual: {actual.dtype}\nDesired: {desired.dtype}" + assert actual.dtype == desired.dtype, _msg + + if check_shape: + if is_dask(xp): + actual.compute_chunk_sizes() + desired.compute_chunk_sizes() + _msg = f"Shapes do not match.\nActual: {actual.shape}\nDesired: {desired.shape}" + assert actual.shape == desired.shape, _msg + + desired = xp.broadcast_to(desired, actual.shape) + return actual, desired, xp + + +def _assert_matching_namespace(actual, desired, xp): + __tracebackhide__ = True # Hide traceback for py.test + + desired_arr_space = array_namespace(desired) + _msg = ("Namespace of desired array does not match expectations " + "set by the `default_xp` context manager or by the `xp`" + "pytest fixture.\n" + f"Desired array's space: {desired_arr_space.__name__}\n" + f"Expected namespace: {xp.__name__}") + assert desired_arr_space == xp, _msg + + actual_arr_space = array_namespace(actual) + _msg = ("Namespace of actual and desired arrays do not match.\n" + f"Actual: {actual_arr_space.__name__}\n" + f"Desired: {xp.__name__}") + assert actual_arr_space == xp, _msg + + +def xp_assert_equal(actual, desired, *, check_namespace=True, check_dtype=True, + check_shape=True, check_0d=True, err_msg='', xp=None): + __tracebackhide__ = True # Hide traceback for py.test + + actual, desired, xp = _strict_check( + actual, desired, xp, check_namespace=check_namespace, + check_dtype=check_dtype, check_shape=check_shape, + check_0d=check_0d + ) + + if is_cupy(xp): + return xp.testing.assert_array_equal(actual, desired, err_msg=err_msg) + elif is_torch(xp): + # PyTorch recommends using `rtol=0, atol=0` like this + # to test for exact equality + err_msg = None if err_msg == '' else err_msg + return xp.testing.assert_close(actual, desired, rtol=0, atol=0, equal_nan=True, + check_dtype=False, msg=err_msg) + # JAX uses `np.testing` + return np.testing.assert_array_equal(actual, desired, err_msg=err_msg) + + +def xp_assert_close(actual, desired, *, rtol=None, atol=0, check_namespace=True, + check_dtype=True, check_shape=True, check_0d=True, + err_msg='', xp=None): + __tracebackhide__ = True # Hide traceback for py.test + + actual, desired, xp = _strict_check( + actual, desired, xp, + check_namespace=check_namespace, check_dtype=check_dtype, + check_shape=check_shape, check_0d=check_0d + ) + + floating = xp.isdtype(actual.dtype, ('real floating', 'complex floating')) + if rtol is None and floating: + # multiplier of 4 is used as for `np.float64` this puts the default `rtol` + # roughly half way between sqrt(eps) and the default for + # `numpy.testing.assert_allclose`, 1e-7 + rtol = xp.finfo(actual.dtype).eps**0.5 * 4 + elif rtol is None: + rtol = 1e-7 + + if is_cupy(xp): + return xp.testing.assert_allclose(actual, desired, rtol=rtol, + atol=atol, err_msg=err_msg) + elif is_torch(xp): + err_msg = None if err_msg == '' else err_msg + return xp.testing.assert_close(actual, desired, rtol=rtol, atol=atol, + equal_nan=True, check_dtype=False, msg=err_msg) + # JAX uses `np.testing` + return np.testing.assert_allclose(actual, desired, rtol=rtol, + atol=atol, err_msg=err_msg) + + +def xp_assert_less(actual, desired, *, check_namespace=True, check_dtype=True, + check_shape=True, check_0d=True, err_msg='', verbose=True, xp=None): + __tracebackhide__ = True # Hide traceback for py.test + + actual, desired, xp = _strict_check( + actual, desired, xp, check_namespace=check_namespace, + check_dtype=check_dtype, check_shape=check_shape, + check_0d=check_0d + ) + + if is_cupy(xp): + return xp.testing.assert_array_less(actual, desired, + err_msg=err_msg, verbose=verbose) + elif is_torch(xp): + if actual.device.type != 'cpu': + actual = actual.cpu() + if desired.device.type != 'cpu': + desired = desired.cpu() + # JAX uses `np.testing` + return np.testing.assert_array_less(actual, desired, + err_msg=err_msg, verbose=verbose) + + +def assert_array_almost_equal(actual, desired, decimal=6, *args, **kwds): + """Backwards compatible replacement. In new code, use xp_assert_close instead. + """ + rtol, atol = 0, 1.5*10**(-decimal) + return xp_assert_close(actual, desired, + atol=atol, rtol=rtol, check_dtype=False, check_shape=False, + *args, **kwds) + + +def assert_almost_equal(actual, desired, decimal=7, *args, **kwds): + """Backwards compatible replacement. In new code, use xp_assert_close instead. + """ + rtol, atol = 0, 1.5*10**(-decimal) + return xp_assert_close(actual, desired, + atol=atol, rtol=rtol, check_dtype=False, check_shape=False, + *args, **kwds) + + +def xp_unsupported_param_msg(param: Any) -> str: + return f'Providing {param!r} is only supported for numpy arrays.' + + +def is_complex(x: Array, xp: ModuleType) -> bool: + return xp.isdtype(x.dtype, 'complex floating') + + +def scipy_namespace_for(xp: ModuleType) -> ModuleType | None: + """Return the `scipy`-like namespace of a non-NumPy backend + + That is, return the namespace corresponding with backend `xp` that contains + `scipy` sub-namespaces like `linalg` and `special`. If no such namespace + exists, return ``None``. Useful for dispatching. + """ + + if is_cupy(xp): + import cupyx # type: ignore[import-not-found,import-untyped] + return cupyx.scipy + + if is_jax(xp): + import jax # type: ignore[import-not-found] + return jax.scipy + + if is_torch(xp): + return xp + + return None + + +# maybe use `scipy.linalg` if/when array API support is added +def xp_vector_norm(x: Array, /, *, + axis: int | tuple[int] | None = None, + keepdims: bool = False, + ord: int | float = 2, + xp: ModuleType | None = None) -> Array: + xp = array_namespace(x) if xp is None else xp + + if SCIPY_ARRAY_API: + # check for optional `linalg` extension + if hasattr(xp, 'linalg'): + return xp.linalg.vector_norm(x, axis=axis, keepdims=keepdims, ord=ord) + else: + if ord != 2: + raise ValueError( + "only the Euclidean norm (`ord=2`) is currently supported in " + "`xp_vector_norm` for backends not implementing the `linalg` " + "extension." + ) + # return (x @ x)**0.5 + # or to get the right behavior with nd, complex arrays + return xp.sum(xp.conj(x) * x, axis=axis, keepdims=keepdims)**0.5 + else: + # to maintain backwards compatibility + return np.linalg.norm(x, ord=ord, axis=axis, keepdims=keepdims) + + +def xp_ravel(x: Array, /, *, xp: ModuleType | None = None) -> Array: + # Equivalent of np.ravel written in terms of array API + # Even though it's one line, it comes up so often that it's worth having + # this function for readability + xp = array_namespace(x) if xp is None else xp + return xp.reshape(x, (-1,)) + + +def xp_swapaxes(a, axis1, axis2, xp=None): + # Equivalent of np.swapaxes written in terms of array API + xp = array_namespace(a) if xp is None else xp + axes = list(range(a.ndim)) + axes[axis1], axes[axis2] = axes[axis2], axes[axis1] + a = xp.permute_dims(a, axes) + return a + + +# utility to find common dtype with option to force floating +def xp_result_type(*args, force_floating=False, xp): + """ + Returns the dtype that results from applying type promotion rules + (see Array API Standard Type Promotion Rules) to the arguments. Augments + standard `result_type` in a few ways: + + - There is a `force_floating` argument that ensures that the result type + is floating point, even when all args are integer. + - When a TypeError is raised (e.g. due to an unsupported promotion) + and `force_floating=True`, we define a custom rule: use the result type + of the default float and any other floats passed. See + https://github.com/scipy/scipy/pull/22695/files#r1997905891 + for rationale. + - This function accepts array-like iterables, which are immediately converted + to the namespace's arrays before result type calculation. Consequently, the + result dtype may be different when an argument is `1.` vs `[1.]`. + + Typically, this function will be called shortly after `array_namespace` + on a subset of the arguments passed to `array_namespace`. + """ + args = [(_asarray(arg, subok=True, xp=xp) if np.iterable(arg) else arg) + for arg in args] + args_not_none = [arg for arg in args if arg is not None] + if force_floating: + args_not_none.append(1.0) + + if is_numpy(xp) and xp.__version__ < '2.0': + # Follow NEP 50 promotion rules anyway + args_not_none = [arg.dtype if getattr(arg, 'size', 0) == 1 else arg + for arg in args_not_none] + return xp.result_type(*args_not_none) + + try: # follow library's preferred promotion rules + return xp.result_type(*args_not_none) + except TypeError: # mixed type promotion isn't defined + if not force_floating: + raise + # use `result_type` of default floating point type and any floats present + # This can be revisited, but right now, the only backends that get here + # are array-api-strict (which is not for production use) and PyTorch + # (due to data-apis/array-api-compat#279). + float_args = [] + for arg in args_not_none: + arg_array = xp.asarray(arg) if np.isscalar(arg) else arg + dtype = getattr(arg_array, 'dtype', arg) + if xp.isdtype(dtype, ('real floating', 'complex floating')): + float_args.append(arg) + return xp.result_type(*float_args, xp_default_dtype(xp)) + + +def xp_promote(*args, broadcast=False, force_floating=False, xp): + """ + Promotes elements of *args to result dtype, ignoring `None`s. + Includes options for forcing promotion to floating point and + broadcasting the arrays, again ignoring `None`s. + Type promotion rules follow `xp_result_type` instead of `xp.result_type`. + + Typically, this function will be called shortly after `array_namespace` + on a subset of the arguments passed to `array_namespace`. + + This function accepts array-like iterables, which are immediately converted + to the namespace's arrays before result type calculation. Consequently, the + result dtype may be different when an argument is `1.` vs `[1.]`. + + See Also + -------- + xp_result_type + """ + args = [(_asarray(arg, subok=True, xp=xp) if np.iterable(arg) else arg) + for arg in args] # solely to prevent double conversion of iterable to array + + dtype = xp_result_type(*args, force_floating=force_floating, xp=xp) + + args = [(_asarray(arg, dtype=dtype, subok=True, xp=xp) if arg is not None else arg) + for arg in args] + + if not broadcast: + return args[0] if len(args)==1 else tuple(args) + + args_not_none = [arg for arg in args if arg is not None] + + # determine result shape + shapes = {arg.shape for arg in args_not_none} + try: + shape = (np.broadcast_shapes(*shapes) if len(shapes) != 1 + else args_not_none[0].shape) + except ValueError as e: + message = "Array shapes are incompatible for broadcasting." + raise ValueError(message) from e + + out = [] + for arg in args: + if arg is None: + out.append(arg) + continue + + # broadcast only if needed + # Even if two arguments need broadcasting, this is faster than + # `broadcast_arrays`, especially since we've already determined `shape` + if arg.shape != shape: + kwargs = {'subok': True} if is_numpy(xp) else {} + arg = xp.broadcast_to(arg, shape, **kwargs) + + # This is much faster than xp.astype(arg, dtype, copy=False) + if arg.dtype != dtype: + arg = xp.astype(arg, dtype) + + out.append(arg) + + return out[0] if len(out)==1 else tuple(out) + + +def xp_float_to_complex(arr: Array, xp: ModuleType | None = None) -> Array: + xp = array_namespace(arr) if xp is None else xp + arr_dtype = arr.dtype + # The standard float dtypes are float32 and float64. + # Convert float32 to complex64, + # and float64 (and non-standard real dtypes) to complex128 + if xp.isdtype(arr_dtype, xp.float32): + arr = xp.astype(arr, xp.complex64) + elif xp.isdtype(arr_dtype, 'real floating'): + arr = xp.astype(arr, xp.complex128) + + return arr + + +def xp_default_dtype(xp): + """Query the namespace-dependent default floating-point dtype. + """ + if is_torch(xp): + # historically, we allow pytorch to keep its default of float32 + return xp.get_default_dtype() + else: + # we default to float64 + return xp.float64 + + +def xp_result_device(*args): + """Return the device of an array in `args`, for the purpose of + input-output device propagation. + If there are multiple devices, return an arbitrary one. + If there are no arrays, return None (this typically happens only on NumPy). + """ + for arg in args: + # Do not do a duck-type test for the .device attribute, as many backends today + # don't have it yet. See workarouunds in array_api_compat.device(). + if is_array_api_obj(arg): + return xp_device(arg) + return None + + +def is_marray(xp): + """Returns True if `xp` is an MArray namespace; False otherwise.""" + return "marray" in xp.__name__ + + +@dataclasses.dataclass(repr=False) +class _XPSphinxCapability: + cpu: bool | None # None if not applicable + gpu: bool | None + warnings: list[str] = dataclasses.field(default_factory=list) + + def _render(self, value): + if value is None: + return "n/a" + if not value: + return "⛔" + if self.warnings: + res = "⚠️ " + '; '.join(self.warnings) + assert len(res) <= 20, "Warnings too long" + return res + return "✅" + + def __str__(self): + cpu = self._render(self.cpu) + gpu = self._render(self.gpu) + return f"{cpu:20} {gpu:20}" + + +def _make_sphinx_capabilities( + # lists of tuples [(module name, reason), ...] + skip_backends=(), xfail_backends=(), + # @pytest.mark.skip/xfail_xp_backends kwargs + cpu_only=False, np_only=False, exceptions=(), + # xpx.lazy_xp_backends kwargs + allow_dask_compute=False, jax_jit=True, + # list of tuples [(module name, reason), ...] + warnings = (), + # unused in documentation + reason=None, +): + exceptions = set(exceptions) + + # Default capabilities + capabilities = { + "numpy": _XPSphinxCapability(cpu=True, gpu=None), + "array_api_strict": _XPSphinxCapability(cpu=True, gpu=None), + "cupy": _XPSphinxCapability(cpu=None, gpu=True), + "torch": _XPSphinxCapability(cpu=True, gpu=True), + "jax.numpy": _XPSphinxCapability(cpu=True, gpu=True, + warnings=[] if jax_jit else ["no JIT"]), + # Note: Dask+CuPy is currently untested and unsupported + "dask.array": _XPSphinxCapability(cpu=True, gpu=None, + warnings=["computes graph"] if allow_dask_compute else []), + } + + # documentation doesn't display the reason + for module, _ in list(skip_backends) + list(xfail_backends): + backend = capabilities[module] + if backend.cpu is not None: + backend.cpu = False + if backend.gpu is not None: + backend.gpu = False + + for module, backend in capabilities.items(): + if np_only and module not in exceptions | {"numpy"}: + if backend.cpu is not None: + backend.cpu = False + if backend.gpu is not None: + backend.gpu = False + elif cpu_only and module not in exceptions and backend.gpu is not None: + backend.gpu = False + + for module, warning in warnings: + backend = capabilities[module] + backend.warnings.append(warning) + + return capabilities + + +def _make_capabilities_note(fun_name, capabilities): + # Note: deliberately not documenting array-api-strict + note = f""" + `{fun_name}` has experimental support for Python Array API Standard compatible + backends in addition to NumPy. Please consider testing these features + by setting an environment variable ``SCIPY_ARRAY_API=1`` and providing + CuPy, PyTorch, JAX, or Dask arrays as array arguments. The following + combinations of backend and device (or other capability) are supported. + + ==================== ==================== ==================== + Library CPU GPU + ==================== ==================== ==================== + NumPy {capabilities['numpy'] } + CuPy {capabilities['cupy'] } + PyTorch {capabilities['torch'] } + JAX {capabilities['jax.numpy'] } + Dask {capabilities['dask.array'] } + ==================== ==================== ==================== + + See :ref:`dev-arrayapi` for more information. + """ + return textwrap.dedent(note) + + +def xp_capabilities( + *, + # Alternative capabilities table. + # Used only for testing this decorator. + capabilities_table=None, + # Generate pytest.mark.skip/xfail_xp_backends. + # See documentation in conftest.py. + # lists of tuples [(module name, reason), ...] + skip_backends=(), xfail_backends=(), + cpu_only=False, np_only=False, reason=None, exceptions=(), + # lists of tuples [(module name, reason), ...] + warnings=(), + # xpx.testing.lazy_xp_function kwargs. + # Refer to array-api-extra documentation. + allow_dask_compute=False, jax_jit=True, +): + """Decorator for a function that states its support among various + Array API compatible backends. + + This decorator has two effects: + 1. It allows tagging tests with ``@make_xp_test_case`` or + ``make_xp_pytest_param`` (see below) to automatically generate + SKIP/XFAIL markers and perform additional backend-specific + testing, such as extra validation for Dask and JAX; + 2. It automatically adds a note to the function's docstring, containing + a table matching what has been tested. + + See Also + -------- + make_xp_test_case + make_xp_pytest_param + array_api_extra.testing.lazy_xp_function + """ + capabilities_table = (xp_capabilities_table if capabilities_table is None + else capabilities_table) + + capabilities = dict( + skip_backends=skip_backends, + xfail_backends=xfail_backends, + cpu_only=cpu_only, + np_only=np_only, + reason=reason, + exceptions=exceptions, + allow_dask_compute=allow_dask_compute, + jax_jit=jax_jit, + warnings=warnings, + ) + sphinx_capabilities = _make_sphinx_capabilities(**capabilities) + + def decorator(f): + # Don't use a wrapper, as in some cases @xp_capabilities is + # applied to a ufunc + capabilities_table[f] = capabilities + note = _make_capabilities_note(f.__name__, sphinx_capabilities) + doc = FunctionDoc(f) + doc['Notes'].append(note) + doc = str(doc).split("\n", 1)[1] # remove signature + try: + f.__doc__ = doc + except AttributeError: + # Can't update __doc__ on ufuncs if SciPy + # was compiled against NumPy < 2.2. + pass + + return f + return decorator + + +def _make_xp_pytest_marks(*funcs, capabilities_table=None): + capabilities_table = (xp_capabilities_table if capabilities_table is None + else capabilities_table) + import pytest + from scipy._lib.array_api_extra.testing import lazy_xp_function + + marks = [] + for func in funcs: + capabilities = capabilities_table[func] + exceptions = capabilities['exceptions'] + reason = capabilities['reason'] + + if capabilities['cpu_only']: + marks.append(pytest.mark.skip_xp_backends( + cpu_only=True, exceptions=exceptions, reason=reason)) + if capabilities['np_only']: + marks.append(pytest.mark.skip_xp_backends( + np_only=True, exceptions=exceptions, reason=reason)) + + for mod_name, reason in capabilities['skip_backends']: + marks.append(pytest.mark.skip_xp_backends(mod_name, reason=reason)) + for mod_name, reason in capabilities['xfail_backends']: + marks.append(pytest.mark.xfail_xp_backends(mod_name, reason=reason)) + + lazy_kwargs = {k: capabilities[k] + for k in ('allow_dask_compute', 'jax_jit')} + lazy_xp_function(func, **lazy_kwargs) + + return marks + + +def make_xp_test_case(*funcs, capabilities_table=None): + capabilities_table = (xp_capabilities_table if capabilities_table is None + else capabilities_table) + """Generate pytest decorator for a test function that tests functionality + of one or more Array API compatible functions. + + Read the parameters of the ``@xp_capabilities`` decorator applied to the + listed functions and: + + - Generate the ``@pytest.mark.skip_xp_backends`` and + ``@pytest.mark.xfail_xp_backends`` decorators + for the decorated test function + - Tag the function with `xpx.testing.lazy_xp_function` + + See Also + -------- + xp_capabilities + make_xp_pytest_param + array_api_extra.testing.lazy_xp_function + """ + marks = _make_xp_pytest_marks(*funcs, capabilities_table=capabilities_table) + return lambda func: functools.reduce(lambda f, g: g(f), marks, func) + + +def make_xp_pytest_param(func, *args, capabilities_table=None): + """Variant of ``make_xp_test_case`` that returns a pytest.param for a function, + with all necessary skip_xp_backends and xfail_xp_backends marks applied:: + + @pytest.mark.parametrize( + "func", [make_xp_pytest_param(f1), make_xp_pytest_param(f2)] + ) + def test(func, xp): + ... + + The above is equivalent to:: + + @pytest.mark.parametrize( + "func", [ + pytest.param(f1, marks=[ + pytest.mark.skip_xp_backends(...), + pytest.mark.xfail_xp_backends(...), ...]), + pytest.param(f2, marks=[ + pytest.mark.skip_xp_backends(...), + pytest.mark.xfail_xp_backends(...), ...]), + ) + def test(func, xp): + ... + + Parameters + ---------- + func : Callable + Function to be tested. It must be decorated with ``@xp_capabilities``. + *args : Any, optional + Extra pytest parameters for the use case, e.g.:: + + @pytest.mark.parametrize("func,verb", [ + make_xp_pytest_param(f1, "hello"), + make_xp_pytest_param(f2, "world")]) + def test(func, verb, xp): + # iterates on (func=f1, verb="hello") + # and (func=f2, verb="world") + + See Also + -------- + xp_capabilities + make_xp_test_case + array_api_extra.testing.lazy_xp_function + """ + import pytest + + marks = _make_xp_pytest_marks(func, capabilities_table=capabilities_table) + return pytest.param(func, *args, marks=marks, id=func.__name__) + + +# Is it OK to have a dictionary that is mutated (once upon import) in many places? +xp_capabilities_table = {} # type: ignore[var-annotated] diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api_compat_vendor.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api_compat_vendor.py new file mode 100644 index 0000000000000000000000000000000000000000..85c720f57a901286633af956248f8be0c0860a65 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api_compat_vendor.py @@ -0,0 +1,9 @@ +# DO NOT RENAME THIS FILE +# This is a hook for array_api_extra/src/array_api_extra/_lib/_compat.py +# to override functions of array_api_compat. + +from .array_api_compat import * # noqa: F403 +from ._array_api import array_namespace as scipy_array_namespace + +# overrides array_api_compat.array_namespace inside array-api-extra +array_namespace = scipy_array_namespace # type: ignore[assignment] diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api_no_0d.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api_no_0d.py new file mode 100644 index 0000000000000000000000000000000000000000..a6b6fe1affd172eea620760a20f185f192d37b69 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_array_api_no_0d.py @@ -0,0 +1,103 @@ +""" +Extra testing functions that forbid 0d-input, see #21044 + +While the xp_assert_* functions generally aim to follow the conventions of the +underlying `xp` library, NumPy in particular is inconsistent in its handling +of scalars vs. 0d-arrays, see https://github.com/numpy/numpy/issues/24897. + +For example, this means that the following operations (as of v2.0.1) currently +return scalars, even though a 0d-array would often be more appropriate: + + import numpy as np + np.array(0) * 2 # scalar, not 0d array + - np.array(0) # scalar, not 0d-array + np.sin(np.array(0)) # scalar, not 0d array + np.mean([1, 2, 3]) # scalar, not 0d array + +Libraries like CuPy tend to return a 0d-array in scenarios like those above, +and even `xp.asarray(0)[()]` remains a 0d-array there. To deal with the reality +of the inconsistencies present in NumPy, as well as 20+ years of code on top, +the `xp_assert_*` functions here enforce consistency in the only way that +doesn't go against the tide, i.e. by forbidding 0d-arrays as the return type. + +However, when scalars are not generally the expected NumPy return type, +it remains preferable to use the assert functions from +the `scipy._lib._array_api` module, which have less surprising behaviour. +""" +from scipy._lib._array_api import array_namespace, is_numpy +from scipy._lib._array_api import (xp_assert_close as xp_assert_close_base, + xp_assert_equal as xp_assert_equal_base, + xp_assert_less as xp_assert_less_base) + +__all__: list[str] = [] + + +def _check_scalar(actual, desired, *, xp=None, **kwargs): + __tracebackhide__ = True # Hide traceback for py.test + + if xp is None: + xp = array_namespace(actual) + + # necessary to handle non-numpy scalars, e.g. bare `0.0` has no shape + desired = xp.asarray(desired) + + # Only NumPy distinguishes between scalars and arrays; + # shape check in xp_assert_* is sufficient except for shape == () + if not (is_numpy(xp) and desired.shape == ()): + return + + _msg = ("Result is a NumPy 0d-array. Many SciPy functions intend to follow " + "the convention of many NumPy functions, returning a scalar when a " + "0d-array would be correct. The specialized `xp_assert_*` functions " + "in the `scipy._lib._array_api_no_0d` module err on the side of " + "caution and do not accept 0d-arrays by default. If the correct " + "result may legitimately be a 0d-array, pass `check_0d=True`, " + "or use the `xp_assert_*` functions from `scipy._lib._array_api`.") + assert xp.isscalar(actual), _msg + + +def xp_assert_equal(actual, desired, *, check_0d=False, **kwargs): + # in contrast to xp_assert_equal_base, this defaults to check_0d=False, + # but will do an extra check in that case, which forbids 0d-arrays for `actual` + __tracebackhide__ = True # Hide traceback for py.test + + # array-ness (check_0d == True) is taken care of by the *_base functions + if not check_0d: + _check_scalar(actual, desired, **kwargs) + return xp_assert_equal_base(actual, desired, check_0d=check_0d, **kwargs) + + +def xp_assert_close(actual, desired, *, check_0d=False, **kwargs): + # as for xp_assert_equal + __tracebackhide__ = True + + if not check_0d: + _check_scalar(actual, desired, **kwargs) + return xp_assert_close_base(actual, desired, check_0d=check_0d, **kwargs) + + +def xp_assert_less(actual, desired, *, check_0d=False, **kwargs): + # as for xp_assert_equal + __tracebackhide__ = True + + if not check_0d: + _check_scalar(actual, desired, **kwargs) + return xp_assert_less_base(actual, desired, check_0d=check_0d, **kwargs) + + +def assert_array_almost_equal(actual, desired, decimal=6, *args, **kwds): + """Backwards compatible replacement. In new code, use xp_assert_close instead. + """ + rtol, atol = 0, 1.5*10**(-decimal) + return xp_assert_close(actual, desired, + atol=atol, rtol=rtol, check_dtype=False, check_shape=False, + *args, **kwds) + + +def assert_almost_equal(actual, desired, decimal=7, *args, **kwds): + """Backwards compatible replacement. In new code, use xp_assert_close instead. + """ + rtol, atol = 0, 1.5*10**(-decimal) + return xp_assert_close(actual, desired, + atol=atol, rtol=rtol, check_dtype=False, check_shape=False, + *args, **kwds) diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_bunch.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_bunch.py new file mode 100644 index 0000000000000000000000000000000000000000..172e7dce1b25d0a70c1810e3d133f4b6bd12a538 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_bunch.py @@ -0,0 +1,229 @@ +import sys as _sys +from keyword import iskeyword as _iskeyword + + +def _validate_names(typename, field_names, extra_field_names): + """ + Ensure that all the given names are valid Python identifiers that + do not start with '_'. Also check that there are no duplicates + among field_names + extra_field_names. + """ + for name in [typename] + field_names + extra_field_names: + if not isinstance(name, str): + raise TypeError('typename and all field names must be strings') + if not name.isidentifier(): + raise ValueError('typename and all field names must be valid ' + f'identifiers: {name!r}') + if _iskeyword(name): + raise ValueError('typename and all field names cannot be a ' + f'keyword: {name!r}') + + seen = set() + for name in field_names + extra_field_names: + if name.startswith('_'): + raise ValueError('Field names cannot start with an underscore: ' + f'{name!r}') + if name in seen: + raise ValueError(f'Duplicate field name: {name!r}') + seen.add(name) + + +# Note: This code is adapted from CPython:Lib/collections/__init__.py +def _make_tuple_bunch(typename, field_names, extra_field_names=None, + module=None): + """ + Create a namedtuple-like class with additional attributes. + + This function creates a subclass of tuple that acts like a namedtuple + and that has additional attributes. + + The additional attributes are listed in `extra_field_names`. The + values assigned to these attributes are not part of the tuple. + + The reason this function exists is to allow functions in SciPy + that currently return a tuple or a namedtuple to returned objects + that have additional attributes, while maintaining backwards + compatibility. + + This should only be used to enhance *existing* functions in SciPy. + New functions are free to create objects as return values without + having to maintain backwards compatibility with an old tuple or + namedtuple return value. + + Parameters + ---------- + typename : str + The name of the type. + field_names : list of str + List of names of the values to be stored in the tuple. These names + will also be attributes of instances, so the values in the tuple + can be accessed by indexing or as attributes. At least one name + is required. See the Notes for additional restrictions. + extra_field_names : list of str, optional + List of names of values that will be stored as attributes of the + object. See the notes for additional restrictions. + + Returns + ------- + cls : type + The new class. + + Notes + ----- + There are restrictions on the names that may be used in `field_names` + and `extra_field_names`: + + * The names must be unique--no duplicates allowed. + * The names must be valid Python identifiers, and must not begin with + an underscore. + * The names must not be Python keywords (e.g. 'def', 'and', etc., are + not allowed). + + Examples + -------- + >>> from scipy._lib._bunch import _make_tuple_bunch + + Create a class that acts like a namedtuple with length 2 (with field + names `x` and `y`) that will also have the attributes `w` and `beta`: + + >>> Result = _make_tuple_bunch('Result', ['x', 'y'], ['w', 'beta']) + + `Result` is the new class. We call it with keyword arguments to create + a new instance with given values. + + >>> result1 = Result(x=1, y=2, w=99, beta=0.5) + >>> result1 + Result(x=1, y=2, w=99, beta=0.5) + + `result1` acts like a tuple of length 2: + + >>> len(result1) + 2 + >>> result1[:] + (1, 2) + + The values assigned when the instance was created are available as + attributes: + + >>> result1.y + 2 + >>> result1.beta + 0.5 + """ + if len(field_names) == 0: + raise ValueError('field_names must contain at least one name') + + if extra_field_names is None: + extra_field_names = [] + _validate_names(typename, field_names, extra_field_names) + + typename = _sys.intern(str(typename)) + field_names = tuple(map(_sys.intern, field_names)) + extra_field_names = tuple(map(_sys.intern, extra_field_names)) + + all_names = field_names + extra_field_names + arg_list = ', '.join(field_names) + full_list = ', '.join(all_names) + repr_fmt = ''.join(('(', + ', '.join(f'{name}=%({name})r' for name in all_names), + ')')) + tuple_new = tuple.__new__ + _dict, _tuple, _zip = dict, tuple, zip + + # Create all the named tuple methods to be added to the class namespace + + s = f"""\ +def __new__(_cls, {arg_list}, **extra_fields): + return _tuple_new(_cls, ({arg_list},)) + +def __init__(self, {arg_list}, **extra_fields): + for key in self._extra_fields: + if key not in extra_fields: + raise TypeError("missing keyword argument '%s'" % (key,)) + for key, val in extra_fields.items(): + if key not in self._extra_fields: + raise TypeError("unexpected keyword argument '%s'" % (key,)) + self.__dict__[key] = val + +def __setattr__(self, key, val): + if key in {repr(field_names)}: + raise AttributeError("can't set attribute %r of class %r" + % (key, self.__class__.__name__)) + else: + self.__dict__[key] = val +""" + del arg_list + namespace = {'_tuple_new': tuple_new, + '__builtins__': dict(TypeError=TypeError, + AttributeError=AttributeError), + '__name__': f'namedtuple_{typename}'} + exec(s, namespace) + __new__ = namespace['__new__'] + __new__.__doc__ = f'Create new instance of {typename}({full_list})' + __init__ = namespace['__init__'] + __init__.__doc__ = f'Instantiate instance of {typename}({full_list})' + __setattr__ = namespace['__setattr__'] + + def __repr__(self): + 'Return a nicely formatted representation string' + return self.__class__.__name__ + repr_fmt % self._asdict() + + def _asdict(self): + 'Return a new dict which maps field names to their values.' + out = _dict(_zip(self._fields, self)) + out.update(self.__dict__) + return out + + def __getnewargs_ex__(self): + 'Return self as a plain tuple. Used by copy and pickle.' + return _tuple(self), self.__dict__ + + # Modify function metadata to help with introspection and debugging + for method in (__new__, __repr__, _asdict, __getnewargs_ex__): + method.__qualname__ = f'{typename}.{method.__name__}' + + # Build-up the class namespace dictionary + # and use type() to build the result class + class_namespace = { + '__doc__': f'{typename}({full_list})', + '_fields': field_names, + '__new__': __new__, + '__init__': __init__, + '__repr__': __repr__, + '__setattr__': __setattr__, + '_asdict': _asdict, + '_extra_fields': extra_field_names, + '__getnewargs_ex__': __getnewargs_ex__, + # _field_defaults and _replace are added to get Polars to detect + # a bunch object as a namedtuple. See gh-22450 + '_field_defaults': {}, + '_replace': None, + } + for index, name in enumerate(field_names): + + def _get(self, index=index): + return self[index] + class_namespace[name] = property(_get) + for name in extra_field_names: + + def _get(self, name=name): + return self.__dict__[name] + class_namespace[name] = property(_get) + + result = type(typename, (tuple,), class_namespace) + + # For pickling to work, the __module__ variable needs to be set to the + # frame where the named tuple is created. Bypass this step in environments + # where sys._getframe is not defined (Jython for example) or sys._getframe + # is not defined for arguments greater than 0 (IronPython), or where the + # user has specified a particular module. + if module is None: + try: + module = _sys._getframe(1).f_globals.get('__name__', '__main__') + except (AttributeError, ValueError): + pass + if module is not None: + result.__module__ = module + __new__.__module__ = module + + return result diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_ccallback.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_ccallback.py new file mode 100644 index 0000000000000000000000000000000000000000..1980d06f5489e6633fb611c35bfb56903bd63e7f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_ccallback.py @@ -0,0 +1,251 @@ +from . import _ccallback_c + +import ctypes + +PyCFuncPtr = ctypes.CFUNCTYPE(ctypes.c_void_p).__bases__[0] + +ffi = None + +class CData: + pass + +def _import_cffi(): + global ffi, CData + + if ffi is not None: + return + + try: + import cffi + ffi = cffi.FFI() + CData = ffi.CData + except ImportError: + ffi = False + + +class LowLevelCallable(tuple): + """ + Low-level callback function. + + Some functions in SciPy take as arguments callback functions, which + can either be python callables or low-level compiled functions. Using + compiled callback functions can improve performance somewhat by + avoiding wrapping data in Python objects. + + Such low-level functions in SciPy are wrapped in `LowLevelCallable` + objects, which can be constructed from function pointers obtained from + ctypes, cffi, Cython, or contained in Python `PyCapsule` objects. + + .. seealso:: + + Functions accepting low-level callables: + + `scipy.integrate.quad`, `scipy.ndimage.generic_filter`, + `scipy.ndimage.generic_filter1d`, `scipy.ndimage.geometric_transform` + + Usage examples: + + :ref:`ndimage-ccallbacks`, :ref:`quad-callbacks` + + Parameters + ---------- + function : {PyCapsule, ctypes function pointer, cffi function pointer} + Low-level callback function. + user_data : {PyCapsule, ctypes void pointer, cffi void pointer} + User data to pass on to the callback function. + signature : str, optional + Signature of the function. If omitted, determined from *function*, + if possible. + + Attributes + ---------- + function + Callback function given. + user_data + User data given. + signature + Signature of the function. + + Methods + ------- + from_cython + Class method for constructing callables from Cython C-exported + functions. + + Notes + ----- + The argument ``function`` can be one of: + + - PyCapsule, whose name contains the C function signature + - ctypes function pointer + - cffi function pointer + + The signature of the low-level callback must match one of those expected + by the routine it is passed to. + + If constructing low-level functions from a PyCapsule, the name of the + capsule must be the corresponding signature, in the format:: + + return_type (arg1_type, arg2_type, ...) + + For example:: + + "void (double)" + "double (double, int *, void *)" + + The context of a PyCapsule passed in as ``function`` is used as ``user_data``, + if an explicit value for ``user_data`` was not given. + + """ + + # Make the class immutable + __slots__ = () + + def __new__(cls, function, user_data=None, signature=None): + # We need to hold a reference to the function & user data, + # to prevent them going out of scope + item = cls._parse_callback(function, user_data, signature) + return tuple.__new__(cls, (item, function, user_data)) + + def __repr__(self): + return f"LowLevelCallable({self.function!r}, {self.user_data!r})" + + @property + def function(self): + return tuple.__getitem__(self, 1) + + @property + def user_data(self): + return tuple.__getitem__(self, 2) + + @property + def signature(self): + return _ccallback_c.get_capsule_signature(tuple.__getitem__(self, 0)) + + def __getitem__(self, idx): + raise ValueError() + + @classmethod + def from_cython(cls, module, name, user_data=None, signature=None): + """ + Create a low-level callback function from an exported Cython function. + + Parameters + ---------- + module : module + Cython module where the exported function resides + name : str + Name of the exported function + user_data : {PyCapsule, ctypes void pointer, cffi void pointer}, optional + User data to pass on to the callback function. + signature : str, optional + Signature of the function. If omitted, determined from *function*. + + """ + try: + function = module.__pyx_capi__[name] + except AttributeError as e: + message = "Given module is not a Cython module with __pyx_capi__ attribute" + raise ValueError(message) from e + except KeyError as e: + message = f"No function {name!r} found in __pyx_capi__ of the module" + raise ValueError(message) from e + return cls(function, user_data, signature) + + @classmethod + def _parse_callback(cls, obj, user_data=None, signature=None): + _import_cffi() + + if isinstance(obj, LowLevelCallable): + func = tuple.__getitem__(obj, 0) + elif isinstance(obj, PyCFuncPtr): + func, signature = _get_ctypes_func(obj, signature) + elif isinstance(obj, CData): + func, signature = _get_cffi_func(obj, signature) + elif _ccallback_c.check_capsule(obj): + func = obj + else: + raise ValueError("Given input is not a callable or a " + "low-level callable (pycapsule/ctypes/cffi)") + + if isinstance(user_data, ctypes.c_void_p): + context = _get_ctypes_data(user_data) + elif isinstance(user_data, CData): + context = _get_cffi_data(user_data) + elif user_data is None: + context = 0 + elif _ccallback_c.check_capsule(user_data): + context = user_data + else: + raise ValueError("Given user data is not a valid " + "low-level void* pointer (pycapsule/ctypes/cffi)") + + return _ccallback_c.get_raw_capsule(func, signature, context) + + +# +# ctypes helpers +# + +def _get_ctypes_func(func, signature=None): + # Get function pointer + func_ptr = ctypes.cast(func, ctypes.c_void_p).value + + # Construct function signature + if signature is None: + signature = _typename_from_ctypes(func.restype) + " (" + for j, arg in enumerate(func.argtypes): + if j == 0: + signature += _typename_from_ctypes(arg) + else: + signature += ", " + _typename_from_ctypes(arg) + signature += ")" + + return func_ptr, signature + + +def _typename_from_ctypes(item): + if item is None: + return "void" + elif item is ctypes.c_void_p: + return "void *" + + name = item.__name__ + + pointer_level = 0 + while name.startswith("LP_"): + pointer_level += 1 + name = name[3:] + + if name.startswith('c_'): + name = name[2:] + + if pointer_level > 0: + name += " " + "*"*pointer_level + + return name + + +def _get_ctypes_data(data): + # Get voidp pointer + return ctypes.cast(data, ctypes.c_void_p).value + + +# +# CFFI helpers +# + +def _get_cffi_func(func, signature=None): + # Get function pointer + func_ptr = ffi.cast('uintptr_t', func) + + # Get signature + if signature is None: + signature = ffi.getctype(ffi.typeof(func)).replace('(*)', ' ') + + return func_ptr, signature + + +def _get_cffi_data(data): + # Get pointer + return ffi.cast('uintptr_t', data) diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_ccallback_c.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_ccallback_c.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..ae278e3f7e9f3a40a9f9fa20b9c6b7ebcf8a6da3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_ccallback_c.cpython-312-x86_64-linux-gnu.so differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_disjoint_set.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_disjoint_set.py new file mode 100644 index 0000000000000000000000000000000000000000..683c5c8e518705e710212dafc01363f92a2f947d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_disjoint_set.py @@ -0,0 +1,254 @@ +""" +Disjoint set data structure +""" + + +class DisjointSet: + """ Disjoint set data structure for incremental connectivity queries. + + .. versionadded:: 1.6.0 + + Attributes + ---------- + n_subsets : int + The number of subsets. + + Methods + ------- + add + merge + connected + subset + subset_size + subsets + __getitem__ + + Notes + ----- + This class implements the disjoint set [1]_, also known as the *union-find* + or *merge-find* data structure. The *find* operation (implemented in + `__getitem__`) implements the *path halving* variant. The *merge* method + implements the *merge by size* variant. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Disjoint-set_data_structure + + Examples + -------- + >>> from scipy.cluster.hierarchy import DisjointSet + + Initialize a disjoint set: + + >>> disjoint_set = DisjointSet([1, 2, 3, 'a', 'b']) + + Merge some subsets: + + >>> disjoint_set.merge(1, 2) + True + >>> disjoint_set.merge(3, 'a') + True + >>> disjoint_set.merge('a', 'b') + True + >>> disjoint_set.merge('b', 'b') + False + + Find root elements: + + >>> disjoint_set[2] + 1 + >>> disjoint_set['b'] + 3 + + Test connectivity: + + >>> disjoint_set.connected(1, 2) + True + >>> disjoint_set.connected(1, 'b') + False + + List elements in disjoint set: + + >>> list(disjoint_set) + [1, 2, 3, 'a', 'b'] + + Get the subset containing 'a': + + >>> disjoint_set.subset('a') + {'a', 3, 'b'} + + Get the size of the subset containing 'a' (without actually instantiating + the subset): + + >>> disjoint_set.subset_size('a') + 3 + + Get all subsets in the disjoint set: + + >>> disjoint_set.subsets() + [{1, 2}, {'a', 3, 'b'}] + """ + def __init__(self, elements=None): + self.n_subsets = 0 + self._sizes = {} + self._parents = {} + # _nbrs is a circular linked list which links connected elements. + self._nbrs = {} + # _indices tracks the element insertion order in `__iter__`. + self._indices = {} + if elements is not None: + for x in elements: + self.add(x) + + def __iter__(self): + """Returns an iterator of the elements in the disjoint set. + + Elements are ordered by insertion order. + """ + return iter(self._indices) + + def __len__(self): + return len(self._indices) + + def __contains__(self, x): + return x in self._indices + + def __getitem__(self, x): + """Find the root element of `x`. + + Parameters + ---------- + x : hashable object + Input element. + + Returns + ------- + root : hashable object + Root element of `x`. + """ + if x not in self._indices: + raise KeyError(x) + + # find by "path halving" + parents = self._parents + while self._indices[x] != self._indices[parents[x]]: + parents[x] = parents[parents[x]] + x = parents[x] + return x + + def add(self, x): + """Add element `x` to disjoint set + """ + if x in self._indices: + return + + self._sizes[x] = 1 + self._parents[x] = x + self._nbrs[x] = x + self._indices[x] = len(self._indices) + self.n_subsets += 1 + + def merge(self, x, y): + """Merge the subsets of `x` and `y`. + + The smaller subset (the child) is merged into the larger subset (the + parent). If the subsets are of equal size, the root element which was + first inserted into the disjoint set is selected as the parent. + + Parameters + ---------- + x, y : hashable object + Elements to merge. + + Returns + ------- + merged : bool + True if `x` and `y` were in disjoint sets, False otherwise. + """ + xr = self[x] + yr = self[y] + if self._indices[xr] == self._indices[yr]: + return False + + sizes = self._sizes + if (sizes[xr], self._indices[yr]) < (sizes[yr], self._indices[xr]): + xr, yr = yr, xr + self._parents[yr] = xr + self._sizes[xr] += self._sizes[yr] + self._nbrs[xr], self._nbrs[yr] = self._nbrs[yr], self._nbrs[xr] + self.n_subsets -= 1 + return True + + def connected(self, x, y): + """Test whether `x` and `y` are in the same subset. + + Parameters + ---------- + x, y : hashable object + Elements to test. + + Returns + ------- + result : bool + True if `x` and `y` are in the same set, False otherwise. + """ + return self._indices[self[x]] == self._indices[self[y]] + + def subset(self, x): + """Get the subset containing `x`. + + Parameters + ---------- + x : hashable object + Input element. + + Returns + ------- + result : set + Subset containing `x`. + """ + if x not in self._indices: + raise KeyError(x) + + result = [x] + nxt = self._nbrs[x] + while self._indices[nxt] != self._indices[x]: + result.append(nxt) + nxt = self._nbrs[nxt] + return set(result) + + def subset_size(self, x): + """Get the size of the subset containing `x`. + + Note that this method is faster than ``len(self.subset(x))`` because + the size is directly read off an internal field, without the need to + instantiate the full subset. + + Parameters + ---------- + x : hashable object + Input element. + + Returns + ------- + result : int + Size of the subset containing `x`. + """ + return self._sizes[self[x]] + + def subsets(self): + """Get all the subsets in the disjoint set. + + Returns + ------- + result : list + Subsets in the disjoint set. + """ + result = [] + visited = set() + for x in self: + if x not in visited: + xset = self.subset(x) + visited.update(xset) + result.append(xset) + return result diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_docscrape.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_docscrape.py new file mode 100644 index 0000000000000000000000000000000000000000..c74d2c20001f102c86f88c7bfb1afe731de60668 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_docscrape.py @@ -0,0 +1,761 @@ +# copied from numpydoc/docscrape.py, commit 97a6026508e0dd5382865672e9563a72cc113bd2 +"""Extract reference documentation from the NumPy source tree.""" + +import copy +import inspect +import pydoc +import re +import sys +import textwrap +from collections import namedtuple +from collections.abc import Callable, Mapping +from functools import cached_property +from warnings import warn + + +def strip_blank_lines(l): + "Remove leading and trailing blank lines from a list of lines" + while l and not l[0].strip(): + del l[0] + while l and not l[-1].strip(): + del l[-1] + return l + + +class Reader: + """A line-based string reader.""" + + def __init__(self, data): + """ + Parameters + ---------- + data : str + String with lines separated by '\\n'. + + """ + if isinstance(data, list): + self._str = data + else: + self._str = data.split("\n") # store string as list of lines + + self.reset() + + def __getitem__(self, n): + return self._str[n] + + def reset(self): + self._l = 0 # current line nr + + def read(self): + if not self.eof(): + out = self[self._l] + self._l += 1 + return out + else: + return "" + + def seek_next_non_empty_line(self): + for l in self[self._l :]: + if l.strip(): + break + else: + self._l += 1 + + def eof(self): + return self._l >= len(self._str) + + def read_to_condition(self, condition_func): + start = self._l + for line in self[start:]: + if condition_func(line): + return self[start : self._l] + self._l += 1 + if self.eof(): + return self[start : self._l + 1] + return [] + + def read_to_next_empty_line(self): + self.seek_next_non_empty_line() + + def is_empty(line): + return not line.strip() + + return self.read_to_condition(is_empty) + + def read_to_next_unindented_line(self): + def is_unindented(line): + return line.strip() and (len(line.lstrip()) == len(line)) + + return self.read_to_condition(is_unindented) + + def peek(self, n=0): + if self._l + n < len(self._str): + return self[self._l + n] + else: + return "" + + def is_empty(self): + return not "".join(self._str).strip() + + +class ParseError(Exception): + def __str__(self): + message = self.args[0] + if hasattr(self, "docstring"): + message = f"{message} in {self.docstring!r}" + return message + + +Parameter = namedtuple("Parameter", ["name", "type", "desc"]) + + +class NumpyDocString(Mapping): + """Parses a numpydoc string to an abstract representation + + Instances define a mapping from section title to structured data. + + """ + + sections = { + "Signature": "", + "Summary": [""], + "Extended Summary": [], + "Parameters": [], + "Attributes": [], + "Methods": [], + "Returns": [], + "Yields": [], + "Receives": [], + "Other Parameters": [], + "Raises": [], + "Warns": [], + "Warnings": [], + "See Also": [], + "Notes": [], + "References": "", + "Examples": "", + "index": {}, + } + + def __init__(self, docstring, config=None): + orig_docstring = docstring + docstring = textwrap.dedent(docstring).split("\n") + + self._doc = Reader(docstring) + self._parsed_data = copy.deepcopy(self.sections) + + try: + self._parse() + except ParseError as e: + e.docstring = orig_docstring + raise + + def __getitem__(self, key): + return self._parsed_data[key] + + def __setitem__(self, key, val): + if key not in self._parsed_data: + self._error_location(f"Unknown section {key}", error=False) + else: + self._parsed_data[key] = val + + def __iter__(self): + return iter(self._parsed_data) + + def __len__(self): + return len(self._parsed_data) + + def _is_at_section(self): + self._doc.seek_next_non_empty_line() + + if self._doc.eof(): + return False + + l1 = self._doc.peek().strip() # e.g. Parameters + + if l1.startswith(".. index::"): + return True + + l2 = self._doc.peek(1).strip() # ---------- or ========== + if len(l2) >= 3 and (set(l2) in ({"-"}, {"="})) and len(l2) != len(l1): + snip = "\n".join(self._doc._str[:2]) + "..." + self._error_location( + f"potentially wrong underline length... \n{l1} \n{l2} in \n{snip}", + error=False, + ) + return l2.startswith("-" * len(l1)) or l2.startswith("=" * len(l1)) + + def _strip(self, doc): + i = 0 + j = 0 + for i, line in enumerate(doc): + if line.strip(): + break + + for j, line in enumerate(doc[::-1]): + if line.strip(): + break + + return doc[i : len(doc) - j] + + def _read_to_next_section(self): + section = self._doc.read_to_next_empty_line() + + while not self._is_at_section() and not self._doc.eof(): + if not self._doc.peek(-1).strip(): # previous line was empty + section += [""] + + section += self._doc.read_to_next_empty_line() + + return section + + def _read_sections(self): + while not self._doc.eof(): + data = self._read_to_next_section() + name = data[0].strip() + + if name.startswith(".."): # index section + yield name, data[1:] + elif len(data) < 2: + yield StopIteration + else: + yield name, self._strip(data[2:]) + + def _parse_param_list(self, content, single_element_is_type=False): + content = dedent_lines(content) + r = Reader(content) + params = [] + while not r.eof(): + header = r.read().strip() + if " : " in header: + arg_name, arg_type = header.split(" : ", maxsplit=1) + else: + # NOTE: param line with single element should never have a + # a " :" before the description line, so this should probably + # warn. + if header.endswith(" :"): + header = header[:-2] + if single_element_is_type: + arg_name, arg_type = "", header + else: + arg_name, arg_type = header, "" + + desc = r.read_to_next_unindented_line() + desc = dedent_lines(desc) + desc = strip_blank_lines(desc) + + params.append(Parameter(arg_name, arg_type, desc)) + + return params + + # See also supports the following formats. + # + # + # SPACE* COLON SPACE+ SPACE* + # ( COMMA SPACE+ )+ (COMMA | PERIOD)? SPACE* + # ( COMMA SPACE+ )* SPACE* COLON SPACE+ SPACE* + + # is one of + # + # COLON COLON BACKTICK BACKTICK + # where + # is a legal function name, and + # is any nonempty sequence of word characters. + # Examples: func_f1 :meth:`func_h1` :obj:`~baz.obj_r` :class:`class_j` + # is a string describing the function. + + _role = r":(?P(py:)?\w+):" + _funcbacktick = r"`(?P(?:~\w+\.)?[a-zA-Z0-9_\.-]+)`" + _funcplain = r"(?P[a-zA-Z0-9_\.-]+)" + _funcname = r"(" + _role + _funcbacktick + r"|" + _funcplain + r")" + _funcnamenext = _funcname.replace("role", "rolenext") + _funcnamenext = _funcnamenext.replace("name", "namenext") + _description = r"(?P\s*:(\s+(?P\S+.*))?)?\s*$" + _func_rgx = re.compile(r"^\s*" + _funcname + r"\s*") + _line_rgx = re.compile( + r"^\s*" + + r"(?P" + + _funcname # group for all function names + + r"(?P([,]\s+" + + _funcnamenext + + r")*)" + + r")" + + r"(?P[,\.])?" # end of "allfuncs" + + _description # Some function lists have a trailing comma (or period) '\s*' + ) + + # Empty elements are replaced with '..' + empty_description = ".." + + def _parse_see_also(self, content): + """ + func_name : Descriptive text + continued text + another_func_name : Descriptive text + func_name1, func_name2, :meth:`func_name`, func_name3 + + """ + + content = dedent_lines(content) + + items = [] + + def parse_item_name(text): + """Match ':role:`name`' or 'name'.""" + m = self._func_rgx.match(text) + if not m: + self._error_location(f"Error parsing See Also entry {line!r}") + role = m.group("role") + name = m.group("name") if role else m.group("name2") + return name, role, m.end() + + rest = [] + for line in content: + if not line.strip(): + continue + + line_match = self._line_rgx.match(line) + description = None + if line_match: + description = line_match.group("desc") + if line_match.group("trailing") and description: + self._error_location( + "Unexpected comma or period after function list at index %d of " + 'line "%s"' % (line_match.end("trailing"), line), + error=False, + ) + if not description and line.startswith(" "): + rest.append(line.strip()) + elif line_match: + funcs = [] + text = line_match.group("allfuncs") + while True: + if not text.strip(): + break + name, role, match_end = parse_item_name(text) + funcs.append((name, role)) + text = text[match_end:].strip() + if text and text[0] == ",": + text = text[1:].strip() + rest = list(filter(None, [description])) + items.append((funcs, rest)) + else: + self._error_location(f"Error parsing See Also entry {line!r}") + return items + + def _parse_index(self, section, content): + """ + .. index:: default + :refguide: something, else, and more + + """ + + def strip_each_in(lst): + return [s.strip() for s in lst] + + out = {} + section = section.split("::") + if len(section) > 1: + out["default"] = strip_each_in(section[1].split(","))[0] + for line in content: + line = line.split(":") + if len(line) > 2: + out[line[1]] = strip_each_in(line[2].split(",")) + return out + + def _parse_summary(self): + """Grab signature (if given) and summary""" + if self._is_at_section(): + return + + # If several signatures present, take the last one + while True: + summary = self._doc.read_to_next_empty_line() + summary_str = " ".join([s.strip() for s in summary]).strip() + compiled = re.compile(r"^([\w., ]+=)?\s*[\w\.]+\(.*\)$") + if compiled.match(summary_str): + self["Signature"] = summary_str + if not self._is_at_section(): + continue + break + + if summary is not None: + self["Summary"] = summary + + if not self._is_at_section(): + self["Extended Summary"] = self._read_to_next_section() + + def _parse(self): + self._doc.reset() + self._parse_summary() + + sections = list(self._read_sections()) + section_names = {section for section, content in sections} + + has_yields = "Yields" in section_names + # We could do more tests, but we are not. Arbitrarily. + if not has_yields and "Receives" in section_names: + msg = "Docstring contains a Receives section but not Yields." + raise ValueError(msg) + + for section, content in sections: + if not section.startswith(".."): + section = (s.capitalize() for s in section.split(" ")) + section = " ".join(section) + if self.get(section): + self._error_location( + "The section %s appears twice in %s" + % (section, "\n".join(self._doc._str)) + ) + + if section in ("Parameters", "Other Parameters", "Attributes", "Methods"): + self[section] = self._parse_param_list(content) + elif section in ("Returns", "Yields", "Raises", "Warns", "Receives"): + self[section] = self._parse_param_list( + content, single_element_is_type=True + ) + elif section.startswith(".. index::"): + self["index"] = self._parse_index(section, content) + elif section == "See Also": + self["See Also"] = self._parse_see_also(content) + else: + self[section] = content + + @property + def _obj(self): + if hasattr(self, "_cls"): + return self._cls + elif hasattr(self, "_f"): + return self._f + return None + + def _error_location(self, msg, error=True): + if self._obj is not None: + # we know where the docs came from: + try: + filename = inspect.getsourcefile(self._obj) + except TypeError: + filename = None + # Make UserWarning more descriptive via object introspection. + # Skip if introspection fails + name = getattr(self._obj, "__name__", None) + if name is None: + name = getattr(getattr(self._obj, "__class__", None), "__name__", None) + if name is not None: + msg += f" in the docstring of {name}" + msg += f" in {filename}." if filename else "" + if error: + raise ValueError(msg) + else: + warn(msg, stacklevel=3) + + # string conversion routines + + def _str_header(self, name, symbol="-"): + return [name, len(name) * symbol] + + def _str_indent(self, doc, indent=4): + return [" " * indent + line for line in doc] + + def _str_signature(self): + if self["Signature"]: + return [self["Signature"].replace("*", r"\*")] + [""] + return [""] + + def _str_summary(self): + if self["Summary"]: + return self["Summary"] + [""] + return [] + + def _str_extended_summary(self): + if self["Extended Summary"]: + return self["Extended Summary"] + [""] + return [] + + def _str_param_list(self, name): + out = [] + if self[name]: + out += self._str_header(name) + for param in self[name]: + parts = [] + if param.name: + parts.append(param.name) + if param.type: + parts.append(param.type) + out += [" : ".join(parts)] + if param.desc and "".join(param.desc).strip(): + out += self._str_indent(param.desc) + out += [""] + return out + + def _str_section(self, name): + out = [] + if self[name]: + out += self._str_header(name) + out += self[name] + out += [""] + return out + + def _str_see_also(self, func_role): + if not self["See Also"]: + return [] + out = [] + out += self._str_header("See Also") + out += [""] + last_had_desc = True + for funcs, desc in self["See Also"]: + assert isinstance(funcs, list) + links = [] + for func, role in funcs: + if role: + link = f":{role}:`{func}`" + elif func_role: + link = f":{func_role}:`{func}`" + else: + link = f"`{func}`_" + links.append(link) + link = ", ".join(links) + out += [link] + if desc: + out += self._str_indent([" ".join(desc)]) + last_had_desc = True + else: + last_had_desc = False + out += self._str_indent([self.empty_description]) + + if last_had_desc: + out += [""] + out += [""] + return out + + def _str_index(self): + idx = self["index"] + out = [] + output_index = False + default_index = idx.get("default", "") + if default_index: + output_index = True + out += [f".. index:: {default_index}"] + for section, references in idx.items(): + if section == "default": + continue + output_index = True + out += [f" :{section}: {', '.join(references)}"] + if output_index: + return out + return "" + + def __str__(self, func_role=""): + out = [] + out += self._str_signature() + out += self._str_summary() + out += self._str_extended_summary() + out += self._str_param_list("Parameters") + for param_list in ("Attributes", "Methods"): + out += self._str_param_list(param_list) + for param_list in ( + "Returns", + "Yields", + "Receives", + "Other Parameters", + "Raises", + "Warns", + ): + out += self._str_param_list(param_list) + out += self._str_section("Warnings") + out += self._str_see_also(func_role) + for s in ("Notes", "References", "Examples"): + out += self._str_section(s) + out += self._str_index() + return "\n".join(out) + + +def dedent_lines(lines): + """Deindent a list of lines maximally""" + return textwrap.dedent("\n".join(lines)).split("\n") + + +class FunctionDoc(NumpyDocString): + def __init__(self, func, role="func", doc=None, config=None): + self._f = func + self._role = role # e.g. "func" or "meth" + + if doc is None: + if func is None: + raise ValueError("No function or docstring given") + doc = inspect.getdoc(func) or "" + if config is None: + config = {} + NumpyDocString.__init__(self, doc, config) + + def get_func(self): + func_name = getattr(self._f, "__name__", self.__class__.__name__) + if inspect.isclass(self._f): + func = getattr(self._f, "__call__", self._f.__init__) + else: + func = self._f + return func, func_name + + def __str__(self): + out = "" + + func, func_name = self.get_func() + + roles = {"func": "function", "meth": "method"} + + if self._role: + if self._role not in roles: + print(f"Warning: invalid role {self._role}") + out += f".. {roles.get(self._role, '')}:: {func_name}\n \n\n" + + out += super().__str__(func_role=self._role) + return out + + +class ObjDoc(NumpyDocString): + def __init__(self, obj, doc=None, config=None): + self._f = obj + if config is None: + config = {} + NumpyDocString.__init__(self, doc, config=config) + + +class ClassDoc(NumpyDocString): + extra_public_methods = ["__call__"] + + def __init__(self, cls, doc=None, modulename="", func_doc=FunctionDoc, config=None): + if not inspect.isclass(cls) and cls is not None: + raise ValueError(f"Expected a class or None, but got {cls!r}") + self._cls = cls + + if "sphinx" in sys.modules: + from sphinx.ext.autodoc import ALL + else: + ALL = object() + + if config is None: + config = {} + self.show_inherited_members = config.get("show_inherited_class_members", True) + + if modulename and not modulename.endswith("."): + modulename += "." + self._mod = modulename + + if doc is None: + if cls is None: + raise ValueError("No class or documentation string given") + doc = pydoc.getdoc(cls) + + NumpyDocString.__init__(self, doc) + + _members = config.get("members", []) + if _members is ALL: + _members = None + _exclude = config.get("exclude-members", []) + + if config.get("show_class_members", True) and _exclude is not ALL: + + def splitlines_x(s): + if not s: + return [] + else: + return s.splitlines() + + for field, items in [ + ("Methods", self.methods), + ("Attributes", self.properties), + ]: + if not self[field]: + doc_list = [] + for name in sorted(items): + if name in _exclude or (_members and name not in _members): + continue + try: + doc_item = pydoc.getdoc(getattr(self._cls, name)) + doc_list.append(Parameter(name, "", splitlines_x(doc_item))) + except AttributeError: + pass # method doesn't exist + self[field] = doc_list + + @property + def methods(self): + if self._cls is None: + return [] + return [ + name + for name, func in inspect.getmembers(self._cls) + if ( + (not name.startswith("_") or name in self.extra_public_methods) + and isinstance(func, Callable) + and self._is_show_member(name) + ) + ] + + @property + def properties(self): + if self._cls is None: + return [] + return [ + name + for name, func in inspect.getmembers(self._cls) + if ( + not name.startswith("_") + and not self._should_skip_member(name, self._cls) + and ( + func is None + or isinstance(func, property | cached_property) + or inspect.isdatadescriptor(func) + ) + and self._is_show_member(name) + ) + ] + + @staticmethod + def _should_skip_member(name, klass): + return ( + # Namedtuples should skip everything in their ._fields as the + # docstrings for each of the members is: "Alias for field number X" + issubclass(klass, tuple) + and hasattr(klass, "_asdict") + and hasattr(klass, "_fields") + and name in klass._fields + ) + + def _is_show_member(self, name): + return ( + # show all class members + self.show_inherited_members + # or class member is not inherited + or name in self._cls.__dict__ + ) + + +def get_doc_object( + obj, + what=None, + doc=None, + config=None, + class_doc=ClassDoc, + func_doc=FunctionDoc, + obj_doc=ObjDoc, +): + if what is None: + if inspect.isclass(obj): + what = "class" + elif inspect.ismodule(obj): + what = "module" + elif isinstance(obj, Callable): + what = "function" + else: + what = "object" + if config is None: + config = {} + + if what == "class": + return class_doc(obj, func_doc=func_doc, doc=doc, config=config) + elif what in ("function", "method"): + return func_doc(obj, doc=doc, config=config) + else: + if doc is None: + doc = pydoc.getdoc(obj) + return obj_doc(obj, doc, config=config) \ No newline at end of file diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_elementwise_iterative_method.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_elementwise_iterative_method.py new file mode 100644 index 0000000000000000000000000000000000000000..14c5c1949ddf407e1aecce0a51a1a834647ac523 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_elementwise_iterative_method.py @@ -0,0 +1,346 @@ +# `_elementwise_iterative_method.py` includes tools for writing functions that +# - are vectorized to work elementwise on arrays, +# - implement non-trivial, iterative algorithms with a callback interface, and +# - return rich objects with iteration count, termination status, etc. +# +# Examples include: +# `scipy.optimize._chandrupatla._chandrupatla for scalar rootfinding, +# `scipy.optimize._chandrupatla._chandrupatla_minimize for scalar minimization, +# `scipy.optimize._differentiate._differentiate for numerical differentiation, +# `scipy.optimize._bracket._bracket_root for finding rootfinding brackets, +# `scipy.optimize._bracket._bracket_minimize for finding minimization brackets, +# `scipy.integrate._tanhsinh._tanhsinh` for numerical quadrature, +# `scipy.differentiate.derivative` for finite difference based differentiation. + +import math +import numpy as np +from ._util import _RichResult, _call_callback_maybe_halt +from ._array_api import array_namespace, xp_size, xp_result_type +import scipy._lib.array_api_extra as xpx + +_ESIGNERR = -1 +_ECONVERR = -2 +_EVALUEERR = -3 +_ECALLBACK = -4 +_EINPUTERR = -5 +_ECONVERGED = 0 +_EINPROGRESS = 1 + +def _initialize(func, xs, args, complex_ok=False, preserve_shape=None, xp=None): + """Initialize abscissa, function, and args arrays for elementwise function + + Parameters + ---------- + func : callable + An elementwise function with signature + + func(x: ndarray, *args) -> ndarray + + where each element of ``x`` is a finite real and ``args`` is a tuple, + which may contain an arbitrary number of arrays that are broadcastable + with ``x``. + xs : tuple of arrays + Finite real abscissa arrays. Must be broadcastable. + args : tuple, optional + Additional positional arguments to be passed to `func`. + preserve_shape : bool, default:False + When ``preserve_shape=False`` (default), `func` may be passed + arguments of any shape; `_scalar_optimization_loop` is permitted + to reshape and compress arguments at will. When + ``preserve_shape=False``, arguments passed to `func` must have shape + `shape` or ``shape + (n,)``, where ``n`` is any integer. + xp : namespace + Namespace of array arguments in `xs`. + + Returns + ------- + xs, fs, args : tuple of arrays + Broadcasted, writeable, 1D abscissa and function value arrays (or + NumPy floats, if appropriate). The dtypes of the `xs` and `fs` are + `xfat`; the dtype of the `args` are unchanged. + shape : tuple of ints + Original shape of broadcasted arrays. + xfat : NumPy dtype + Result dtype of abscissae, function values, and args determined using + `np.result_type`, except integer types are promoted to `np.float64`. + + Raises + ------ + ValueError + If the result dtype is not that of a real scalar + + Notes + ----- + Useful for initializing the input of SciPy functions that accept + an elementwise callable, abscissae, and arguments; e.g. + `scipy.optimize._chandrupatla`. + """ + nx = len(xs) + xp = array_namespace(*xs) if xp is None else xp + + # Try to preserve `dtype`, but we need to ensure that the arguments are at + # least floats before passing them into the function; integers can overflow + # and cause failure. + # There might be benefit to combining the `xs` into a single array and + # calling `func` once on the combined array. For now, keep them separate. + xat = xp_result_type(*xs, force_floating=True, xp=xp) + xas = xp.broadcast_arrays(*xs, *args) # broadcast and rename + xs, args = xas[:nx], xas[nx:] + xs = [xp.asarray(x, dtype=xat) for x in xs] # use copy=False when implemented + fs = [xp.asarray(func(x, *args)) for x in xs] + shape = xs[0].shape + fshape = fs[0].shape + + if preserve_shape: + # bind original shape/func now to avoid late-binding gotcha + def func(x, *args, shape=shape, func=func, **kwargs): + i = (0,)*(len(fshape) - len(shape)) + return func(x[i], *args, **kwargs) + shape = np.broadcast_shapes(fshape, shape) # just shapes; use of NumPy OK + xs = [xp.broadcast_to(x, shape) for x in xs] + args = [xp.broadcast_to(arg, shape) for arg in args] + + message = ("The shape of the array returned by `func` must be the same as " + "the broadcasted shape of `x` and all other `args`.") + if preserve_shape is not None: # only in tanhsinh for now + message = f"When `preserve_shape=False`, {message.lower()}" + shapes_equal = [f.shape == shape for f in fs] + if not all(shapes_equal): # use Python all to reduce overhead + raise ValueError(message) + + # These algorithms tend to mix the dtypes of the abscissae and function + # values, so figure out what the result will be and convert them all to + # that type from the outset. + xfat = xp.result_type(*([f.dtype for f in fs] + [xat])) + if not complex_ok and not xp.isdtype(xfat, "real floating"): + raise ValueError("Abscissae and function output must be real numbers.") + xs = [xp.asarray(x, dtype=xfat, copy=True) for x in xs] + fs = [xp.asarray(f, dtype=xfat, copy=True) for f in fs] + + # To ensure that we can do indexing, we'll work with at least 1d arrays, + # but remember the appropriate shape of the output. + xs = [xp.reshape(x, (-1,)) for x in xs] + fs = [xp.reshape(f, (-1,)) for f in fs] + args = [xp.reshape(xp.asarray(arg, copy=True), (-1,)) for arg in args] + return func, xs, fs, args, shape, xfat, xp + + +def _loop(work, callback, shape, maxiter, func, args, dtype, pre_func_eval, + post_func_eval, check_termination, post_termination_check, + customize_result, res_work_pairs, xp, preserve_shape=False): + """Main loop of a vectorized scalar optimization algorithm + + Parameters + ---------- + work : _RichResult + All variables that need to be retained between iterations. Must + contain attributes `nit`, `nfev`, and `success`. All arrays are + subject to being "compressed" if `preserve_shape is False`; nest + arrays that should not be compressed inside another object (e.g. + `dict` or `_RichResult`). + callback : callable + User-specified callback function + shape : tuple of ints + The shape of all output arrays + maxiter : + Maximum number of iterations of the algorithm + func : callable + The user-specified callable that is being optimized or solved + args : tuple + Additional positional arguments to be passed to `func`. + dtype : NumPy dtype + The common dtype of all abscissae and function values + pre_func_eval : callable + A function that accepts `work` and returns `x`, the active elements + of `x` at which `func` will be evaluated. May modify attributes + of `work` with any algorithmic steps that need to happen + at the beginning of an iteration, before `func` is evaluated, + post_func_eval : callable + A function that accepts `x`, `func(x)`, and `work`. May modify + attributes of `work` with any algorithmic steps that need to happen + in the middle of an iteration, after `func` is evaluated but before + the termination check. + check_termination : callable + A function that accepts `work` and returns `stop`, a boolean array + indicating which of the active elements have met a termination + condition. + post_termination_check : callable + A function that accepts `work`. May modify `work` with any algorithmic + steps that need to happen after the termination check and before the + end of the iteration. + customize_result : callable + A function that accepts `res` and `shape` and returns `shape`. May + modify `res` (in-place) according to preferences (e.g. rearrange + elements between attributes) and modify `shape` if needed. + res_work_pairs : list of (str, str) + Identifies correspondence between attributes of `res` and attributes + of `work`; i.e., attributes of active elements of `work` will be + copied to the appropriate indices of `res` when appropriate. The order + determines the order in which _RichResult attributes will be + pretty-printed. + preserve_shape : bool, default: False + Whether to compress the attributes of `work` (to avoid unnecessary + computation on elements that have already converged). + + Returns + ------- + res : _RichResult + The final result object + + Notes + ----- + Besides providing structure, this framework provides several important + services for a vectorized optimization algorithm. + + - It handles common tasks involving iteration count, function evaluation + count, a user-specified callback, and associated termination conditions. + - It compresses the attributes of `work` to eliminate unnecessary + computation on elements that have already converged. + + """ + if xp is None: + raise NotImplementedError("Must provide xp.") + + cb_terminate = False + + # Initialize the result object and active element index array + n_elements = math.prod(shape) + active = xp.arange(n_elements) # in-progress element indices + res_dict = {i: xp.zeros(n_elements, dtype=dtype) for i, j in res_work_pairs} + res_dict['success'] = xp.zeros(n_elements, dtype=xp.bool) + res_dict['status'] = xp.full(n_elements, xp.asarray(_EINPROGRESS), dtype=xp.int32) + res_dict['nit'] = xp.zeros(n_elements, dtype=xp.int32) + res_dict['nfev'] = xp.zeros(n_elements, dtype=xp.int32) + res = _RichResult(res_dict) + work.args = args + + active = _check_termination(work, res, res_work_pairs, active, + check_termination, preserve_shape, xp) + + if callback is not None: + temp = _prepare_result(work, res, res_work_pairs, active, shape, + customize_result, preserve_shape, xp) + if _call_callback_maybe_halt(callback, temp): + cb_terminate = True + + while work.nit < maxiter and xp_size(active) and not cb_terminate and n_elements: + x = pre_func_eval(work) + + if work.args and work.args[0].ndim != x.ndim: + # `x` always starts as 1D. If the SciPy function that uses + # _loop added dimensions to `x`, we need to + # add them to the elements of `args`. + args = [] + for arg in work.args: + n_new_dims = x.ndim - arg.ndim + new_shape = arg.shape + (1,)*n_new_dims + args.append(xp.reshape(arg, new_shape)) + work.args = args + + x_shape = x.shape + if preserve_shape: + x = xp.reshape(x, (shape + (-1,))) + f = func(x, *work.args) + f = xp.asarray(f, dtype=dtype) + if preserve_shape: + x = xp.reshape(x, x_shape) + f = xp.reshape(f, x_shape) + work.nfev += 1 if x.ndim == 1 else x.shape[-1] + + post_func_eval(x, f, work) + + work.nit += 1 + active = _check_termination(work, res, res_work_pairs, active, + check_termination, preserve_shape, xp) + + if callback is not None: + temp = _prepare_result(work, res, res_work_pairs, active, shape, + customize_result, preserve_shape, xp) + if _call_callback_maybe_halt(callback, temp): + cb_terminate = True + break + if xp_size(active) == 0: + break + + post_termination_check(work) + + work.status = xpx.at(work.status)[:].set(_ECALLBACK if cb_terminate else _ECONVERR) + return _prepare_result(work, res, res_work_pairs, active, shape, + customize_result, preserve_shape, xp) + + +def _check_termination(work, res, res_work_pairs, active, check_termination, + preserve_shape, xp): + # Checks termination conditions, updates elements of `res` with + # corresponding elements of `work`, and compresses `work`. + + stop = check_termination(work) + + if xp.any(stop): + # update the active elements of the result object with the active + # elements for which a termination condition has been met + _update_active(work, res, res_work_pairs, active, stop, preserve_shape, xp) + + if preserve_shape: + stop = stop[active] + + proceed = ~stop + active = active[proceed] + + if not preserve_shape: + # compress the arrays to avoid unnecessary computation + for key, val in work.items(): + # `continued_fraction` hacks `n`; improve if this becomes a problem + if key in {'args', 'n'}: + continue + work[key] = val[proceed] if getattr(val, 'ndim', 0) > 0 else val + work.args = [arg[proceed] for arg in work.args] + + return active + + +def _update_active(work, res, res_work_pairs, active, mask, preserve_shape, xp): + # Update `active` indices of the arrays in result object `res` with the + # contents of the scalars and arrays in `update_dict`. When provided, + # `mask` is a boolean array applied both to the arrays in `update_dict` + # that are to be used and to the arrays in `res` that are to be updated. + update_dict = {key1: work[key2] for key1, key2 in res_work_pairs} + update_dict['success'] = work.status == 0 + + if mask is not None: + if preserve_shape: + active_mask = xp.zeros_like(mask) + active_mask = xpx.at(active_mask)[active].set(True) + active_mask = active_mask & mask + for key, val in update_dict.items(): + val = val[active_mask] if getattr(val, 'ndim', 0) > 0 else val + res[key] = xpx.at(res[key])[active_mask].set(val) + else: + active_mask = active[mask] + for key, val in update_dict.items(): + val = val[mask] if getattr(val, 'ndim', 0) > 0 else val + res[key] = xpx.at(res[key])[active_mask].set(val) + else: + for key, val in update_dict.items(): + if preserve_shape and getattr(val, 'ndim', 0) > 0: + val = val[active] + res[key] = xpx.at(res[key])[active].set(val) + + +def _prepare_result(work, res, res_work_pairs, active, shape, customize_result, + preserve_shape, xp): + # Prepare the result object `res` by creating a copy, copying the latest + # data from work, running the provided result customization function, + # and reshaping the data to the original shapes. + res = res.copy() + _update_active(work, res, res_work_pairs, active, None, preserve_shape, xp) + + shape = customize_result(res, shape) + + for key, val in res.items(): + # this looks like it won't work for xp != np if val is not numeric + temp = xp.reshape(val, shape) + res[key] = temp[()] if temp.ndim == 0 else temp + + res['_order_keys'] = ['success'] + [i for i, j in res_work_pairs] + return _RichResult(**res) diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_fpumode.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_fpumode.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..3a443899bde3481ed6c1359eff4ef9696f6c8e4d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_fpumode.cpython-312-x86_64-linux-gnu.so differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_gcutils.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_gcutils.py new file mode 100644 index 0000000000000000000000000000000000000000..854ae36228614f3eb8849e9f95abf0dd387b5d35 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_gcutils.py @@ -0,0 +1,105 @@ +""" +Module for testing automatic garbage collection of objects + +.. autosummary:: + :toctree: generated/ + + set_gc_state - enable or disable garbage collection + gc_state - context manager for given state of garbage collector + assert_deallocated - context manager to check for circular references on object + +""" +import weakref +import gc + +from contextlib import contextmanager +from platform import python_implementation + +__all__ = ['set_gc_state', 'gc_state', 'assert_deallocated'] + + +IS_PYPY = python_implementation() == 'PyPy' + + +class ReferenceError(AssertionError): + pass + + +def set_gc_state(state): + """ Set status of garbage collector """ + if gc.isenabled() == state: + return + if state: + gc.enable() + else: + gc.disable() + + +@contextmanager +def gc_state(state): + """ Context manager to set state of garbage collector to `state` + + Parameters + ---------- + state : bool + True for gc enabled, False for disabled + + Examples + -------- + >>> with gc_state(False): + ... assert not gc.isenabled() + >>> with gc_state(True): + ... assert gc.isenabled() + """ + orig_state = gc.isenabled() + set_gc_state(state) + yield + set_gc_state(orig_state) + + +@contextmanager +def assert_deallocated(func, *args, **kwargs): + """Context manager to check that object is deallocated + + This is useful for checking that an object can be freed directly by + reference counting, without requiring gc to break reference cycles. + GC is disabled inside the context manager. + + This check is not available on PyPy. + + Parameters + ---------- + func : callable + Callable to create object to check + \\*args : sequence + positional arguments to `func` in order to create object to check + \\*\\*kwargs : dict + keyword arguments to `func` in order to create object to check + + Examples + -------- + >>> class C: pass + >>> with assert_deallocated(C) as c: + ... # do something + ... del c + + >>> class C: + ... def __init__(self): + ... self._circular = self # Make circular reference + >>> with assert_deallocated(C) as c: #doctest: +IGNORE_EXCEPTION_DETAIL + ... # do something + ... del c + Traceback (most recent call last): + ... + ReferenceError: Remaining reference(s) to object + """ + if IS_PYPY: + raise RuntimeError("assert_deallocated is unavailable on PyPy") + + with gc_state(False): + obj = func(*args, **kwargs) + ref = weakref.ref(obj) + yield obj + del obj + if ref() is not None: + raise ReferenceError("Remaining reference(s) to object") diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_pep440.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_pep440.py new file mode 100644 index 0000000000000000000000000000000000000000..d546e32a0349461a0aab76bfb4636ebf25227ca0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_pep440.py @@ -0,0 +1,487 @@ +"""Utility to compare pep440 compatible version strings. + +The LooseVersion and StrictVersion classes that distutils provides don't +work; they don't recognize anything like alpha/beta/rc/dev versions. +""" + +# Copyright (c) Donald Stufft and individual contributors. +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import collections +import itertools +import re + + +__all__ = [ + "parse", "Version", "LegacyVersion", "InvalidVersion", "VERSION_PATTERN", +] + + +# BEGIN packaging/_structures.py + + +class Infinity: + def __repr__(self): + return "Infinity" + + def __hash__(self): + return hash(repr(self)) + + def __lt__(self, other): + return False + + def __le__(self, other): + return False + + def __eq__(self, other): + return isinstance(other, self.__class__) + + def __ne__(self, other): + return not isinstance(other, self.__class__) + + def __gt__(self, other): + return True + + def __ge__(self, other): + return True + + def __neg__(self): + return NegativeInfinity + + +Infinity = Infinity() + + +class NegativeInfinity: + def __repr__(self): + return "-Infinity" + + def __hash__(self): + return hash(repr(self)) + + def __lt__(self, other): + return True + + def __le__(self, other): + return True + + def __eq__(self, other): + return isinstance(other, self.__class__) + + def __ne__(self, other): + return not isinstance(other, self.__class__) + + def __gt__(self, other): + return False + + def __ge__(self, other): + return False + + def __neg__(self): + return Infinity + + +# BEGIN packaging/version.py + + +NegativeInfinity = NegativeInfinity() + +_Version = collections.namedtuple( + "_Version", + ["epoch", "release", "dev", "pre", "post", "local"], +) + + +def parse(version): + """ + Parse the given version string and return either a :class:`Version` object + or a :class:`LegacyVersion` object depending on if the given version is + a valid PEP 440 version or a legacy version. + """ + try: + return Version(version) + except InvalidVersion: + return LegacyVersion(version) + + +class InvalidVersion(ValueError): + """ + An invalid version was found, users should refer to PEP 440. + """ + + +class _BaseVersion: + + def __hash__(self): + return hash(self._key) + + def __lt__(self, other): + return self._compare(other, lambda s, o: s < o) + + def __le__(self, other): + return self._compare(other, lambda s, o: s <= o) + + def __eq__(self, other): + return self._compare(other, lambda s, o: s == o) + + def __ge__(self, other): + return self._compare(other, lambda s, o: s >= o) + + def __gt__(self, other): + return self._compare(other, lambda s, o: s > o) + + def __ne__(self, other): + return self._compare(other, lambda s, o: s != o) + + def _compare(self, other, method): + if not isinstance(other, _BaseVersion): + return NotImplemented + + return method(self._key, other._key) + + +class LegacyVersion(_BaseVersion): + + def __init__(self, version): + self._version = str(version) + self._key = _legacy_cmpkey(self._version) + + def __str__(self): + return self._version + + def __repr__(self): + return f"" + + @property + def public(self): + return self._version + + @property + def base_version(self): + return self._version + + @property + def local(self): + return None + + @property + def is_prerelease(self): + return False + + @property + def is_postrelease(self): + return False + + +_legacy_version_component_re = re.compile( + r"(\d+ | [a-z]+ | \.| -)", re.VERBOSE, +) + +_legacy_version_replacement_map = { + "pre": "c", "preview": "c", "-": "final-", "rc": "c", "dev": "@", +} + + +def _parse_version_parts(s): + for part in _legacy_version_component_re.split(s): + part = _legacy_version_replacement_map.get(part, part) + + if not part or part == ".": + continue + + if part[:1] in "0123456789": + # pad for numeric comparison + yield part.zfill(8) + else: + yield "*" + part + + # ensure that alpha/beta/candidate are before final + yield "*final" + + +def _legacy_cmpkey(version): + # We hardcode an epoch of -1 here. A PEP 440 version can only have an epoch + # greater than or equal to 0. This will effectively put the LegacyVersion, + # which uses the defacto standard originally implemented by setuptools, + # as before all PEP 440 versions. + epoch = -1 + + # This scheme is taken from pkg_resources.parse_version setuptools prior to + # its adoption of the packaging library. + parts = [] + for part in _parse_version_parts(version.lower()): + if part.startswith("*"): + # remove "-" before a prerelease tag + if part < "*final": + while parts and parts[-1] == "*final-": + parts.pop() + + # remove trailing zeros from each series of numeric parts + while parts and parts[-1] == "00000000": + parts.pop() + + parts.append(part) + parts = tuple(parts) + + return epoch, parts + + +# Deliberately not anchored to the start and end of the string, to make it +# easier for 3rd party code to reuse +VERSION_PATTERN = r""" + v? + (?: + (?:(?P[0-9]+)!)? # epoch + (?P[0-9]+(?:\.[0-9]+)*) # release segment + (?P
                                          # pre-release
+            [-_\.]?
+            (?P(a|b|c|rc|alpha|beta|pre|preview))
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+        (?P                                         # post release
+            (?:-(?P[0-9]+))
+            |
+            (?:
+                [-_\.]?
+                (?Ppost|rev|r)
+                [-_\.]?
+                (?P[0-9]+)?
+            )
+        )?
+        (?P                                          # dev release
+            [-_\.]?
+            (?Pdev)
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+    )
+    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
+"""
+
+
+class Version(_BaseVersion):
+
+    _regex = re.compile(
+        r"^\s*" + VERSION_PATTERN + r"\s*$",
+        re.VERBOSE | re.IGNORECASE,
+    )
+
+    def __init__(self, version):
+        # Validate the version and parse it into pieces
+        match = self._regex.search(version)
+        if not match:
+            raise InvalidVersion(f"Invalid version: '{version}'")
+
+        # Store the parsed out pieces of the version
+        self._version = _Version(
+            epoch=int(match.group("epoch")) if match.group("epoch") else 0,
+            release=tuple(int(i) for i in match.group("release").split(".")),
+            pre=_parse_letter_version(
+                match.group("pre_l"),
+                match.group("pre_n"),
+            ),
+            post=_parse_letter_version(
+                match.group("post_l"),
+                match.group("post_n1") or match.group("post_n2"),
+            ),
+            dev=_parse_letter_version(
+                match.group("dev_l"),
+                match.group("dev_n"),
+            ),
+            local=_parse_local_version(match.group("local")),
+        )
+
+        # Generate a key which will be used for sorting
+        self._key = _cmpkey(
+            self._version.epoch,
+            self._version.release,
+            self._version.pre,
+            self._version.post,
+            self._version.dev,
+            self._version.local,
+        )
+
+    def __repr__(self):
+        return f""
+
+    def __str__(self):
+        parts = []
+
+        # Epoch
+        if self._version.epoch != 0:
+            parts.append(f"{self._version.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self._version.release))
+
+        # Pre-release
+        if self._version.pre is not None:
+            parts.append("".join(str(x) for x in self._version.pre))
+
+        # Post-release
+        if self._version.post is not None:
+            parts.append(f".post{self._version.post[1]}")
+
+        # Development release
+        if self._version.dev is not None:
+            parts.append(f".dev{self._version.dev[1]}")
+
+        # Local version segment
+        if self._version.local is not None:
+            parts.append(
+                "+{}".format(".".join(str(x) for x in self._version.local))
+            )
+
+        return "".join(parts)
+
+    @property
+    def public(self):
+        return str(self).split("+", 1)[0]
+
+    @property
+    def base_version(self):
+        parts = []
+
+        # Epoch
+        if self._version.epoch != 0:
+            parts.append(f"{self._version.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self._version.release))
+
+        return "".join(parts)
+
+    @property
+    def local(self):
+        version_string = str(self)
+        if "+" in version_string:
+            return version_string.split("+", 1)[1]
+
+    @property
+    def is_prerelease(self):
+        return bool(self._version.dev or self._version.pre)
+
+    @property
+    def is_postrelease(self):
+        return bool(self._version.post)
+
+
+def _parse_letter_version(letter, number):
+    if letter:
+        # We assume there is an implicit 0 in a pre-release if there is
+        # no numeral associated with it.
+        if number is None:
+            number = 0
+
+        # We normalize any letters to their lower-case form
+        letter = letter.lower()
+
+        # We consider some words to be alternate spellings of other words and
+        # in those cases we want to normalize the spellings to our preferred
+        # spelling.
+        if letter == "alpha":
+            letter = "a"
+        elif letter == "beta":
+            letter = "b"
+        elif letter in ["c", "pre", "preview"]:
+            letter = "rc"
+        elif letter in ["rev", "r"]:
+            letter = "post"
+
+        return letter, int(number)
+    if not letter and number:
+        # We assume that if we are given a number but not given a letter,
+        # then this is using the implicit post release syntax (e.g., 1.0-1)
+        letter = "post"
+
+        return letter, int(number)
+
+
+_local_version_seperators = re.compile(r"[\._-]")
+
+
+def _parse_local_version(local):
+    """
+    Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
+    """
+    if local is not None:
+        return tuple(
+            part.lower() if not part.isdigit() else int(part)
+            for part in _local_version_seperators.split(local)
+        )
+
+
+def _cmpkey(epoch, release, pre, post, dev, local):
+    # When we compare a release version, we want to compare it with all of the
+    # trailing zeros removed. So we'll use a reverse the list, drop all the now
+    # leading zeros until we come to something non-zero, then take the rest,
+    # re-reverse it back into the correct order, and make it a tuple and use
+    # that for our sorting key.
+    release = tuple(
+        reversed(list(
+            itertools.dropwhile(
+                lambda x: x == 0,
+                reversed(release),
+            )
+        ))
+    )
+
+    # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
+    # We'll do this by abusing the pre-segment, but we _only_ want to do this
+    # if there is no pre- or a post-segment. If we have one of those, then
+    # the normal sorting rules will handle this case correctly.
+    if pre is None and post is None and dev is not None:
+        pre = -Infinity
+    # Versions without a pre-release (except as noted above) should sort after
+    # those with one.
+    elif pre is None:
+        pre = Infinity
+
+    # Versions without a post-segment should sort before those with one.
+    if post is None:
+        post = -Infinity
+
+    # Versions without a development segment should sort after those with one.
+    if dev is None:
+        dev = Infinity
+
+    if local is None:
+        # Versions without a local segment should sort before those with one.
+        local = -Infinity
+    else:
+        # Versions with a local segment need that segment parsed to implement
+        # the sorting rules in PEP440.
+        # - Alphanumeric segments sort before numeric segments
+        # - Alphanumeric segments sort lexicographically
+        # - Numeric segments sort numerically
+        # - Shorter versions sort before longer versions when the prefixes
+        #   match exactly
+        local = tuple(
+            (i, "") if isinstance(i, int) else (-Infinity, i)
+            for i in local
+        )
+
+    return epoch, release, pre, post, dev, local
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_sparse.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_sparse.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7deb32dd6e5d19bb8fceae4a7d22f2c6eddda7a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_sparse.py
@@ -0,0 +1,41 @@
+from abc import ABC
+
+__all__ = ["SparseABC", "issparse"]
+
+
+class SparseABC(ABC):
+    pass
+
+
+def issparse(x):
+    """Is `x` of a sparse array or sparse matrix type?
+
+    Parameters
+    ----------
+    x
+        object to check for being a sparse array or sparse matrix
+
+    Returns
+    -------
+    bool
+        True if `x` is a sparse array or a sparse matrix, False otherwise
+
+    Notes
+    -----
+    Use `isinstance(x, sp.sparse.sparray)` to check between an array or matrix.
+    Use `a.format` to check the sparse format, e.g. `a.format == 'csr'`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csr_array, csr_matrix, issparse
+    >>> issparse(csr_matrix([[5]]))
+    True
+    >>> issparse(csr_array([[5]]))
+    True
+    >>> issparse(np.array([[5]]))
+    False
+    >>> issparse(5)
+    False
+    """
+    return isinstance(x, SparseABC)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_test_ccallback.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_test_ccallback.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..29a7cea059184c0608bab3bb0a6b92dae08ba9db
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_test_ccallback.cpython-312-x86_64-linux-gnu.so differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_test_deprecation_call.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_test_deprecation_call.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..be3f7389b178e6b78951453f485ac8cd2eec1dc8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_test_deprecation_call.cpython-312-x86_64-linux-gnu.so differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_test_deprecation_def.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_test_deprecation_def.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..5f6810bbd9636acbbd0c8309d0c1264621545718
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_test_deprecation_def.cpython-312-x86_64-linux-gnu.so differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_testutils.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..442bb539db3bbedf0a64876fea124c107f3d0383
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_testutils.py
@@ -0,0 +1,373 @@
+"""
+Generic test utilities.
+
+"""
+
+import inspect
+import os
+import re
+import shutil
+import subprocess
+import sys
+import sysconfig
+import threading
+from importlib.util import module_from_spec, spec_from_file_location
+
+import numpy as np
+import scipy
+
+try:
+    # Need type: ignore[import-untyped] for mypy >= 1.6
+    import cython  # type: ignore[import-untyped]
+    from Cython.Compiler.Version import (  # type: ignore[import-untyped]
+        version as cython_version,
+    )
+except ImportError:
+    cython = None
+else:
+    from scipy._lib import _pep440
+    required_version = '3.0.8'
+    if _pep440.parse(cython_version) < _pep440.Version(required_version):
+        # too old or wrong cython, skip Cython API tests
+        cython = None
+
+
+__all__ = ['PytestTester', 'check_free_memory', '_TestPythranFunc', 'IS_MUSL']
+
+
+IS_MUSL = False
+# alternate way is
+# from packaging.tags import sys_tags
+#     _tags = list(sys_tags())
+#     if 'musllinux' in _tags[0].platform:
+_v = sysconfig.get_config_var('HOST_GNU_TYPE') or ''
+if 'musl' in _v:
+    IS_MUSL = True
+
+
+IS_EDITABLE = 'editable' in scipy.__path__[0]
+
+
+class FPUModeChangeWarning(RuntimeWarning):
+    """Warning about FPU mode change"""
+    pass
+
+
+class PytestTester:
+    """
+    Run tests for this namespace
+
+    ``scipy.test()`` runs tests for all of SciPy, with the default settings.
+    When used from a submodule (e.g., ``scipy.cluster.test()``, only the tests
+    for that namespace are run.
+
+    Parameters
+    ----------
+    label : {'fast', 'full'}, optional
+        Whether to run only the fast tests, or also those marked as slow.
+        Default is 'fast'.
+    verbose : int, optional
+        Test output verbosity. Default is 1.
+    extra_argv : list, optional
+        Arguments to pass through to Pytest.
+    doctests : bool, optional
+        Whether to run doctests or not. Default is False.
+    coverage : bool, optional
+        Whether to run tests with code coverage measurements enabled.
+        Default is False.
+    tests : list of str, optional
+        List of module names to run tests for. By default, uses the module
+        from which the ``test`` function is called.
+    parallel : int, optional
+        Run tests in parallel with pytest-xdist, if number given is larger than
+        1. Default is 1.
+
+    """
+    def __init__(self, module_name):
+        self.module_name = module_name
+
+    def __call__(self, label="fast", verbose=1, extra_argv=None, doctests=False,
+                 coverage=False, tests=None, parallel=None):
+        import pytest
+
+        module = sys.modules[self.module_name]
+        module_path = os.path.abspath(module.__path__[0])
+
+        pytest_args = ['--showlocals', '--tb=short']
+
+        if extra_argv is None:
+            extra_argv = []
+        pytest_args += extra_argv
+        if any(arg == "-m" or arg == "--markers" for arg in extra_argv):
+            # Likely conflict with default --mode=fast
+            raise ValueError("Must specify -m before --")
+
+        if verbose and int(verbose) > 1:
+            pytest_args += ["-" + "v"*(int(verbose)-1)]
+
+        if coverage:
+            pytest_args += ["--cov=" + module_path]
+
+        if label == "fast":
+            pytest_args += ["-m", "not slow"]
+        elif label != "full":
+            pytest_args += ["-m", label]
+
+        if tests is None:
+            tests = [self.module_name]
+
+        if parallel is not None and parallel > 1:
+            if _pytest_has_xdist():
+                pytest_args += ['-n', str(parallel)]
+            else:
+                import warnings
+                warnings.warn('Could not run tests in parallel because '
+                              'pytest-xdist plugin is not available.',
+                              stacklevel=2)
+
+        pytest_args += ['--pyargs'] + list(tests)
+
+        try:
+            code = pytest.main(pytest_args)
+        except SystemExit as exc:
+            code = exc.code
+
+        return (code == 0)
+
+
+class _TestPythranFunc:
+    '''
+    These are situations that can be tested in our pythran tests:
+    - A function with multiple array arguments and then
+      other positional and keyword arguments.
+    - A function with array-like keywords (e.g. `def somefunc(x0, x1=None)`.
+    Note: list/tuple input is not yet tested!
+
+    `self.arguments`: A dictionary which key is the index of the argument,
+                      value is tuple(array value, all supported dtypes)
+    `self.partialfunc`: A function used to freeze some non-array argument
+                        that of no interests in the original function
+    '''
+    ALL_INTEGER = [np.int8, np.int16, np.int32, np.int64, np.intc, np.intp]
+    ALL_FLOAT = [np.float32, np.float64]
+    ALL_COMPLEX = [np.complex64, np.complex128]
+
+    def setup_method(self):
+        self.arguments = {}
+        self.partialfunc = None
+        self.expected = None
+
+    def get_optional_args(self, func):
+        # get optional arguments with its default value,
+        # used for testing keywords
+        signature = inspect.signature(func)
+        optional_args = {}
+        for k, v in signature.parameters.items():
+            if v.default is not inspect.Parameter.empty:
+                optional_args[k] = v.default
+        return optional_args
+
+    def get_max_dtype_list_length(self):
+        # get the max supported dtypes list length in all arguments
+        max_len = 0
+        for arg_idx in self.arguments:
+            cur_len = len(self.arguments[arg_idx][1])
+            if cur_len > max_len:
+                max_len = cur_len
+        return max_len
+
+    def get_dtype(self, dtype_list, dtype_idx):
+        # get the dtype from dtype_list via index
+        # if the index is out of range, then return the last dtype
+        if dtype_idx > len(dtype_list)-1:
+            return dtype_list[-1]
+        else:
+            return dtype_list[dtype_idx]
+
+    def test_all_dtypes(self):
+        for type_idx in range(self.get_max_dtype_list_length()):
+            args_array = []
+            for arg_idx in self.arguments:
+                new_dtype = self.get_dtype(self.arguments[arg_idx][1],
+                                           type_idx)
+                args_array.append(self.arguments[arg_idx][0].astype(new_dtype))
+            self.pythranfunc(*args_array)
+
+    def test_views(self):
+        args_array = []
+        for arg_idx in self.arguments:
+            args_array.append(self.arguments[arg_idx][0][::-1][::-1])
+        self.pythranfunc(*args_array)
+
+    def test_strided(self):
+        args_array = []
+        for arg_idx in self.arguments:
+            args_array.append(np.repeat(self.arguments[arg_idx][0],
+                                        2, axis=0)[::2])
+        self.pythranfunc(*args_array)
+
+
+def _pytest_has_xdist():
+    """
+    Check if the pytest-xdist plugin is installed, providing parallel tests
+    """
+    # Check xdist exists without importing, otherwise pytests emits warnings
+    from importlib.util import find_spec
+    return find_spec('xdist') is not None
+
+
+def check_free_memory(free_mb):
+    """
+    Check *free_mb* of memory is available, otherwise do pytest.skip
+    """
+    import pytest
+
+    try:
+        mem_free = _parse_size(os.environ['SCIPY_AVAILABLE_MEM'])
+        msg = '{} MB memory required, but environment SCIPY_AVAILABLE_MEM={}'.format(
+            free_mb, os.environ['SCIPY_AVAILABLE_MEM'])
+    except KeyError:
+        mem_free = _get_mem_available()
+        if mem_free is None:
+            pytest.skip("Could not determine available memory; set SCIPY_AVAILABLE_MEM "
+                        "variable to free memory in MB to run the test.")
+        msg = f'{free_mb} MB memory required, but {mem_free/1e6} MB available'
+
+    if mem_free < free_mb * 1e6:
+        pytest.skip(msg)
+
+
+def _parse_size(size_str):
+    suffixes = {'': 1e6,
+                'b': 1.0,
+                'k': 1e3, 'M': 1e6, 'G': 1e9, 'T': 1e12,
+                'kb': 1e3, 'Mb': 1e6, 'Gb': 1e9, 'Tb': 1e12,
+                'kib': 1024.0, 'Mib': 1024.0**2, 'Gib': 1024.0**3, 'Tib': 1024.0**4}
+    m = re.match(r'^\s*(\d+)\s*({})\s*$'.format('|'.join(suffixes.keys())),
+                 size_str,
+                 re.I)
+    if not m or m.group(2) not in suffixes:
+        raise ValueError("Invalid size string")
+
+    return float(m.group(1)) * suffixes[m.group(2)]
+
+
+def _get_mem_available():
+    """
+    Get information about memory available, not counting swap.
+    """
+    try:
+        import psutil
+        return psutil.virtual_memory().available
+    except (ImportError, AttributeError):
+        pass
+
+    if sys.platform.startswith('linux'):
+        info = {}
+        with open('/proc/meminfo') as f:
+            for line in f:
+                p = line.split()
+                info[p[0].strip(':').lower()] = float(p[1]) * 1e3
+
+        if 'memavailable' in info:
+            # Linux >= 3.14
+            return info['memavailable']
+        else:
+            return info['memfree'] + info['cached']
+
+    return None
+
+def _test_cython_extension(tmp_path, srcdir):
+    """
+    Helper function to test building and importing Cython modules that
+    make use of the Cython APIs for BLAS, LAPACK, optimize, and special.
+    """
+    import pytest
+    try:
+        subprocess.check_call(["meson", "--version"])
+    except FileNotFoundError:
+        pytest.skip("No usable 'meson' found")
+
+    # Make safe for being called by multiple threads within one test
+    tmp_path = tmp_path / str(threading.get_ident())
+
+    # build the examples in a temporary directory
+    mod_name = os.path.split(srcdir)[1]
+    shutil.copytree(srcdir, tmp_path / mod_name)
+    build_dir = tmp_path / mod_name / 'tests' / '_cython_examples'
+    target_dir = build_dir / 'build'
+    os.makedirs(target_dir, exist_ok=True)
+
+    # Ensure we use the correct Python interpreter even when `meson` is
+    # installed in a different Python environment (see numpy#24956)
+    native_file = str(build_dir / 'interpreter-native-file.ini')
+    with open(native_file, 'w') as f:
+        f.write("[binaries]\n")
+        f.write(f"python = '{sys.executable}'")
+
+    if sys.platform == "win32":
+        subprocess.check_call(["meson", "setup",
+                               "--buildtype=release",
+                               "--native-file", native_file,
+                               "--vsenv", str(build_dir)],
+                              cwd=target_dir,
+                              )
+    else:
+        subprocess.check_call(["meson", "setup",
+                               "--native-file", native_file, str(build_dir)],
+                              cwd=target_dir
+                              )
+    subprocess.check_call(["meson", "compile", "-vv"], cwd=target_dir)
+
+    # import without adding the directory to sys.path
+    suffix = sysconfig.get_config_var('EXT_SUFFIX')
+
+    def load(modname):
+        so = (target_dir / modname).with_suffix(suffix)
+        spec = spec_from_file_location(modname, so)
+        mod = module_from_spec(spec)
+        spec.loader.exec_module(mod)
+        return mod
+
+    # test that the module can be imported
+    return load("extending"), load("extending_cpp")
+
+
+def _run_concurrent_barrier(n_workers, fn, *args, **kwargs):
+    """
+    Run a given function concurrently across a given number of threads.
+
+    This is equivalent to using a ThreadPoolExecutor, but using the threading
+    primitives instead. This function ensures that the closure passed by
+    parameter gets called concurrently by setting up a barrier before it gets
+    called before any of the threads.
+
+    Arguments
+    ---------
+    n_workers: int
+        Number of concurrent threads to spawn.
+    fn: callable
+        Function closure to execute concurrently. Its first argument will
+        be the thread id.
+    *args: tuple
+        Variable number of positional arguments to pass to the function.
+    **kwargs: dict
+        Keyword arguments to pass to the function.
+    """
+    barrier = threading.Barrier(n_workers)
+
+    def closure(i, *args, **kwargs):
+        barrier.wait()
+        fn(i, *args, **kwargs)
+
+    workers = []
+    for i in range(0, n_workers):
+        workers.append(threading.Thread(
+            target=closure,
+            args=(i,) + args, kwargs=kwargs))
+
+    for worker in workers:
+        worker.start()
+
+    for worker in workers:
+        worker.join()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_threadsafety.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_threadsafety.py
new file mode 100644
index 0000000000000000000000000000000000000000..530339ec7075dafdb81e9fa0ff5447952af77497
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_threadsafety.py
@@ -0,0 +1,58 @@
+import threading
+
+import scipy._lib.decorator
+
+
+__all__ = ['ReentrancyError', 'ReentrancyLock', 'non_reentrant']
+
+
+class ReentrancyError(RuntimeError):
+    pass
+
+
+class ReentrancyLock:
+    """
+    Threading lock that raises an exception for reentrant calls.
+
+    Calls from different threads are serialized, and nested calls from the
+    same thread result to an error.
+
+    The object can be used as a context manager or to decorate functions
+    via the decorate() method.
+
+    """
+
+    def __init__(self, err_msg):
+        self._rlock = threading.RLock()
+        self._entered = False
+        self._err_msg = err_msg
+
+    def __enter__(self):
+        self._rlock.acquire()
+        if self._entered:
+            self._rlock.release()
+            raise ReentrancyError(self._err_msg)
+        self._entered = True
+
+    def __exit__(self, type, value, traceback):
+        self._entered = False
+        self._rlock.release()
+
+    def decorate(self, func):
+        def caller(func, *a, **kw):
+            with self:
+                return func(*a, **kw)
+        return scipy._lib.decorator.decorate(func, caller)
+
+
+def non_reentrant(err_msg=None):
+    """
+    Decorate a function with a threading lock and prevent reentrant calls.
+    """
+    def decorator(func):
+        msg = err_msg
+        if msg is None:
+            msg = f"{func.__name__} is not re-entrant"
+        lock = ReentrancyLock(msg)
+        return lock.decorate(func)
+    return decorator
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_tmpdirs.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_tmpdirs.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f9fd546a9d2ae3e9a20c0684f79eb0b3d61ee92
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_tmpdirs.py
@@ -0,0 +1,86 @@
+''' Contexts for *with* statement providing temporary directories
+'''
+import os
+from contextlib import contextmanager
+from shutil import rmtree
+from tempfile import mkdtemp
+
+
+@contextmanager
+def tempdir():
+    """Create and return a temporary directory. This has the same
+    behavior as mkdtemp but can be used as a context manager.
+
+    Upon exiting the context, the directory and everything contained
+    in it are removed.
+
+    Examples
+    --------
+    >>> import os
+    >>> with tempdir() as tmpdir:
+    ...     fname = os.path.join(tmpdir, 'example_file.txt')
+    ...     with open(fname, 'wt') as fobj:
+    ...         _ = fobj.write('a string\\n')
+    >>> os.path.exists(tmpdir)
+    False
+    """
+    d = mkdtemp()
+    yield d
+    rmtree(d)
+
+
+@contextmanager
+def in_tempdir():
+    ''' Create, return, and change directory to a temporary directory
+
+    Examples
+    --------
+    >>> import os
+    >>> my_cwd = os.getcwd()
+    >>> with in_tempdir() as tmpdir:
+    ...     _ = open('test.txt', 'wt').write('some text')
+    ...     assert os.path.isfile('test.txt')
+    ...     assert os.path.isfile(os.path.join(tmpdir, 'test.txt'))
+    >>> os.path.exists(tmpdir)
+    False
+    >>> os.getcwd() == my_cwd
+    True
+    '''
+    pwd = os.getcwd()
+    d = mkdtemp()
+    os.chdir(d)
+    yield d
+    os.chdir(pwd)
+    rmtree(d)
+
+
+@contextmanager
+def in_dir(dir=None):
+    """ Change directory to given directory for duration of ``with`` block
+
+    Useful when you want to use `in_tempdir` for the final test, but
+    you are still debugging. For example, you may want to do this in the end:
+
+    >>> with in_tempdir() as tmpdir:
+    ...     # do something complicated which might break
+    ...     pass
+
+    But, indeed, the complicated thing does break, and meanwhile, the
+    ``in_tempdir`` context manager wiped out the directory with the
+    temporary files that you wanted for debugging. So, while debugging, you
+    replace with something like:
+
+    >>> with in_dir() as tmpdir: # Use working directory by default
+    ...     # do something complicated which might break
+    ...     pass
+
+    You can then look at the temporary file outputs to debug what is happening,
+    fix, and finally replace ``in_dir`` with ``in_tempdir`` again.
+    """
+    cwd = os.getcwd()
+    if dir is None:
+        yield cwd
+        return
+    os.chdir(dir)
+    yield dir
+    os.chdir(cwd)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_util.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..b60c2de817e9eabcb42e160633cdff6c6caa8c3a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/_util.py
@@ -0,0 +1,1283 @@
+import re
+from contextlib import contextmanager
+import functools
+import operator
+import warnings
+import numbers
+from collections import namedtuple
+import inspect
+import math
+from types import ModuleType
+from typing import Literal, TypeAlias, TypeVar
+
+import numpy as np
+from scipy._lib._array_api import (Array, array_namespace, is_lazy_array,
+                                   is_numpy, is_marray, xp_result_device,
+                                   xp_size, xp_result_type)
+from scipy._lib._docscrape import FunctionDoc, Parameter
+from scipy._lib._sparse import issparse
+
+from numpy.exceptions import AxisError
+
+
+np_long: type
+np_ulong: type
+
+if np.lib.NumpyVersion(np.__version__) >= "2.0.0.dev0":
+    try:
+        with warnings.catch_warnings():
+            warnings.filterwarnings(
+                "ignore",
+                r".*In the future `np\.long` will be defined as.*",
+                FutureWarning,
+            )
+            np_long = np.long  # type: ignore[attr-defined]
+            np_ulong = np.ulong  # type: ignore[attr-defined]
+    except AttributeError:
+            np_long = np.int_
+            np_ulong = np.uint
+else:
+    np_long = np.int_
+    np_ulong = np.uint
+
+IntNumber = int | np.integer
+DecimalNumber = float | np.floating | np.integer
+
+copy_if_needed: bool | None
+
+if np.lib.NumpyVersion(np.__version__) >= "2.0.0":
+    copy_if_needed = None
+elif np.lib.NumpyVersion(np.__version__) < "1.28.0":
+    copy_if_needed = False
+else:
+    # 2.0.0 dev versions, handle cases where copy may or may not exist
+    try:
+        np.array([1]).__array__(copy=None)  # type: ignore[call-overload]
+        copy_if_needed = None
+    except TypeError:
+        copy_if_needed = False
+
+
+_RNG: TypeAlias = np.random.Generator | np.random.RandomState
+SeedType: TypeAlias = IntNumber | _RNG | None
+
+GeneratorType = TypeVar("GeneratorType", bound=_RNG)
+
+# Since Generator was introduced in numpy 1.17, the following condition is needed for
+# backward compatibility
+try:
+    from numpy.random import Generator as Generator
+except ImportError:
+    class Generator:  # type: ignore[no-redef]
+        pass
+
+
+def _lazyselect(condlist, choicelist, arrays, default=0):
+    """
+    Mimic `np.select(condlist, choicelist)`.
+
+    Notice, it assumes that all `arrays` are of the same shape or can be
+    broadcasted together.
+
+    All functions in `choicelist` must accept array arguments in the order
+    given in `arrays` and must return an array of the same shape as broadcasted
+    `arrays`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> x = np.arange(6)
+    >>> np.select([x <3, x > 3], [x**2, x**3], default=0)
+    array([  0,   1,   4,   0,  64, 125])
+
+    >>> _lazyselect([x < 3, x > 3], [lambda x: x**2, lambda x: x**3], (x,))
+    array([   0.,    1.,    4.,   0.,   64.,  125.])
+
+    >>> a = -np.ones_like(x)
+    >>> _lazyselect([x < 3, x > 3],
+    ...             [lambda x, a: x**2, lambda x, a: a * x**3],
+    ...             (x, a), default=np.nan)
+    array([   0.,    1.,    4.,   nan,  -64., -125.])
+
+    """
+    arrays = np.broadcast_arrays(*arrays)
+    tcode = np.mintypecode([a.dtype.char for a in arrays])
+    out = np.full(np.shape(arrays[0]), fill_value=default, dtype=tcode)
+    for func, cond in zip(choicelist, condlist):
+        if np.all(cond is False):
+            continue
+        cond, _ = np.broadcast_arrays(cond, arrays[0])
+        temp = tuple(np.extract(cond, arr) for arr in arrays)
+        np.place(out, cond, func(*temp))
+    return out
+
+
+def _aligned_zeros(shape, dtype=float, order="C", align=None):
+    """Allocate a new ndarray with aligned memory.
+
+    Primary use case for this currently is working around a f2py issue
+    in NumPy 1.9.1, where dtype.alignment is such that np.zeros() does
+    not necessarily create arrays aligned up to it.
+
+    """
+    dtype = np.dtype(dtype)
+    if align is None:
+        align = dtype.alignment
+    if not hasattr(shape, '__len__'):
+        shape = (shape,)
+    size = functools.reduce(operator.mul, shape) * dtype.itemsize
+    buf = np.empty(size + align + 1, np.uint8)
+    offset = buf.__array_interface__['data'][0] % align
+    if offset != 0:
+        offset = align - offset
+    # Note: slices producing 0-size arrays do not necessarily change
+    # data pointer --- so we use and allocate size+1
+    buf = buf[offset:offset+size+1][:-1]
+    data = np.ndarray(shape, dtype, buf, order=order)
+    data.fill(0)
+    return data
+
+
+def _prune_array(array):
+    """Return an array equivalent to the input array. If the input
+    array is a view of a much larger array, copy its contents to a
+    newly allocated array. Otherwise, return the input unchanged.
+    """
+    if array.base is not None and array.size < array.base.size // 2:
+        return array.copy()
+    return array
+
+
+def float_factorial(n: int) -> float:
+    """Compute the factorial and return as a float
+
+    Returns infinity when result is too large for a double
+    """
+    return float(math.factorial(n)) if n < 171 else np.inf
+
+
+_rng_desc = (
+    r"""If `rng` is passed by keyword, types other than `numpy.random.Generator` are
+    passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+    If `rng` is already a ``Generator`` instance, then the provided instance is
+    used. Specify `rng` for repeatable function behavior.
+
+    If this argument is passed by position or `{old_name}` is passed by keyword,
+    legacy behavior for the argument `{old_name}` applies:
+
+    - If `{old_name}` is None (or `numpy.random`), the `numpy.random.RandomState`
+      singleton is used.
+    - If `{old_name}` is an int, a new ``RandomState`` instance is used,
+      seeded with `{old_name}`.
+    - If `{old_name}` is already a ``Generator`` or ``RandomState`` instance then
+      that instance is used.
+
+    .. versionchanged:: 1.15.0
+        As part of the `SPEC-007 `_
+        transition from use of `numpy.random.RandomState` to
+        `numpy.random.Generator`, this keyword was changed from `{old_name}` to `rng`.
+        For an interim period, both keywords will continue to work, although only one
+        may be specified at a time. After the interim period, function calls using the
+        `{old_name}` keyword will emit warnings. The behavior of both `{old_name}` and
+        `rng` are outlined above, but only the `rng` keyword should be used in new code.
+        """
+)
+
+
+# SPEC 7
+def _transition_to_rng(old_name, *, position_num=None, end_version=None,
+                       replace_doc=True):
+    """Example decorator to transition from old PRNG usage to new `rng` behavior
+
+    Suppose the decorator is applied to a function that used to accept parameter
+    `old_name='random_state'` either by keyword or as a positional argument at
+    `position_num=1`. At the time of application, the name of the argument in the
+    function signature is manually changed to the new name, `rng`. If positional
+    use was allowed before, this is not changed.*
+
+    - If the function is called with both `random_state` and `rng`, the decorator
+      raises an error.
+    - If `random_state` is provided as a keyword argument, the decorator passes
+      `random_state` to the function's `rng` argument as a keyword. If `end_version`
+      is specified, the decorator will emit a `DeprecationWarning` about the
+      deprecation of keyword `random_state`.
+    - If `random_state` is provided as a positional argument, the decorator passes
+      `random_state` to the function's `rng` argument by position. If `end_version`
+      is specified, the decorator will emit a `FutureWarning` about the changing
+      interpretation of the argument.
+    - If `rng` is provided as a keyword argument, the decorator validates `rng` using
+      `numpy.random.default_rng` before passing it to the function.
+    - If `end_version` is specified and neither `random_state` nor `rng` is provided
+      by the user, the decorator checks whether `np.random.seed` has been used to set
+      the global seed. If so, it emits a `FutureWarning`, noting that usage of
+      `numpy.random.seed` will eventually have no effect. Either way, the decorator
+      calls the function without explicitly passing the `rng` argument.
+
+    If `end_version` is specified, a user must pass `rng` as a keyword to avoid
+    warnings.
+
+    After the deprecation period, the decorator can be removed, and the function
+    can simply validate the `rng` argument by calling `np.random.default_rng(rng)`.
+
+    * A `FutureWarning` is emitted when the PRNG argument is used by
+      position. It indicates that the "Hinsen principle" (same
+      code yielding different results in two versions of the software)
+      will be violated, unless positional use is deprecated. Specifically:
+
+      - If `None` is passed by position and `np.random.seed` has been used,
+        the function will change from being seeded to being unseeded.
+      - If an integer is passed by position, the random stream will change.
+      - If `np.random` or an instance of `RandomState` is passed by position,
+        an error will be raised.
+
+      We suggest that projects consider deprecating positional use of
+      `random_state`/`rng` (i.e., change their function signatures to
+      ``def my_func(..., *, rng=None)``); that might not make sense
+      for all projects, so this SPEC does not make that
+      recommendation, neither does this decorator enforce it.
+
+    Parameters
+    ----------
+    old_name : str
+        The old name of the PRNG argument (e.g. `seed` or `random_state`).
+    position_num : int, optional
+        The (0-indexed) position of the old PRNG argument (if accepted by position).
+        Maintainers are welcome to eliminate this argument and use, for example,
+        `inspect`, if preferred.
+    end_version : str, optional
+        The full version number of the library when the behavior described in
+        `DeprecationWarning`s and `FutureWarning`s will take effect. If left
+        unspecified, no warnings will be emitted by the decorator.
+    replace_doc : bool, default: True
+        Whether the decorator should replace the documentation for parameter `rng` with
+        `_rng_desc` (defined above), which documents both new `rng` keyword behavior
+        and typical legacy `random_state`/`seed` behavior. If True, manually replace
+        the first paragraph of the function's old `random_state`/`seed` documentation
+        with the desired *final* `rng` documentation; this way, no changes to
+        documentation are needed when the decorator is removed. Documentation of `rng`
+        after the first blank line is preserved. Use False if the function's old
+        `random_state`/`seed` behavior does not match that described by `_rng_desc`.
+
+    """
+    NEW_NAME = "rng"
+
+    cmn_msg = (
+        "To silence this warning and ensure consistent behavior in SciPy "
+        f"{end_version}, control the RNG using argument `{NEW_NAME}`. Arguments passed "
+        f"to keyword `{NEW_NAME}` will be validated by `np.random.default_rng`, so the "
+        "behavior corresponding with a given value may change compared to use of "
+        f"`{old_name}`. For example, "
+        "1) `None` will result in unpredictable random numbers, "
+        "2) an integer will result in a different stream of random numbers, (with the "
+        "same distribution), and "
+        "3) `np.random` or `RandomState` instances will result in an error. "
+        "See the documentation of `default_rng` for more information."
+    )
+
+    def decorator(fun):
+        @functools.wraps(fun)
+        def wrapper(*args, **kwargs):
+            # Determine how PRNG was passed
+            as_old_kwarg = old_name in kwargs
+            as_new_kwarg = NEW_NAME in kwargs
+            as_pos_arg = position_num is not None and len(args) >= position_num + 1
+            emit_warning = end_version is not None
+
+            # Can only specify PRNG one of the three ways
+            if int(as_old_kwarg) + int(as_new_kwarg) + int(as_pos_arg) > 1:
+                message = (
+                    f"{fun.__name__}() got multiple values for "
+                    f"argument now known as `{NEW_NAME}`. Specify one of "
+                    f"`{NEW_NAME}` or `{old_name}`."
+                )
+                raise TypeError(message)
+
+            # Check whether global random state has been set
+            global_seed_set = np.random.mtrand._rand._bit_generator._seed_seq is None
+
+            if as_old_kwarg:  # warn about deprecated use of old kwarg
+                kwargs[NEW_NAME] = kwargs.pop(old_name)
+                if emit_warning:
+                    message = (
+                        f"Use of keyword argument `{old_name}` is "
+                        f"deprecated and replaced by `{NEW_NAME}`.  "
+                        f"Support for `{old_name}` will be removed "
+                        f"in SciPy {end_version}. "
+                    ) + cmn_msg
+                    warnings.warn(message, DeprecationWarning, stacklevel=2)
+
+            elif as_pos_arg:
+                # Warn about changing meaning of positional arg
+
+                # Note that this decorator does not deprecate positional use of the
+                # argument; it only warns that the behavior will change in the future.
+                # Simultaneously transitioning to keyword-only use is another option.
+
+                arg = args[position_num]
+                # If the argument is None and the global seed wasn't set, or if the
+                # argument is one of a few new classes, the user will not notice change
+                # in behavior.
+                ok_classes = (
+                    np.random.Generator,
+                    np.random.SeedSequence,
+                    np.random.BitGenerator,
+                )
+                if (arg is None and not global_seed_set) or isinstance(arg, ok_classes):
+                    pass
+                elif emit_warning:
+                    message = (
+                        f"Positional use of `{NEW_NAME}` (formerly known as "
+                        f"`{old_name}`) is still allowed, but the behavior is "
+                        "changing: the argument will be normalized using "
+                        f"`np.random.default_rng` beginning in SciPy {end_version}, "
+                        "and the resulting `Generator` will be used to generate "
+                        "random numbers."
+                    ) + cmn_msg
+                    warnings.warn(message, FutureWarning, stacklevel=2)
+
+            elif as_new_kwarg:  # no warnings; this is the preferred use
+                # After the removal of the decorator, normalization with
+                # np.random.default_rng will be done inside the decorated function
+                kwargs[NEW_NAME] = np.random.default_rng(kwargs[NEW_NAME])
+
+            elif global_seed_set and emit_warning:
+                # Emit FutureWarning if `np.random.seed` was used and no PRNG was passed
+                message = (
+                    "The NumPy global RNG was seeded by calling "
+                    f"`np.random.seed`. Beginning in {end_version}, this "
+                    "function will no longer use the global RNG."
+                ) + cmn_msg
+                warnings.warn(message, FutureWarning, stacklevel=2)
+
+            return fun(*args, **kwargs)
+
+        # Add the old parameter name to the function signature
+        wrapped_signature = inspect.signature(fun)
+        wrapper.__signature__ = wrapped_signature.replace(parameters=[
+            *wrapped_signature.parameters.values(),
+            inspect.Parameter(old_name, inspect.Parameter.KEYWORD_ONLY, default=None),
+        ])
+
+        if replace_doc:
+            doc = FunctionDoc(wrapper)
+            parameter_names = [param.name for param in doc['Parameters']]
+            if 'rng' in parameter_names:
+                _type = "{None, int, `numpy.random.Generator`}, optional"
+                _desc = _rng_desc.replace("{old_name}", old_name)
+                old_doc = doc['Parameters'][parameter_names.index('rng')].desc
+                old_doc_keep = old_doc[old_doc.index("") + 1:] if "" in old_doc else []
+                new_doc = [_desc] + old_doc_keep
+                _rng_parameter_doc = Parameter('rng', _type, new_doc)
+                doc['Parameters'][parameter_names.index('rng')] = _rng_parameter_doc
+                doc = str(doc).split("\n", 1)[1]  # remove signature
+                wrapper.__doc__ = str(doc)
+        return wrapper
+
+    return decorator
+
+
+# copy-pasted from scikit-learn utils/validation.py
+def check_random_state(seed):
+    """Turn `seed` into a `np.random.RandomState` instance.
+
+    Parameters
+    ----------
+    seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
+        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+        singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used,
+        seeded with `seed`.
+        If `seed` is already a ``Generator`` or ``RandomState`` instance then
+        that instance is used.
+
+    Returns
+    -------
+    seed : {`numpy.random.Generator`, `numpy.random.RandomState`}
+        Random number generator.
+
+    """
+    if seed is None or seed is np.random:
+        return np.random.mtrand._rand
+    if isinstance(seed, numbers.Integral | np.integer):
+        return np.random.RandomState(seed)
+    if isinstance(seed, np.random.RandomState | np.random.Generator):
+        return seed
+
+    raise ValueError(f"'{seed}' cannot be used to seed a numpy.random.RandomState"
+                     " instance")
+
+
+def _asarray_validated(a, check_finite=True,
+                       sparse_ok=False, objects_ok=False, mask_ok=False,
+                       as_inexact=False):
+    """
+    Helper function for SciPy argument validation.
+
+    Many SciPy linear algebra functions do support arbitrary array-like
+    input arguments. Examples of commonly unsupported inputs include
+    matrices containing inf/nan, sparse matrix representations, and
+    matrices with complicated elements.
+
+    Parameters
+    ----------
+    a : array_like
+        The array-like input.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+    sparse_ok : bool, optional
+        True if scipy sparse matrices are allowed.
+    objects_ok : bool, optional
+        True if arrays with dype('O') are allowed.
+    mask_ok : bool, optional
+        True if masked arrays are allowed.
+    as_inexact : bool, optional
+        True to convert the input array to a np.inexact dtype.
+
+    Returns
+    -------
+    ret : ndarray
+        The converted validated array.
+
+    """
+    if not sparse_ok:
+        if issparse(a):
+            msg = ('Sparse arrays/matrices are not supported by this function. '
+                   'Perhaps one of the `scipy.sparse.linalg` functions '
+                   'would work instead.')
+            raise ValueError(msg)
+    if not mask_ok:
+        if np.ma.isMaskedArray(a):
+            raise ValueError('masked arrays are not supported')
+    toarray = np.asarray_chkfinite if check_finite else np.asarray
+    a = toarray(a)
+    if not objects_ok:
+        if a.dtype is np.dtype('O'):
+            raise ValueError('object arrays are not supported')
+    if as_inexact:
+        if not np.issubdtype(a.dtype, np.inexact):
+            a = toarray(a, dtype=np.float64)
+    return a
+
+
+def _validate_int(k, name, minimum=None):
+    """
+    Validate a scalar integer.
+
+    This function can be used to validate an argument to a function
+    that expects the value to be an integer.  It uses `operator.index`
+    to validate the value (so, for example, k=2.0 results in a
+    TypeError).
+
+    Parameters
+    ----------
+    k : int
+        The value to be validated.
+    name : str
+        The name of the parameter.
+    minimum : int, optional
+        An optional lower bound.
+    """
+    try:
+        k = operator.index(k)
+    except TypeError:
+        raise TypeError(f'{name} must be an integer.') from None
+    if minimum is not None and k < minimum:
+        raise ValueError(f'{name} must be an integer not less '
+                         f'than {minimum}') from None
+    return k
+
+
+# Add a replacement for inspect.getfullargspec()/
+# The version below is borrowed from Django,
+# https://github.com/django/django/pull/4846.
+
+# Note an inconsistency between inspect.getfullargspec(func) and
+# inspect.signature(func). If `func` is a bound method, the latter does *not*
+# list `self` as a first argument, while the former *does*.
+# Hence, cook up a common ground replacement: `getfullargspec_no_self` which
+# mimics `inspect.getfullargspec` but does not list `self`.
+#
+# This way, the caller code does not need to know whether it uses a legacy
+# .getfullargspec or a bright and shiny .signature.
+
+FullArgSpec = namedtuple('FullArgSpec',
+                         ['args', 'varargs', 'varkw', 'defaults',
+                          'kwonlyargs', 'kwonlydefaults', 'annotations'])
+
+
+def getfullargspec_no_self(func):
+    """inspect.getfullargspec replacement using inspect.signature.
+
+    If func is a bound method, do not list the 'self' parameter.
+
+    Parameters
+    ----------
+    func : callable
+        A callable to inspect
+
+    Returns
+    -------
+    fullargspec : FullArgSpec(args, varargs, varkw, defaults, kwonlyargs,
+                              kwonlydefaults, annotations)
+
+        NOTE: if the first argument of `func` is self, it is *not*, I repeat
+        *not*, included in fullargspec.args.
+        This is done for consistency between inspect.getargspec() under
+        Python 2.x, and inspect.signature() under Python 3.x.
+
+    """
+    sig = inspect.signature(func)
+    args = [
+        p.name for p in sig.parameters.values()
+        if p.kind in [inspect.Parameter.POSITIONAL_OR_KEYWORD,
+                      inspect.Parameter.POSITIONAL_ONLY]
+    ]
+    varargs = [
+        p.name for p in sig.parameters.values()
+        if p.kind == inspect.Parameter.VAR_POSITIONAL
+    ]
+    varargs = varargs[0] if varargs else None
+    varkw = [
+        p.name for p in sig.parameters.values()
+        if p.kind == inspect.Parameter.VAR_KEYWORD
+    ]
+    varkw = varkw[0] if varkw else None
+    defaults = tuple(
+        p.default for p in sig.parameters.values()
+        if (p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD and
+            p.default is not p.empty)
+    ) or None
+    kwonlyargs = [
+        p.name for p in sig.parameters.values()
+        if p.kind == inspect.Parameter.KEYWORD_ONLY
+    ]
+    kwdefaults = {p.name: p.default for p in sig.parameters.values()
+                  if p.kind == inspect.Parameter.KEYWORD_ONLY and
+                  p.default is not p.empty}
+    annotations = {p.name: p.annotation for p in sig.parameters.values()
+                   if p.annotation is not p.empty}
+    return FullArgSpec(args, varargs, varkw, defaults, kwonlyargs,
+                       kwdefaults or None, annotations)
+
+
+class _FunctionWrapper:
+    """
+    Object to wrap user's function, allowing picklability
+    """
+    def __init__(self, f, args):
+        self.f = f
+        self.args = [] if args is None else args
+
+    def __call__(self, x):
+        return self.f(x, *self.args)
+
+
+class _ScalarFunctionWrapper:
+    """
+    Object to wrap scalar user function, allowing picklability
+    """
+    def __init__(self, f, args=None):
+        self.f = f
+        self.args = [] if args is None else args
+        self.nfev = 0
+
+    def __call__(self, x):
+        # Send a copy because the user may overwrite it.
+        # The user of this class might want `x` to remain unchanged.
+        fx = self.f(np.copy(x), *self.args)
+        self.nfev += 1
+
+        # Make sure the function returns a true scalar
+        if not np.isscalar(fx):
+            try:
+                fx = np.asarray(fx).item()
+            except (TypeError, ValueError) as e:
+                raise ValueError(
+                    "The user-provided objective function "
+                    "must return a scalar value."
+                ) from e
+        return fx
+
+class MapWrapper:
+    """
+    Parallelisation wrapper for working with map-like callables, such as
+    `multiprocessing.Pool.map`.
+
+    Parameters
+    ----------
+    pool : int or map-like callable
+        If `pool` is an integer, then it specifies the number of threads to
+        use for parallelization. If ``int(pool) == 1``, then no parallel
+        processing is used and the map builtin is used.
+        If ``pool == -1``, then the pool will utilize all available CPUs.
+        If `pool` is a map-like callable that follows the same
+        calling sequence as the built-in map function, then this callable is
+        used for parallelization.
+    """
+    def __init__(self, pool=1):
+        self.pool = None
+        self._mapfunc = map
+        self._own_pool = False
+
+        if callable(pool):
+            self.pool = pool
+            self._mapfunc = self.pool
+        else:
+            from multiprocessing import Pool
+            # user supplies a number
+            if int(pool) == -1:
+                # use as many processors as possible
+                self.pool = Pool()
+                self._mapfunc = self.pool.map
+                self._own_pool = True
+            elif int(pool) == 1:
+                pass
+            elif int(pool) > 1:
+                # use the number of processors requested
+                self.pool = Pool(processes=int(pool))
+                self._mapfunc = self.pool.map
+                self._own_pool = True
+            else:
+                raise RuntimeError("Number of workers specified must be -1,"
+                                   " an int >= 1, or an object with a 'map' "
+                                   "method")
+
+    def __enter__(self):
+        return self
+
+    def terminate(self):
+        if self._own_pool:
+            self.pool.terminate()
+
+    def join(self):
+        if self._own_pool:
+            self.pool.join()
+
+    def close(self):
+        if self._own_pool:
+            self.pool.close()
+
+    def __exit__(self, exc_type, exc_value, traceback):
+        if self._own_pool:
+            self.pool.close()
+            self.pool.terminate()
+
+    def __call__(self, func, iterable):
+        # only accept one iterable because that's all Pool.map accepts
+        try:
+            return self._mapfunc(func, iterable)
+        except TypeError as e:
+            # wrong number of arguments
+            raise TypeError("The map-like callable must be of the"
+                            " form f(func, iterable)") from e
+
+
+def _workers_wrapper(func):
+    """
+    Wrapper to deal with setup-cleanup of workers outside a user function via a
+    ContextManager. It saves having to do the setup/tear down with within that
+    function, which can be messy.
+    """
+    @functools.wraps(func)
+    def inner(*args, **kwds):
+        kwargs = kwds.copy()
+        if 'workers' not in kwargs:
+            _workers = map
+        elif 'workers' in kwargs and kwargs['workers'] is None:
+            _workers = map
+        else:
+            _workers = kwargs['workers']
+
+        with MapWrapper(_workers) as mf:
+            kwargs['workers'] = mf
+            return func(*args, **kwargs)
+
+    return inner
+
+
+def rng_integers(gen, low, high=None, size=None, dtype='int64',
+                 endpoint=False):
+    """
+    Return random integers from low (inclusive) to high (exclusive), or if
+    endpoint=True, low (inclusive) to high (inclusive). Replaces
+    `RandomState.randint` (with endpoint=False) and
+    `RandomState.random_integers` (with endpoint=True).
+
+    Return random integers from the "discrete uniform" distribution of the
+    specified dtype. If high is None (the default), then results are from
+    0 to low.
+
+    Parameters
+    ----------
+    gen : {None, np.random.RandomState, np.random.Generator}
+        Random number generator. If None, then the np.random.RandomState
+        singleton is used.
+    low : int or array-like of ints
+        Lowest (signed) integers to be drawn from the distribution (unless
+        high=None, in which case this parameter is 0 and this value is used
+        for high).
+    high : int or array-like of ints
+        If provided, one above the largest (signed) integer to be drawn from
+        the distribution (see above for behavior if high=None). If array-like,
+        must contain integer values.
+    size : array-like of ints, optional
+        Output shape. If the given shape is, e.g., (m, n, k), then m * n * k
+        samples are drawn. Default is None, in which case a single value is
+        returned.
+    dtype : {str, dtype}, optional
+        Desired dtype of the result. All dtypes are determined by their name,
+        i.e., 'int64', 'int', etc, so byteorder is not available and a specific
+        precision may have different C types depending on the platform.
+        The default value is 'int64'.
+    endpoint : bool, optional
+        If True, sample from the interval [low, high] instead of the default
+        [low, high) Defaults to False.
+
+    Returns
+    -------
+    out: int or ndarray of ints
+        size-shaped array of random integers from the appropriate distribution,
+        or a single such random int if size not provided.
+    """
+    if isinstance(gen, Generator):
+        return gen.integers(low, high=high, size=size, dtype=dtype,
+                            endpoint=endpoint)
+    else:
+        if gen is None:
+            # default is RandomState singleton used by np.random.
+            gen = np.random.mtrand._rand
+        if endpoint:
+            # inclusive of endpoint
+            # remember that low and high can be arrays, so don't modify in
+            # place
+            if high is None:
+                return gen.randint(low + 1, size=size, dtype=dtype)
+            if high is not None:
+                return gen.randint(low, high=high + 1, size=size, dtype=dtype)
+
+        # exclusive
+        return gen.randint(low, high=high, size=size, dtype=dtype)
+
+
+@contextmanager
+def _fixed_default_rng(seed=1638083107694713882823079058616272161):
+    """Context with a fixed np.random.default_rng seed."""
+    orig_fun = np.random.default_rng
+    np.random.default_rng = lambda seed=seed: orig_fun(seed)
+    try:
+        yield
+    finally:
+        np.random.default_rng = orig_fun
+
+
+def _rng_html_rewrite(func):
+    """Rewrite the HTML rendering of ``np.random.default_rng``.
+
+    This is intended to decorate
+    ``numpydoc.docscrape_sphinx.SphinxDocString._str_examples``.
+
+    Examples are only run by Sphinx when there are plot involved. Even so,
+    it does not change the result values getting printed.
+    """
+    # hexadecimal or number seed, case-insensitive
+    pattern = re.compile(r'np.random.default_rng\((0x[0-9A-F]+|\d+)\)', re.I)
+
+    def _wrapped(*args, **kwargs):
+        res = func(*args, **kwargs)
+        lines = [
+            re.sub(pattern, 'np.random.default_rng()', line)
+            for line in res
+        ]
+        return lines
+
+    return _wrapped
+
+
+def _argmin(a, keepdims=False, axis=None):
+    """
+    argmin with a `keepdims` parameter.
+
+    See https://github.com/numpy/numpy/issues/8710
+
+    If axis is not None, a.shape[axis] must be greater than 0.
+    """
+    res = np.argmin(a, axis=axis)
+    if keepdims and axis is not None:
+        res = np.expand_dims(res, axis=axis)
+    return res
+
+
+def _first_nonnan(a, axis):
+    """
+    Return the first non-nan value along the given axis.
+
+    If a slice is all nan, nan is returned for that slice.
+
+    The shape of the return value corresponds to ``keepdims=True``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> nan = np.nan
+    >>> a = np.array([[ 3.,  3., nan,  3.],
+                      [ 1., nan,  2.,  4.],
+                      [nan, nan,  9., -1.],
+                      [nan,  5.,  4.,  3.],
+                      [ 2.,  2.,  2.,  2.],
+                      [nan, nan, nan, nan]])
+    >>> _first_nonnan(a, axis=0)
+    array([[3., 3., 2., 3.]])
+    >>> _first_nonnan(a, axis=1)
+    array([[ 3.],
+           [ 1.],
+           [ 9.],
+           [ 5.],
+           [ 2.],
+           [nan]])
+    """
+    k = _argmin(np.isnan(a), axis=axis, keepdims=True)
+    return np.take_along_axis(a, k, axis=axis)
+
+
+def _nan_allsame(a, axis, keepdims=False):
+    """
+    Determine if the values along an axis are all the same.
+
+    nan values are ignored.
+
+    `a` must be a numpy array.
+
+    `axis` is assumed to be normalized; that is, 0 <= axis < a.ndim.
+
+    For an axis of length 0, the result is True.  That is, we adopt the
+    convention that ``allsame([])`` is True. (There are no values in the
+    input that are different.)
+
+    `True` is returned for slices that are all nan--not because all the
+    values are the same, but because this is equivalent to ``allsame([])``.
+
+    Examples
+    --------
+    >>> from numpy import nan, array
+    >>> a = array([[ 3.,  3., nan,  3.],
+    ...            [ 1., nan,  2.,  4.],
+    ...            [nan, nan,  9., -1.],
+    ...            [nan,  5.,  4.,  3.],
+    ...            [ 2.,  2.,  2.,  2.],
+    ...            [nan, nan, nan, nan]])
+    >>> _nan_allsame(a, axis=1, keepdims=True)
+    array([[ True],
+           [False],
+           [False],
+           [False],
+           [ True],
+           [ True]])
+    """
+    if axis is None:
+        if a.size == 0:
+            return True
+        a = a.ravel()
+        axis = 0
+    else:
+        shp = a.shape
+        if shp[axis] == 0:
+            shp = shp[:axis] + (1,)*keepdims + shp[axis + 1:]
+            return np.full(shp, fill_value=True, dtype=bool)
+    a0 = _first_nonnan(a, axis=axis)
+    return ((a0 == a) | np.isnan(a)).all(axis=axis, keepdims=keepdims)
+
+
+def _contains_nan(
+    a: Array,
+    nan_policy: Literal["propagate", "raise", "omit"] = "propagate",
+    *,
+    xp_omit_okay: bool = False, 
+    xp: ModuleType | None = None,
+) -> Array | bool:
+    # Regarding `xp_omit_okay`: Temporarily, while `_axis_nan_policy` does not
+    # handle non-NumPy arrays, most functions that call `_contains_nan` want
+    # it to raise an error if `nan_policy='omit'` and `xp` is not `np`.
+    # Some functions support `nan_policy='omit'` natively, so setting this to
+    # `True` prevents the error from being raised.
+    policies = {"propagate", "raise", "omit"}
+    if nan_policy not in policies:
+        msg = f"nan_policy must be one of {policies}."
+        raise ValueError(msg)
+
+    if xp_size(a) == 0:
+        return False
+
+    if xp is None:
+        xp = array_namespace(a)
+
+    if xp.isdtype(a.dtype, "real floating"):
+        # Faster and less memory-intensive than xp.any(xp.isnan(a)), and unlike other
+        # reductions, `max`/`min` won't return NaN unless there is a NaN in the data.
+        contains_nan = xp.isnan(xp.max(a))
+    elif xp.isdtype(a.dtype, "complex floating"):
+        # Typically `real` and `imag` produce views; otherwise, `xp.any(xp.isnan(a))`
+        # would be more efficient.
+        contains_nan = xp.isnan(xp.max(xp.real(a))) | xp.isnan(xp.max(xp.imag(a)))
+    elif is_numpy(xp) and np.issubdtype(a.dtype, object):
+        contains_nan = False
+        for el in a.ravel():
+            # isnan doesn't work on non-numeric elements
+            if np.issubdtype(type(el), np.number) and np.isnan(el):
+                contains_nan = True
+                break
+    else:
+        # Only `object` and `inexact` arrays can have NaNs
+        return False
+
+    # The implicit call to bool(contains_nan) must happen after testing
+    # nan_policy to prevent lazy and device-bound xps from raising in the
+    # default policy='propagate' case.
+    if nan_policy == 'raise':
+        if is_lazy_array(a):
+            msg = "nan_policy='raise' is not supported for lazy arrays."
+            raise TypeError(msg)
+        if contains_nan:
+            msg = "The input contains nan values"
+            raise ValueError(msg)
+    elif nan_policy == 'omit' and not xp_omit_okay and not is_numpy(xp):
+        if is_lazy_array(a):
+            msg = "nan_policy='omit' is not supported for lazy arrays."
+            raise TypeError(msg)
+        if contains_nan:
+            msg = "nan_policy='omit' is incompatible with non-NumPy arrays."
+            raise ValueError(msg)
+
+    return contains_nan
+
+
+def _rename_parameter(old_name, new_name, dep_version=None):
+    """
+    Generate decorator for backward-compatible keyword renaming.
+
+    Apply the decorator generated by `_rename_parameter` to functions with a
+    recently renamed parameter to maintain backward-compatibility.
+
+    After decoration, the function behaves as follows:
+    If only the new parameter is passed into the function, behave as usual.
+    If only the old parameter is passed into the function (as a keyword), raise
+    a DeprecationWarning if `dep_version` is provided, and behave as usual
+    otherwise.
+    If both old and new parameters are passed into the function, raise a
+    DeprecationWarning if `dep_version` is provided, and raise the appropriate
+    TypeError (function got multiple values for argument).
+
+    Parameters
+    ----------
+    old_name : str
+        Old name of parameter
+    new_name : str
+        New name of parameter
+    dep_version : str, optional
+        Version of SciPy in which old parameter was deprecated in the format
+        'X.Y.Z'. If supplied, the deprecation message will indicate that
+        support for the old parameter will be removed in version 'X.Y+2.Z'
+
+    Notes
+    -----
+    Untested with functions that accept *args. Probably won't work as written.
+
+    """
+    def decorator(fun):
+        @functools.wraps(fun)
+        def wrapper(*args, **kwargs):
+            if old_name in kwargs:
+                if dep_version:
+                    end_version = dep_version.split('.')
+                    end_version[1] = str(int(end_version[1]) + 2)
+                    end_version = '.'.join(end_version)
+                    message = (f"Use of keyword argument `{old_name}` is "
+                               f"deprecated and replaced by `{new_name}`.  "
+                               f"Support for `{old_name}` will be removed "
+                               f"in SciPy {end_version}.")
+                    warnings.warn(message, DeprecationWarning, stacklevel=2)
+                if new_name in kwargs:
+                    message = (f"{fun.__name__}() got multiple values for "
+                               f"argument now known as `{new_name}`")
+                    raise TypeError(message)
+                kwargs[new_name] = kwargs.pop(old_name)
+            return fun(*args, **kwargs)
+        return wrapper
+    return decorator
+
+
+def _rng_spawn(rng, n_children):
+    # spawns independent RNGs from a parent RNG
+    bg = rng._bit_generator
+    ss = bg._seed_seq
+    child_rngs = [np.random.Generator(type(bg)(child_ss))
+                  for child_ss in ss.spawn(n_children)]
+    return child_rngs
+
+
+def _get_nan(*data, shape=(), xp=None):
+    xp = array_namespace(*data) if xp is None else xp
+    # Get NaN of appropriate dtype for data
+    dtype = xp_result_type(*data, force_floating=True, xp=xp)
+    device = xp_result_device(*data)
+    res = xp.full(shape, xp.nan, dtype=dtype, device=device)
+    if not shape:
+        res = res[()]
+    # whenever mdhaber/marray#89 is resolved, could just return `res`
+    return res.data if is_marray(xp) else res
+
+
+def normalize_axis_index(axis, ndim):
+    # Check if `axis` is in the correct range and normalize it
+    if axis < -ndim or axis >= ndim:
+        msg = f"axis {axis} is out of bounds for array of dimension {ndim}"
+        raise AxisError(msg)
+
+    if axis < 0:
+        axis = axis + ndim
+    return axis
+
+
+def _call_callback_maybe_halt(callback, res):
+    """Call wrapped callback; return True if algorithm should stop.
+
+    Parameters
+    ----------
+    callback : callable or None
+        A user-provided callback wrapped with `_wrap_callback`
+    res : OptimizeResult
+        Information about the current iterate
+
+    Returns
+    -------
+    halt : bool
+        True if minimization should stop
+
+    """
+    if callback is None:
+        return False
+    try:
+        callback(res)
+        return False
+    except StopIteration:
+        callback.stop_iteration = True
+        return True
+
+
+class _RichResult(dict):
+    """ Container for multiple outputs with pretty-printing """
+    def __getattr__(self, name):
+        try:
+            return self[name]
+        except KeyError as e:
+            raise AttributeError(name) from e
+
+    __setattr__ = dict.__setitem__  # type: ignore[assignment]
+    __delattr__ = dict.__delitem__  # type: ignore[assignment]
+
+    def __repr__(self):
+        order_keys = ['message', 'success', 'status', 'fun', 'funl', 'x', 'xl',
+                      'col_ind', 'nit', 'lower', 'upper', 'eqlin', 'ineqlin',
+                      'converged', 'flag', 'function_calls', 'iterations',
+                      'root']
+        order_keys = getattr(self, '_order_keys', order_keys)
+        # 'slack', 'con' are redundant with residuals
+        # 'crossover_nit' is probably not interesting to most users
+        omit_keys = {'slack', 'con', 'crossover_nit', '_order_keys'}
+
+        def key(item):
+            try:
+                return order_keys.index(item[0].lower())
+            except ValueError:  # item not in list
+                return np.inf
+
+        def omit_redundant(items):
+            for item in items:
+                if item[0] in omit_keys:
+                    continue
+                yield item
+
+        def item_sorter(d):
+            return sorted(omit_redundant(d.items()), key=key)
+
+        if self.keys():
+            return _dict_formatter(self, sorter=item_sorter)
+        else:
+            return self.__class__.__name__ + "()"
+
+    def __dir__(self):
+        return list(self.keys())
+
+
+def _indenter(s, n=0):
+    """
+    Ensures that lines after the first are indented by the specified amount
+    """
+    split = s.split("\n")
+    indent = " "*n
+    return ("\n" + indent).join(split)
+
+
+def _float_formatter_10(x):
+    """
+    Returns a string representation of a float with exactly ten characters
+    """
+    if np.isposinf(x):
+        return "       inf"
+    elif np.isneginf(x):
+        return "      -inf"
+    elif np.isnan(x):
+        return "       nan"
+    return np.format_float_scientific(x, precision=3, pad_left=2, unique=False)
+
+
+def _dict_formatter(d, n=0, mplus=1, sorter=None):
+    """
+    Pretty printer for dictionaries
+
+    `n` keeps track of the starting indentation;
+    lines are indented by this much after a line break.
+    `mplus` is additional left padding applied to keys
+    """
+    if isinstance(d, dict):
+        m = max(map(len, list(d.keys()))) + mplus  # width to print keys
+        s = '\n'.join([k.rjust(m) + ': ' +  # right justified, width m
+                       _indenter(_dict_formatter(v, m+n+2, 0, sorter), m+2)
+                       for k, v in sorter(d)])  # +2 for ': '
+    else:
+        # By default, NumPy arrays print with linewidth=76. `n` is
+        # the indent at which a line begins printing, so it is subtracted
+        # from the default to avoid exceeding 76 characters total.
+        # `edgeitems` is the number of elements to include before and after
+        # ellipses when arrays are not shown in full.
+        # `threshold` is the maximum number of elements for which an
+        # array is shown in full.
+        # These values tend to work well for use with OptimizeResult.
+        with np.printoptions(linewidth=76-n, edgeitems=2, threshold=12,
+                             formatter={'float_kind': _float_formatter_10}):
+            s = str(d)
+    return s
+
+
+_batch_note = """
+The documentation is written assuming array arguments are of specified
+"core" shapes. However, array argument(s) of this function may have additional
+"batch" dimensions prepended to the core shape. In this case, the array is treated
+as a batch of lower-dimensional slices; see :ref:`linalg_batch` for details.
+"""
+
+
+def _apply_over_batch(*argdefs):
+    """
+    Factory for decorator that applies a function over batched arguments.
+
+    Array arguments may have any number of core dimensions (typically 0,
+    1, or 2) and any broadcastable batch shapes. There may be any
+    number of array outputs of any number of dimensions. Assumptions
+    right now - which are satisfied by all functions of interest in `linalg` -
+    are that all array inputs are consecutive keyword or positional arguments,
+    and that the wrapped function returns either a single array or a tuple of
+    arrays. It's only as general as it needs to be right now - it can be extended.
+
+    Parameters
+    ----------
+    *argdefs : tuple of (str, int)
+        Definitions of array arguments: the keyword name of the argument, and
+        the number of core dimensions.
+
+    Example:
+    --------
+    `linalg.eig` accepts two matrices as the first two arguments `a` and `b`, where
+    `b` is optional, and returns one array or a tuple of arrays, depending on the
+    values of other positional or keyword arguments. To generate a wrapper that applies
+    the function over batches of `a` and optionally `b` :
+
+    >>> _apply_over_batch(('a', 2), ('b', 2))
+    """
+    names, ndims = list(zip(*argdefs))
+    n_arrays = len(names)
+
+    def decorator(f):
+        @functools.wraps(f)
+        def wrapper(*args, **kwargs):
+            args = list(args)
+
+            # Ensure all arrays in `arrays`, other arguments in `other_args`/`kwargs`
+            arrays, other_args = args[:n_arrays], args[n_arrays:]
+            for i, name in enumerate(names):
+                if name in kwargs:
+                    if i + 1 <= len(args):
+                        raise ValueError(f'{f.__name__}() got multiple values '
+                                         f'for argument `{name}`.')
+                    else:
+                        arrays.append(kwargs.pop(name))
+
+            # Determine core and batch shapes
+            batch_shapes = []
+            core_shapes = []
+            for i, (array, ndim) in enumerate(zip(arrays, ndims)):
+                array = None if array is None else np.asarray(array)
+                shape = () if array is None else array.shape
+
+                if ndim == "1|2":  # special case for `solve`, etc.
+                    ndim = 2 if array.ndim >= 2 else 1
+
+                arrays[i] = array
+                batch_shapes.append(shape[:-ndim] if ndim > 0 else shape)
+                core_shapes.append(shape[-ndim:] if ndim > 0 else ())
+
+            # Early exit if call is not batched
+            if not any(batch_shapes):
+                return f(*arrays, *other_args, **kwargs)
+
+            # Determine broadcasted batch shape
+            batch_shape = np.broadcast_shapes(*batch_shapes)  # Gives OK error message
+
+            # Broadcast arrays to appropriate shape
+            for i, (array, core_shape) in enumerate(zip(arrays, core_shapes)):
+                if array is None:
+                    continue
+                arrays[i] = np.broadcast_to(array, batch_shape + core_shape)
+
+            # Main loop
+            results = []
+            for index in np.ndindex(batch_shape):
+                result = f(*(array[index] for array in arrays), *other_args, **kwargs)
+                # Assume `result` is either a tuple or single array. This is easily
+                # generalized by allowing the contributor to pass an `unpack_result`
+                # callable to the decorator factory.
+                result = (result,) if not isinstance(result, tuple) else result
+                results.append(result)
+            results = list(zip(*results))
+
+            # Reshape results
+            for i, result in enumerate(results):
+                result = np.stack(result)
+                core_shape = result.shape[1:]
+                results[i] = np.reshape(result, batch_shape + core_shape)
+
+            # Assume `result` should be a single array if there is only one element or
+            # a `tuple` otherwise. This is easily generalized by allowing the
+            # contributor to pass an `pack_result` callable to the decorator factory.
+            return results[0] if len(results) == 1 else results
+
+        doc = FunctionDoc(wrapper)
+        doc['Extended Summary'].append(_batch_note.rstrip())
+        wrapper.__doc__ = str(doc).split("\n", 1)[1]  # remove signature
+
+        return wrapper
+    return decorator
+
+
+def np_vecdot(x1, x2, /, *, axis=-1):
+    # `np.vecdot` has advantages (e.g. see gh-22462), so let's use it when
+    # available. As functions are translated to Array API, `np_vecdot` can be
+    # replaced with `xp.vecdot`.
+    if np.__version__ > "2.0":
+        return np.vecdot(x1, x2, axis=axis)
+    else:
+        # of course there are other fancy ways of doing this (e.g. `einsum`)
+        # but let's keep it simple since it's temporary
+        return np.sum(x1 * x2, axis=axis)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/decorator.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/decorator.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea0122762ef2b580fc022d54ce46a1667237d064
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/decorator.py
@@ -0,0 +1,399 @@
+# #########################     LICENSE     ############################ #
+
+# Copyright (c) 2005-2015, Michele Simionato
+# All rights reserved.
+
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+
+#   Redistributions of source code must retain the above copyright
+#   notice, this list of conditions and the following disclaimer.
+#   Redistributions in bytecode form must reproduce the above copyright
+#   notice, this list of conditions and the following disclaimer in
+#   the documentation and/or other materials provided with the
+#   distribution.
+
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+# DAMAGE.
+
+"""
+Decorator module, see https://pypi.python.org/pypi/decorator
+for the documentation.
+"""
+import re
+import sys
+import inspect
+import operator
+import itertools
+import collections
+
+from inspect import getfullargspec
+
+__version__ = '4.0.5'
+
+
+def get_init(cls):
+    return cls.__init__
+
+
+# getargspec has been deprecated in Python 3.5
+ArgSpec = collections.namedtuple(
+    'ArgSpec', 'args varargs varkw defaults')
+
+
+def getargspec(f):
+    """A replacement for inspect.getargspec"""
+    spec = getfullargspec(f)
+    return ArgSpec(spec.args, spec.varargs, spec.varkw, spec.defaults)
+
+
+DEF = re.compile(r'\s*def\s*([_\w][_\w\d]*)\s*\(')
+
+
+# basic functionality
+class FunctionMaker:
+    """
+    An object with the ability to create functions with a given signature.
+    It has attributes name, doc, module, signature, defaults, dict, and
+    methods update and make.
+    """
+
+    # Atomic get-and-increment provided by the GIL
+    _compile_count = itertools.count()
+
+    def __init__(self, func=None, name=None, signature=None,
+                 defaults=None, doc=None, module=None, funcdict=None):
+        self.shortsignature = signature
+        if func:
+            # func can be a class or a callable, but not an instance method
+            self.name = func.__name__
+            if self.name == '':  # small hack for lambda functions
+                self.name = '_lambda_'
+            self.doc = func.__doc__
+            self.module = func.__module__
+            if inspect.isfunction(func):
+                argspec = getfullargspec(func)
+                self.annotations = getattr(func, '__annotations__', {})
+                for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs',
+                          'kwonlydefaults'):
+                    setattr(self, a, getattr(argspec, a))
+                for i, arg in enumerate(self.args):
+                    setattr(self, f'arg{i}', arg)
+                allargs = list(self.args)
+                allshortargs = list(self.args)
+                if self.varargs:
+                    allargs.append('*' + self.varargs)
+                    allshortargs.append('*' + self.varargs)
+                elif self.kwonlyargs:
+                    allargs.append('*')  # single star syntax
+                for a in self.kwonlyargs:
+                    allargs.append(f'{a}=None')
+                    allshortargs.append(f'{a}={a}')
+                if self.varkw:
+                    allargs.append('**' + self.varkw)
+                    allshortargs.append('**' + self.varkw)
+                self.signature = ', '.join(allargs)
+                self.shortsignature = ', '.join(allshortargs)
+                self.dict = func.__dict__.copy()
+        # func=None happens when decorating a caller
+        if name:
+            self.name = name
+        if signature is not None:
+            self.signature = signature
+        if defaults:
+            self.defaults = defaults
+        if doc:
+            self.doc = doc
+        if module:
+            self.module = module
+        if funcdict:
+            self.dict = funcdict
+        # check existence required attributes
+        assert hasattr(self, 'name')
+        if not hasattr(self, 'signature'):
+            raise TypeError(f'You are decorating a non-function: {func}')
+
+    def update(self, func, **kw):
+        "Update the signature of func with the data in self"
+        func.__name__ = self.name
+        func.__doc__ = getattr(self, 'doc', None)
+        func.__dict__ = getattr(self, 'dict', {})
+        func.__defaults__ = getattr(self, 'defaults', ())
+        func.__kwdefaults__ = getattr(self, 'kwonlydefaults', None)
+        func.__annotations__ = getattr(self, 'annotations', None)
+        try:
+            frame = sys._getframe(3)
+        except AttributeError:  # for IronPython and similar implementations
+            callermodule = '?'
+        else:
+            callermodule = frame.f_globals.get('__name__', '?')
+        func.__module__ = getattr(self, 'module', callermodule)
+        func.__dict__.update(kw)
+
+    def make(self, src_templ, evaldict=None, addsource=False, **attrs):
+        "Make a new function from a given template and update the signature"
+        src = src_templ % vars(self)  # expand name and signature
+        evaldict = evaldict or {}
+        mo = DEF.match(src)
+        if mo is None:
+            raise SyntaxError(f'not a valid function template\n{src}')
+        name = mo.group(1)  # extract the function name
+        names = set([name] + [arg.strip(' *') for arg in
+                              self.shortsignature.split(',')])
+        for n in names:
+            if n in ('_func_', '_call_'):
+                raise NameError(f'{n} is overridden in\n{src}')
+        if not src.endswith('\n'):  # add a newline just for safety
+            src += '\n'  # this is needed in old versions of Python
+
+        # Ensure each generated function has a unique filename for profilers
+        # (such as cProfile) that depend on the tuple of (,
+        # , ) being unique.
+        filename = f''
+        try:
+            code = compile(src, filename, 'single')
+            exec(code, evaldict)
+        except:  # noqa: E722
+            print('Error in generated code:', file=sys.stderr)
+            print(src, file=sys.stderr)
+            raise
+        func = evaldict[name]
+        if addsource:
+            attrs['__source__'] = src
+        self.update(func, **attrs)
+        return func
+
+    @classmethod
+    def create(cls, obj, body, evaldict, defaults=None,
+               doc=None, module=None, addsource=True, **attrs):
+        """
+        Create a function from the strings name, signature, and body.
+        evaldict is the evaluation dictionary. If addsource is true, an
+        attribute __source__ is added to the result. The attributes attrs
+        are added, if any.
+        """
+        if isinstance(obj, str):  # "name(signature)"
+            name, rest = obj.strip().split('(', 1)
+            signature = rest[:-1]  # strip a right parens
+            func = None
+        else:  # a function
+            name = None
+            signature = None
+            func = obj
+        self = cls(func, name, signature, defaults, doc, module)
+        ibody = '\n'.join('    ' + line for line in body.splitlines())
+        return self.make('def %(name)s(%(signature)s):\n' + ibody,
+                         evaldict, addsource, **attrs)
+
+
+def decorate(func, caller):
+    """
+    decorate(func, caller) decorates a function using a caller.
+    """
+    evaldict = func.__globals__.copy()
+    evaldict['_call_'] = caller
+    evaldict['_func_'] = func
+    fun = FunctionMaker.create(
+        func, "return _call_(_func_, %(shortsignature)s)",
+        evaldict, __wrapped__=func)
+    if hasattr(func, '__qualname__'):
+        fun.__qualname__ = func.__qualname__
+    return fun
+
+
+def decorator(caller, _func=None):
+    """decorator(caller) converts a caller function into a decorator"""
+    if _func is not None:  # return a decorated function
+        # this is obsolete behavior; you should use decorate instead
+        return decorate(_func, caller)
+    # else return a decorator function
+    if inspect.isclass(caller):
+        name = caller.__name__.lower()
+        callerfunc = get_init(caller)
+        doc = (f'decorator({caller.__name__}) converts functions/generators into ' 
+               f'factories of {caller.__name__} objects')
+    elif inspect.isfunction(caller):
+        if caller.__name__ == '':
+            name = '_lambda_'
+        else:
+            name = caller.__name__
+        callerfunc = caller
+        doc = caller.__doc__
+    else:  # assume caller is an object with a __call__ method
+        name = caller.__class__.__name__.lower()
+        callerfunc = caller.__call__.__func__
+        doc = caller.__call__.__doc__
+    evaldict = callerfunc.__globals__.copy()
+    evaldict['_call_'] = caller
+    evaldict['_decorate_'] = decorate
+    return FunctionMaker.create(
+        f'{name}(func)', 'return _decorate_(func, _call_)',
+        evaldict, doc=doc, module=caller.__module__,
+        __wrapped__=caller)
+
+
+# ####################### contextmanager ####################### #
+
+try:  # Python >= 3.2
+    from contextlib import _GeneratorContextManager
+except ImportError:  # Python >= 2.5
+    from contextlib import GeneratorContextManager as _GeneratorContextManager
+
+
+class ContextManager(_GeneratorContextManager):
+    def __call__(self, func):
+        """Context manager decorator"""
+        return FunctionMaker.create(
+            func, "with _self_: return _func_(%(shortsignature)s)",
+            dict(_self_=self, _func_=func), __wrapped__=func)
+
+
+init = getfullargspec(_GeneratorContextManager.__init__)
+n_args = len(init.args)
+if n_args == 2 and not init.varargs:  # (self, genobj) Python 2.7
+    def __init__(self, g, *a, **k):
+        return _GeneratorContextManager.__init__(self, g(*a, **k))
+    ContextManager.__init__ = __init__
+elif n_args == 2 and init.varargs:  # (self, gen, *a, **k) Python 3.4
+    pass
+elif n_args == 4:  # (self, gen, args, kwds) Python 3.5
+    def __init__(self, g, *a, **k):
+        return _GeneratorContextManager.__init__(self, g, a, k)
+    ContextManager.__init__ = __init__
+
+contextmanager = decorator(ContextManager)
+
+
+# ############################ dispatch_on ############################ #
+
+def append(a, vancestors):
+    """
+    Append ``a`` to the list of the virtual ancestors, unless it is already
+    included.
+    """
+    add = True
+    for j, va in enumerate(vancestors):
+        if issubclass(va, a):
+            add = False
+            break
+        if issubclass(a, va):
+            vancestors[j] = a
+            add = False
+    if add:
+        vancestors.append(a)
+
+
+# inspired from simplegeneric by P.J. Eby and functools.singledispatch
+def dispatch_on(*dispatch_args):
+    """
+    Factory of decorators turning a function into a generic function
+    dispatching on the given arguments.
+    """
+    assert dispatch_args, 'No dispatch args passed'
+    dispatch_str = f"({', '.join(dispatch_args)},)"
+
+    def check(arguments, wrong=operator.ne, msg=''):
+        """Make sure one passes the expected number of arguments"""
+        if wrong(len(arguments), len(dispatch_args)):
+            raise TypeError(f'Expected {len(dispatch_args)} arguments, '
+                            'got {len(arguments)}{msg}')
+
+    def gen_func_dec(func):
+        """Decorator turning a function into a generic function"""
+
+        # first check the dispatch arguments
+        argset = set(getfullargspec(func).args)
+        if not set(dispatch_args) <= argset:
+            raise NameError(f'Unknown dispatch arguments {dispatch_str}')
+
+        typemap = {}
+
+        def vancestors(*types):
+            """
+            Get a list of sets of virtual ancestors for the given types
+            """
+            check(types)
+            ras = [[] for _ in range(len(dispatch_args))]
+            for types_ in typemap:
+                for t, type_, ra in zip(types, types_, ras):
+                    if issubclass(t, type_) and type_ not in t.__mro__:
+                        append(type_, ra)
+            return [set(ra) for ra in ras]
+
+        def ancestors(*types):
+            """
+            Get a list of virtual MROs, one for each type
+            """
+            check(types)
+            lists = []
+            for t, vas in zip(types, vancestors(*types)):
+                n_vas = len(vas)
+                if n_vas > 1:
+                    raise RuntimeError(
+                        f'Ambiguous dispatch for {t}: {vas}')
+                elif n_vas == 1:
+                    va, = vas
+                    mro = type('t', (t, va), {}).__mro__[1:]
+                else:
+                    mro = t.__mro__
+                lists.append(mro[:-1])  # discard t and object
+            return lists
+
+        def register(*types):
+            """
+            Decorator to register an implementation for the given types
+            """
+            check(types)
+
+            def dec(f):
+                check(getfullargspec(f).args, operator.lt, ' in ' + f.__name__)
+                typemap[types] = f
+                return f
+            return dec
+
+        def dispatch_info(*types):
+            """
+            An utility to introspect the dispatch algorithm
+            """
+            check(types)
+            lst = [tuple(a.__name__ for a in anc)
+                   for anc in itertools.product(*ancestors(*types))]
+            return lst
+
+        def _dispatch(dispatch_args, *args, **kw):
+            types = tuple(type(arg) for arg in dispatch_args)
+            try:  # fast path
+                f = typemap[types]
+            except KeyError:
+                pass
+            else:
+                return f(*args, **kw)
+            combinations = itertools.product(*ancestors(*types))
+            next(combinations)  # the first one has been already tried
+            for types_ in combinations:
+                f = typemap.get(types_)
+                if f is not None:
+                    return f(*args, **kw)
+
+            # else call the default implementation
+            return func(*args, **kw)
+
+        return FunctionMaker.create(
+            func, f'return _f_({dispatch_str}, %%(shortsignature)s)',
+            dict(_f_=_dispatch), register=register, default=func,
+            typemap=typemap, vancestors=vancestors, ancestors=ancestors,
+            dispatch_info=dispatch_info, __wrapped__=func)
+
+    gen_func_dec.__name__ = 'dispatch_on' + dispatch_str
+    return gen_func_dec
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/deprecation.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/deprecation.py
new file mode 100644
index 0000000000000000000000000000000000000000..82a6ef8f39ba764b46fdc01de9281cdbf72f4736
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/deprecation.py
@@ -0,0 +1,274 @@
+from inspect import Parameter, signature
+import functools
+import warnings
+from importlib import import_module
+from scipy._lib._docscrape import FunctionDoc
+
+
+__all__ = ["_deprecated"]
+
+
+# Object to use as default value for arguments to be deprecated. This should
+# be used over 'None' as the user could parse 'None' as a positional argument
+_NoValue = object()
+
+def _sub_module_deprecation(*, sub_package, module, private_modules, all,
+                            attribute, correct_module=None, dep_version="1.16.0"):
+    """Helper function for deprecating modules that are public but were
+    intended to be private.
+
+    Parameters
+    ----------
+    sub_package : str
+        Subpackage the module belongs to eg. stats
+    module : str
+        Public but intended private module to deprecate
+    private_modules : list
+        Private replacement(s) for `module`; should contain the
+        content of ``all``, possibly spread over several modules.
+    all : list
+        ``__all__`` belonging to `module`
+    attribute : str
+        The attribute in `module` being accessed
+    correct_module : str, optional
+        Module in `sub_package` that `attribute` should be imported from.
+        Default is that `attribute` should be imported from ``scipy.sub_package``.
+    dep_version : str, optional
+        Version in which deprecated attributes will be removed.
+    """
+    if correct_module is not None:
+        correct_import = f"scipy.{sub_package}.{correct_module}"
+    else:
+        correct_import = f"scipy.{sub_package}"
+
+    if attribute not in all:
+        raise AttributeError(
+            f"`scipy.{sub_package}.{module}` has no attribute `{attribute}`; "
+            f"furthermore, `scipy.{sub_package}.{module}` is deprecated "
+            f"and will be removed in SciPy 2.0.0."
+        )
+
+    attr = getattr(import_module(correct_import), attribute, None)
+
+    if attr is not None:
+        message = (
+            f"Please import `{attribute}` from the `{correct_import}` namespace; "
+            f"the `scipy.{sub_package}.{module}` namespace is deprecated "
+            f"and will be removed in SciPy 2.0.0."
+        )
+    else:
+        message = (
+            f"`scipy.{sub_package}.{module}.{attribute}` is deprecated along with "
+            f"the `scipy.{sub_package}.{module}` namespace. "
+            f"`scipy.{sub_package}.{module}.{attribute}` will be removed "
+            f"in SciPy {dep_version}, and the `scipy.{sub_package}.{module}` namespace "
+            f"will be removed in SciPy 2.0.0."
+        )
+
+    warnings.warn(message, category=DeprecationWarning, stacklevel=3)
+
+    for module in private_modules:
+        try:
+            return getattr(import_module(f"scipy.{sub_package}.{module}"), attribute)
+        except AttributeError as e:
+            # still raise an error if the attribute isn't in any of the expected
+            # private modules
+            if module == private_modules[-1]:
+                raise e
+            continue
+    
+
+def _deprecated(msg, stacklevel=2):
+    """Deprecate a function by emitting a warning on use."""
+    def wrap(fun):
+        if isinstance(fun, type):
+            warnings.warn(
+                f"Trying to deprecate class {fun!r}",
+                category=RuntimeWarning, stacklevel=2)
+            return fun
+
+        @functools.wraps(fun)
+        def call(*args, **kwargs):
+            warnings.warn(msg, category=DeprecationWarning,
+                          stacklevel=stacklevel)
+            return fun(*args, **kwargs)
+        call.__doc__ = fun.__doc__
+        return call
+
+    return wrap
+
+
+class _DeprecationHelperStr:
+    """
+    Helper class used by deprecate_cython_api
+    """
+    def __init__(self, content, message):
+        self._content = content
+        self._message = message
+
+    def __hash__(self):
+        return hash(self._content)
+
+    def __eq__(self, other):
+        res = (self._content == other)
+        if res:
+            warnings.warn(self._message, category=DeprecationWarning,
+                          stacklevel=2)
+        return res
+
+
+def deprecate_cython_api(module, routine_name, new_name=None, message=None):
+    """
+    Deprecate an exported cdef function in a public Cython API module.
+
+    Only functions can be deprecated; typedefs etc. cannot.
+
+    Parameters
+    ----------
+    module : module
+        Public Cython API module (e.g. scipy.linalg.cython_blas).
+    routine_name : str
+        Name of the routine to deprecate. May also be a fused-type
+        routine (in which case its all specializations are deprecated).
+    new_name : str
+        New name to include in the deprecation warning message
+    message : str
+        Additional text in the deprecation warning message
+
+    Examples
+    --------
+    Usually, this function would be used in the top-level of the
+    module ``.pyx`` file:
+
+    >>> from scipy._lib.deprecation import deprecate_cython_api
+    >>> import scipy.linalg.cython_blas as mod
+    >>> deprecate_cython_api(mod, "dgemm", "dgemm_new",
+    ...                      message="Deprecated in Scipy 1.5.0")
+    >>> del deprecate_cython_api, mod
+
+    After this, Cython modules that use the deprecated function emit a
+    deprecation warning when they are imported.
+
+    """
+    old_name = f"{module.__name__}.{routine_name}"
+
+    if new_name is None:
+        depdoc = f"`{old_name}` is deprecated!"
+    else:
+        depdoc = f"`{old_name}` is deprecated, use `{new_name}` instead!"
+
+    if message is not None:
+        depdoc += "\n" + message
+
+    d = module.__pyx_capi__
+
+    # Check if the function is a fused-type function with a mangled name
+    j = 0
+    has_fused = False
+    while True:
+        fused_name = f"__pyx_fuse_{j}{routine_name}"
+        if fused_name in d:
+            has_fused = True
+            d[_DeprecationHelperStr(fused_name, depdoc)] = d.pop(fused_name)
+            j += 1
+        else:
+            break
+
+    # If not, apply deprecation to the named routine
+    if not has_fused:
+        d[_DeprecationHelperStr(routine_name, depdoc)] = d.pop(routine_name)
+
+
+# taken from scikit-learn, see
+# https://github.com/scikit-learn/scikit-learn/blob/1.3.0/sklearn/utils/validation.py#L38
+def _deprecate_positional_args(func=None, *, version=None,
+                               deprecated_args=None, custom_message=""):
+    """Decorator for methods that issues warnings for positional arguments.
+
+    Using the keyword-only argument syntax in pep 3102, arguments after the
+    * will issue a warning when passed as a positional argument.
+
+    Parameters
+    ----------
+    func : callable, default=None
+        Function to check arguments on.
+    version : callable, default=None
+        The version when positional arguments will result in error.
+    deprecated_args : set of str, optional
+        Arguments to deprecate - whether passed by position or keyword.
+    custom_message : str, optional
+        Custom message to add to deprecation warning and documentation.
+    """
+    if version is None:
+        msg = "Need to specify a version where signature will be changed"
+        raise ValueError(msg)
+
+    deprecated_args = set() if deprecated_args is None else set(deprecated_args)
+
+    def _inner_deprecate_positional_args(f):
+        sig = signature(f)
+        kwonly_args = []
+        all_args = []
+
+        for name, param in sig.parameters.items():
+            if param.kind == Parameter.POSITIONAL_OR_KEYWORD:
+                all_args.append(name)
+            elif param.kind == Parameter.KEYWORD_ONLY:
+                kwonly_args.append(name)
+
+        def warn_deprecated_args(kwargs):
+            intersection = deprecated_args.intersection(kwargs)
+            if intersection:
+                message = (f"Arguments {intersection} are deprecated, whether passed "
+                           "by position or keyword. They will be removed in SciPy "
+                           f"{version}. ")
+                message += custom_message
+                warnings.warn(message, category=DeprecationWarning, stacklevel=3)
+
+        @functools.wraps(f)
+        def inner_f(*args, **kwargs):
+
+            extra_args = len(args) - len(all_args)
+            if extra_args <= 0:
+                warn_deprecated_args(kwargs)
+                return f(*args, **kwargs)
+
+            # extra_args > 0
+            kwonly_extra_args = set(kwonly_args[:extra_args]) - deprecated_args
+            args_msg = ", ".join(kwonly_extra_args)
+            warnings.warn(
+                (
+                    f"You are passing as positional arguments: {args_msg}. "
+                    "Please change your invocation to use keyword arguments. "
+                    f"From SciPy {version}, passing these as positional "
+                    "arguments will result in an error."
+                ),
+                DeprecationWarning,
+                stacklevel=2,
+            )
+            kwargs.update(zip(sig.parameters, args))
+            warn_deprecated_args(kwargs)
+            return f(**kwargs)
+
+        doc = FunctionDoc(inner_f)
+        kwonly_extra_args = set(kwonly_args) - deprecated_args
+        admonition = f"""
+.. deprecated:: {version}
+    Use of argument(s) ``{kwonly_extra_args}`` by position is deprecated; beginning in 
+    SciPy {version}, these will be keyword-only. """
+        if deprecated_args:
+            admonition += (f"Argument(s) ``{deprecated_args}`` are deprecated, whether "
+                           "passed by position or keyword; they will be removed in "
+                           f"SciPy {version}. ")
+        admonition += custom_message
+        doc['Extended Summary'] += [admonition]
+
+        doc = str(doc).split("\n", 1)[1]  # remove signature
+        inner_f.__doc__ = str(doc)
+
+        return inner_f
+
+    if func is not None:
+        return _inner_deprecate_positional_args(func)
+
+    return _inner_deprecate_positional_args
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/doccer.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/doccer.py
new file mode 100644
index 0000000000000000000000000000000000000000..7fd8fef0b4c49a60fdd71427d134528aee00a216
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/doccer.py
@@ -0,0 +1,366 @@
+"""Utilities to allow inserting docstring fragments for common
+parameters into function and method docstrings."""
+
+from collections.abc import Callable, Iterable, Mapping
+from typing import Protocol, TypeVar
+import sys
+
+__all__ = [
+    "docformat",
+    "inherit_docstring_from",
+    "indentcount_lines",
+    "filldoc",
+    "unindent_dict",
+    "unindent_string",
+    "extend_notes_in_docstring",
+    "replace_notes_in_docstring",
+    "doc_replace",
+]
+
+_F = TypeVar("_F", bound=Callable[..., object])
+
+
+class Decorator(Protocol):
+    """A decorator of a function."""
+
+    def __call__(self, func: _F, /) -> _F: ...
+
+
+def docformat(docstring: str, docdict: Mapping[str, str] | None = None) -> str:
+    """Fill a function docstring from variables in dictionary.
+
+    Adapt the indent of the inserted docs
+
+    Parameters
+    ----------
+    docstring : str
+        A docstring from a function, possibly with dict formatting strings.
+    docdict : dict[str, str], optional
+        A dictionary with keys that match the dict formatting strings
+        and values that are docstring fragments to be inserted. The
+        indentation of the inserted docstrings is set to match the
+        minimum indentation of the ``docstring`` by adding this
+        indentation to all lines of the inserted string, except the
+        first.
+
+    Returns
+    -------
+    docstring : str
+        string with requested ``docdict`` strings inserted.
+
+    Examples
+    --------
+    >>> docformat(' Test string with %(value)s', {'value':'inserted value'})
+    ' Test string with inserted value'
+    >>> docstring = 'First line\\n    Second line\\n    %(value)s'
+    >>> inserted_string = "indented\\nstring"
+    >>> docdict = {'value': inserted_string}
+    >>> docformat(docstring, docdict)
+    'First line\\n    Second line\\n    indented\\n    string'
+    """
+    if not docstring:
+        return docstring
+    if docdict is None:
+        docdict = {}
+    if not docdict:
+        return docstring
+    lines = docstring.expandtabs().splitlines()
+    # Find the minimum indent of the main docstring, after first line
+    if len(lines) < 2:
+        icount = 0
+    else:
+        icount = indentcount_lines(lines[1:])
+    indent = " " * icount
+    # Insert this indent to dictionary docstrings
+    indented = {}
+    for name, dstr in docdict.items():
+        lines = dstr.expandtabs().splitlines()
+        indented[name] = ("\n" + indent).join(lines)
+    return docstring % indented
+
+
+def inherit_docstring_from(cls: object) -> Decorator:
+    """This decorator modifies the decorated function's docstring by
+    replacing occurrences of '%(super)s' with the docstring of the
+    method of the same name from the class `cls`.
+
+    If the decorated method has no docstring, it is simply given the
+    docstring of `cls`s method.
+
+    Parameters
+    ----------
+    cls : type or object
+        A class with a method with the same name as the decorated method.
+        The docstring of the method in this class replaces '%(super)s' in the
+        docstring of the decorated method.
+
+    Returns
+    -------
+    decfunc : function
+        The decorator function that modifies the __doc__ attribute
+        of its argument.
+
+    Examples
+    --------
+    In the following, the docstring for Bar.func created using the
+    docstring of `Foo.func`.
+
+    >>> class Foo:
+    ...     def func(self):
+    ...         '''Do something useful.'''
+    ...         return
+    ...
+    >>> class Bar(Foo):
+    ...     @inherit_docstring_from(Foo)
+    ...     def func(self):
+    ...         '''%(super)s
+    ...         Do it fast.
+    ...         '''
+    ...         return
+    ...
+    >>> b = Bar()
+    >>> b.func.__doc__
+    'Do something useful.\n        Do it fast.\n        '
+    """
+
+    def _doc(func: _F) -> _F:
+        cls_docstring = getattr(cls, func.__name__).__doc__
+        func_docstring = func.__doc__
+        if func_docstring is None:
+            func.__doc__ = cls_docstring
+        else:
+            new_docstring = func_docstring % dict(super=cls_docstring)
+            func.__doc__ = new_docstring
+        return func
+
+    return _doc
+
+
+def extend_notes_in_docstring(cls: object, notes: str) -> Decorator:
+    """This decorator replaces the decorated function's docstring
+    with the docstring from corresponding method in `cls`.
+    It extends the 'Notes' section of that docstring to include
+    the given `notes`.
+
+    Parameters
+    ----------
+    cls : type or object
+        A class with a method with the same name as the decorated method.
+        The docstring of the method in this class replaces the docstring of the
+        decorated method.
+    notes : str
+        Additional notes to append to the 'Notes' section of the docstring.
+
+    Returns
+    -------
+    decfunc : function
+        The decorator function that modifies the __doc__ attribute
+        of its argument.
+    """
+
+    def _doc(func: _F) -> _F:
+        cls_docstring = getattr(cls, func.__name__).__doc__
+        # If python is called with -OO option,
+        # there is no docstring
+        if cls_docstring is None:
+            return func
+        end_of_notes = cls_docstring.find("        References\n")
+        if end_of_notes == -1:
+            end_of_notes = cls_docstring.find("        Examples\n")
+            if end_of_notes == -1:
+                end_of_notes = len(cls_docstring)
+        func.__doc__ = (
+            cls_docstring[:end_of_notes] + notes + cls_docstring[end_of_notes:]
+        )
+        return func
+
+    return _doc
+
+
+def replace_notes_in_docstring(cls: object, notes: str) -> Decorator:
+    """This decorator replaces the decorated function's docstring
+    with the docstring from corresponding method in `cls`.
+    It replaces the 'Notes' section of that docstring with
+    the given `notes`.
+
+    Parameters
+    ----------
+    cls : type or object
+        A class with a method with the same name as the decorated method.
+        The docstring of the method in this class replaces the docstring of the
+        decorated method.
+    notes : str
+        The notes to replace the existing 'Notes' section with.
+
+    Returns
+    -------
+    decfunc : function
+        The decorator function that modifies the __doc__ attribute
+        of its argument.
+    """
+
+    def _doc(func: _F) -> _F:
+        cls_docstring = getattr(cls, func.__name__).__doc__
+        notes_header = "        Notes\n        -----\n"
+        # If python is called with -OO option,
+        # there is no docstring
+        if cls_docstring is None:
+            return func
+        start_of_notes = cls_docstring.find(notes_header)
+        end_of_notes = cls_docstring.find("        References\n")
+        if end_of_notes == -1:
+            end_of_notes = cls_docstring.find("        Examples\n")
+            if end_of_notes == -1:
+                end_of_notes = len(cls_docstring)
+        func.__doc__ = (
+            cls_docstring[: start_of_notes + len(notes_header)]
+            + notes
+            + cls_docstring[end_of_notes:]
+        )
+        return func
+
+    return _doc
+
+
+def indentcount_lines(lines: Iterable[str]) -> int:
+    """Minimum indent for all lines in line list
+
+    Parameters
+    ----------
+    lines : Iterable[str]
+        The lines to find the minimum indent of.
+
+    Returns
+    -------
+    indent : int
+        The minimum indent.
+
+
+    Examples
+    --------
+    >>> lines = [' one', '  two', '   three']
+    >>> indentcount_lines(lines)
+    1
+    >>> lines = []
+    >>> indentcount_lines(lines)
+    0
+    >>> lines = [' one']
+    >>> indentcount_lines(lines)
+    1
+    >>> indentcount_lines(['    '])
+    0
+    """
+    indentno = sys.maxsize
+    for line in lines:
+        stripped = line.lstrip()
+        if stripped:
+            indentno = min(indentno, len(line) - len(stripped))
+    if indentno == sys.maxsize:
+        return 0
+    return indentno
+
+
+def filldoc(docdict: Mapping[str, str], unindent_params: bool = True) -> Decorator:
+    """Return docstring decorator using docdict variable dictionary.
+
+    Parameters
+    ----------
+    docdict : dict[str, str]
+        A dictionary containing name, docstring fragment pairs.
+    unindent_params : bool, optional
+        If True, strip common indentation from all parameters in docdict.
+        Default is False.
+
+    Returns
+    -------
+    decfunc : function
+        The decorator function that applies dictionary to its
+        argument's __doc__ attribute.
+    """
+    if unindent_params:
+        docdict = unindent_dict(docdict)
+
+    def decorate(func: _F) -> _F:
+        # __doc__ may be None for optimized Python (-OO)
+        doc = func.__doc__ or ""
+        func.__doc__ = docformat(doc, docdict)
+        return func
+
+    return decorate
+
+
+def unindent_dict(docdict: Mapping[str, str]) -> dict[str, str]:
+    """Unindent all strings in a docdict.
+
+    Parameters
+    ----------
+    docdict : dict[str, str]
+        A dictionary with string values to unindent.
+
+    Returns
+    -------
+    docdict : dict[str, str]
+        The `docdict` dictionary but each of its string values are unindented.
+    """
+    can_dict: dict[str, str] = {}
+    for name, dstr in docdict.items():
+        can_dict[name] = unindent_string(dstr)
+    return can_dict
+
+
+def unindent_string(docstring: str) -> str:
+    """Set docstring to minimum indent for all lines, including first.
+
+    Parameters
+    ----------
+    docstring : str
+        The input docstring to unindent.
+
+    Returns
+    -------
+    docstring : str
+        The unindented docstring.
+
+    Examples
+    --------
+    >>> unindent_string(' two')
+    'two'
+    >>> unindent_string('  two\\n   three')
+    'two\\n three'
+    """
+    lines = docstring.expandtabs().splitlines()
+    icount = indentcount_lines(lines)
+    if icount == 0:
+        return docstring
+    return "\n".join([line[icount:] for line in lines])
+
+
+def doc_replace(obj: object, oldval: str, newval: str) -> Decorator:
+    """Decorator to take the docstring from obj, with oldval replaced by newval
+
+    Equivalent to ``func.__doc__ = obj.__doc__.replace(oldval, newval)``
+
+    Parameters
+    ----------
+    obj : object
+        A class or object whose docstring will be used as the basis for the
+        replacement operation.
+    oldval : str
+        The string to search for in the docstring.
+    newval : str
+        The string to replace `oldval` with in the docstring.
+
+    Returns
+    -------
+    decfunc : function
+        A decorator function that replaces occurrences of `oldval` with `newval`
+        in the docstring of the decorated function.
+    """
+    # __doc__ may be None for optimized Python (-OO)
+    doc = (obj.__doc__ or "").replace(oldval, newval)
+
+    def inner(func: _F) -> _F:
+        func.__doc__ = doc
+        return func
+
+    return inner
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/messagestream.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/messagestream.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..0e6161a24338eef4309811cefbee3e6a36ad8b4e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/messagestream.cpython-312-x86_64-linux-gnu.so differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/uarray.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/uarray.py
new file mode 100644
index 0000000000000000000000000000000000000000..b29fc713efb3e836cc179ac87ce41f87b51870ef
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/_lib/uarray.py
@@ -0,0 +1,31 @@
+"""`uarray` provides functions for generating multimethods that dispatch to
+multiple different backends
+
+This should be imported, rather than `_uarray` so that an installed version could
+be used instead, if available. This means that users can call
+`uarray.set_backend` directly instead of going through SciPy.
+
+"""
+
+
+# Prefer an installed version of uarray, if available
+try:
+    import uarray as _uarray
+except ImportError:
+    _has_uarray = False
+else:
+    from scipy._lib._pep440 import Version as _Version
+
+    _has_uarray = _Version(_uarray.__version__) >= _Version("0.8")
+    del _uarray
+    del _Version
+
+
+if _has_uarray:
+    from uarray import *  # noqa: F403
+    from uarray import _Function
+else:
+    from ._uarray import *  # noqa: F403
+    from ._uarray import _Function  # noqa: F401
+
+del _has_uarray
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b7784969a573d05cc6b98ee9066c42720156d1d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/__init__.py
@@ -0,0 +1,31 @@
+"""
+=========================================
+Clustering package (:mod:`scipy.cluster`)
+=========================================
+
+.. currentmodule:: scipy.cluster
+
+Clustering algorithms are useful in information theory, target detection,
+communications, compression, and other areas. The `vq` module only
+supports vector quantization and the k-means algorithms.
+
+The `hierarchy` module provides functions for hierarchical and
+agglomerative clustering.  Its features include generating hierarchical
+clusters from distance matrices,
+calculating statistics on clusters, cutting linkages
+to generate flat clusters, and visualizing clusters with dendrograms.
+
+.. toctree::
+   :maxdepth: 1
+
+   cluster.vq
+   cluster.hierarchy
+
+"""
+__all__ = ['vq', 'hierarchy']
+
+from . import vq, hierarchy
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/_hierarchy.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/_hierarchy.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..76bdcdf0c660d5965d27e3ed408447171bb52926
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/_hierarchy.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:06d7a371d04ebd6ebffb169e63c62b47c3647e97548f012b942d1cbcb32c1903
+size 300088
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/_optimal_leaf_ordering.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/_optimal_leaf_ordering.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..fc4683c356f9f714e33e17dff0cf1515120be86e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/_optimal_leaf_ordering.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a07f9f1b9bce7a39f0150194dc8bcacae4f8f53c47af21f9f672d38ed05c67c4
+size 195304
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/_vq.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/_vq.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..102914a1898d547cc1b00ccf5031ffb4a985d282
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/_vq.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:54a856896fc3b62956b45b0ec7c29b5fc5e338beb5dc078952e1950aaec24d43
+size 129872
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a7d212355db23023789f0006c5bf6d00b4078d6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/hierarchy.py
@@ -0,0 +1,4348 @@
+"""
+Hierarchical clustering (:mod:`scipy.cluster.hierarchy`)
+========================================================
+
+.. currentmodule:: scipy.cluster.hierarchy
+
+These functions cut hierarchical clusterings into flat clusterings
+or find the roots of the forest formed by a cut by providing the flat
+cluster ids of each observation.
+
+.. autosummary::
+   :toctree: generated/
+
+   fcluster
+   fclusterdata
+   leaders
+
+These are routines for agglomerative clustering.
+
+.. autosummary::
+   :toctree: generated/
+
+   linkage
+   single
+   complete
+   average
+   weighted
+   centroid
+   median
+   ward
+
+These routines compute statistics on hierarchies.
+
+.. autosummary::
+   :toctree: generated/
+
+   cophenet
+   from_mlab_linkage
+   inconsistent
+   maxinconsts
+   maxdists
+   maxRstat
+   to_mlab_linkage
+
+Routines for visualizing flat clusters.
+
+.. autosummary::
+   :toctree: generated/
+
+   dendrogram
+
+These are data structures and routines for representing hierarchies as
+tree objects.
+
+.. autosummary::
+   :toctree: generated/
+
+   ClusterNode
+   leaves_list
+   to_tree
+   cut_tree
+   optimal_leaf_ordering
+
+These are predicates for checking the validity of linkage and
+inconsistency matrices as well as for checking isomorphism of two
+flat cluster assignments.
+
+.. autosummary::
+   :toctree: generated/
+
+   is_valid_im
+   is_valid_linkage
+   is_isomorphic
+   is_monotonic
+   correspond
+   num_obs_linkage
+
+Utility routines for plotting:
+
+.. autosummary::
+   :toctree: generated/
+
+   set_link_color_palette
+
+Utility classes:
+
+.. autosummary::
+   :toctree: generated/
+
+   DisjointSet -- data structure for incremental connectivity queries
+
+"""
+# Copyright (C) Damian Eads, 2007-2008. New BSD License.
+
+# hierarchy.py (derived from cluster.py, http://scipy-cluster.googlecode.com)
+#
+# Author: Damian Eads
+# Date:   September 22, 2007
+#
+# Copyright (c) 2007, 2008, Damian Eads
+#
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#   - Redistributions of source code must retain the above
+#     copyright notice, this list of conditions and the
+#     following disclaimer.
+#   - Redistributions in binary form must reproduce the above copyright
+#     notice, this list of conditions and the following disclaimer
+#     in the documentation and/or other materials provided with the
+#     distribution.
+#   - Neither the name of the author nor the names of its
+#     contributors may be used to endorse or promote products derived
+#     from this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+import warnings
+import bisect
+from collections import deque
+
+import numpy as np
+from . import _hierarchy, _optimal_leaf_ordering
+import scipy.spatial.distance as distance
+from scipy._lib._array_api import (_asarray, array_namespace, is_dask,
+                                   is_lazy_array, xp_capabilities, xp_copy)
+from scipy._lib._disjoint_set import DisjointSet
+import scipy._lib.array_api_extra as xpx
+
+
+_LINKAGE_METHODS = {'single': 0, 'complete': 1, 'average': 2, 'centroid': 3,
+                    'median': 4, 'ward': 5, 'weighted': 6}
+_EUCLIDEAN_METHODS = ('centroid', 'median', 'ward')
+
+__all__ = ['ClusterNode', 'DisjointSet', 'average', 'centroid', 'complete',
+           'cophenet', 'correspond', 'cut_tree', 'dendrogram', 'fcluster',
+           'fclusterdata', 'from_mlab_linkage', 'inconsistent',
+           'is_isomorphic', 'is_monotonic', 'is_valid_im', 'is_valid_linkage',
+           'leaders', 'leaves_list', 'linkage', 'maxRstat', 'maxdists',
+           'maxinconsts', 'median', 'num_obs_linkage', 'optimal_leaf_ordering',
+           'set_link_color_palette', 'single', 'to_mlab_linkage', 'to_tree',
+           'ward', 'weighted']
+
+
+class ClusterWarning(UserWarning):
+    pass
+
+
+def _warning(s):
+    warnings.warn(f'scipy.cluster: {s}', ClusterWarning, stacklevel=3)
+
+
+def int_floor(arr, xp):
+    # array_api_strict is strict about not allowing `int()` on a float array.
+    # That's typically not needed, here it is - so explicitly convert
+    return int(xp.asarray(arr, dtype=xp.int64))
+
+
+lazy_cython = xp_capabilities(
+    cpu_only=True, reason="Cython code",
+    warnings=[("dask.array", "merges chunks")])
+
+
+@lazy_cython
+def single(y):
+    """
+    Perform single/min/nearest linkage on the condensed distance matrix ``y``.
+
+    Parameters
+    ----------
+    y : ndarray
+        The upper triangular of the distance matrix. The result of
+        ``pdist`` is returned in this form.
+
+    Returns
+    -------
+    Z : ndarray
+        The linkage matrix.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import single, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = single(y)
+    >>> Z
+    array([[ 0.,  1.,  1.,  2.],
+           [ 2., 12.,  1.,  3.],
+           [ 3.,  4.,  1.,  2.],
+           [ 5., 14.,  1.,  3.],
+           [ 6.,  7.,  1.,  2.],
+           [ 8., 16.,  1.,  3.],
+           [ 9., 10.,  1.,  2.],
+           [11., 18.,  1.,  3.],
+           [13., 15.,  2.,  6.],
+           [17., 20.,  2.,  9.],
+           [19., 21.,  2., 12.]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 7,  8,  9, 10, 11, 12,  4,  5,  6,  1,  2,  3], dtype=int32)
+    >>> fcluster(Z, 1, criterion='distance')
+    array([3, 3, 3, 4, 4, 4, 2, 2, 2, 1, 1, 1], dtype=int32)
+    >>> fcluster(Z, 2, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+    """
+    return linkage(y, method='single', metric='euclidean')
+
+
+@lazy_cython
+def complete(y):
+    """
+    Perform complete/max/farthest point linkage on a condensed distance matrix.
+
+    Parameters
+    ----------
+    y : ndarray
+        The upper triangular of the distance matrix. The result of
+        ``pdist`` is returned in this form.
+
+    Returns
+    -------
+    Z : ndarray
+        A linkage matrix containing the hierarchical clustering. See
+        the `linkage` function documentation for more information
+        on its structure.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import complete, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = complete(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.41421356,  3.        ],
+           [ 5.        , 13.        ,  1.41421356,  3.        ],
+           [ 8.        , 14.        ,  1.41421356,  3.        ],
+           [11.        , 15.        ,  1.41421356,  3.        ],
+           [16.        , 17.        ,  4.12310563,  6.        ],
+           [18.        , 19.        ,  4.12310563,  6.        ],
+           [20.        , 21.        ,  5.65685425, 12.        ]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12], dtype=int32)
+    >>> fcluster(Z, 1.5, criterion='distance')
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+    >>> fcluster(Z, 4.5, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2], dtype=int32)
+    >>> fcluster(Z, 6, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+    """
+    return linkage(y, method='complete', metric='euclidean')
+
+
+@lazy_cython
+def average(y):
+    """
+    Perform average/UPGMA linkage on a condensed distance matrix.
+
+    Parameters
+    ----------
+    y : ndarray
+        The upper triangular of the distance matrix. The result of
+        ``pdist`` is returned in this form.
+
+    Returns
+    -------
+    Z : ndarray
+        A linkage matrix containing the hierarchical clustering. See
+        `linkage` for more information on its structure.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import average, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = average(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.20710678,  3.        ],
+           [ 5.        , 13.        ,  1.20710678,  3.        ],
+           [ 8.        , 14.        ,  1.20710678,  3.        ],
+           [11.        , 15.        ,  1.20710678,  3.        ],
+           [16.        , 17.        ,  3.39675184,  6.        ],
+           [18.        , 19.        ,  3.39675184,  6.        ],
+           [20.        , 21.        ,  4.09206523, 12.        ]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12], dtype=int32)
+    >>> fcluster(Z, 1.5, criterion='distance')
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+    >>> fcluster(Z, 4, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2], dtype=int32)
+    >>> fcluster(Z, 6, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+
+    """
+    return linkage(y, method='average', metric='euclidean')
+
+
+@lazy_cython
+def weighted(y):
+    """
+    Perform weighted/WPGMA linkage on the condensed distance matrix.
+
+    See `linkage` for more information on the return
+    structure and algorithm.
+
+    Parameters
+    ----------
+    y : ndarray
+        The upper triangular of the distance matrix. The result of
+        ``pdist`` is returned in this form.
+
+    Returns
+    -------
+    Z : ndarray
+        A linkage matrix containing the hierarchical clustering. See
+        `linkage` for more information on its structure.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import weighted, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = weighted(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 11.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.20710678,  3.        ],
+           [ 8.        , 13.        ,  1.20710678,  3.        ],
+           [ 5.        , 14.        ,  1.20710678,  3.        ],
+           [10.        , 15.        ,  1.20710678,  3.        ],
+           [18.        , 19.        ,  3.05595762,  6.        ],
+           [16.        , 17.        ,  3.32379407,  6.        ],
+           [20.        , 21.        ,  4.06357713, 12.        ]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 7,  8,  9,  1,  2,  3, 10, 11, 12,  4,  6,  5], dtype=int32)
+    >>> fcluster(Z, 1.5, criterion='distance')
+    array([3, 3, 3, 1, 1, 1, 4, 4, 4, 2, 2, 2], dtype=int32)
+    >>> fcluster(Z, 4, criterion='distance')
+    array([2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1], dtype=int32)
+    >>> fcluster(Z, 6, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+
+    """
+    return linkage(y, method='weighted', metric='euclidean')
+
+
+@lazy_cython
+def centroid(y):
+    """
+    Perform centroid/UPGMC linkage.
+
+    See `linkage` for more information on the input matrix,
+    return structure, and algorithm.
+
+    The following are common calling conventions:
+
+    1. ``Z = centroid(y)``
+
+       Performs centroid/UPGMC linkage on the condensed distance
+       matrix ``y``.
+
+    2. ``Z = centroid(X)``
+
+       Performs centroid/UPGMC linkage on the observation matrix ``X``
+       using Euclidean distance as the distance metric.
+
+    Parameters
+    ----------
+    y : ndarray
+        A condensed distance matrix. A condensed
+        distance matrix is a flat array containing the upper
+        triangular of the distance matrix. This is the form that
+        ``pdist`` returns. Alternatively, a collection of
+        m observation vectors in n dimensions may be passed as
+        an m by n array.
+
+    Returns
+    -------
+    Z : ndarray
+        A linkage matrix containing the hierarchical clustering. See
+        the `linkage` function documentation for more information
+        on its structure.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import centroid, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = centroid(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.11803399,  3.        ],
+           [ 5.        , 13.        ,  1.11803399,  3.        ],
+           [ 8.        , 15.        ,  1.11803399,  3.        ],
+           [11.        , 14.        ,  1.11803399,  3.        ],
+           [18.        , 19.        ,  3.33333333,  6.        ],
+           [16.        , 17.        ,  3.33333333,  6.        ],
+           [20.        , 21.        ,  3.33333333, 12.        ]]) # may vary
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 7,  8,  9, 10, 11, 12,  1,  2,  3,  4,  5,  6], dtype=int32) # may vary
+    >>> fcluster(Z, 1.1, criterion='distance')
+    array([5, 5, 6, 7, 7, 8, 1, 1, 2, 3, 3, 4], dtype=int32) # may vary
+    >>> fcluster(Z, 2, criterion='distance')
+    array([3, 3, 3, 4, 4, 4, 1, 1, 1, 2, 2, 2], dtype=int32) # may vary
+    >>> fcluster(Z, 4, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+
+    """
+    return linkage(y, method='centroid', metric='euclidean')
+
+
+@lazy_cython
+def median(y):
+    """
+    Perform median/WPGMC linkage.
+
+    See `linkage` for more information on the return structure
+    and algorithm.
+
+     The following are common calling conventions:
+
+     1. ``Z = median(y)``
+
+        Performs median/WPGMC linkage on the condensed distance matrix
+        ``y``.  See ``linkage`` for more information on the return
+        structure and algorithm.
+
+     2. ``Z = median(X)``
+
+        Performs median/WPGMC linkage on the observation matrix ``X``
+        using Euclidean distance as the distance metric. See `linkage`
+        for more information on the return structure and algorithm.
+
+    Parameters
+    ----------
+    y : ndarray
+        A condensed distance matrix. A condensed
+        distance matrix is a flat array containing the upper
+        triangular of the distance matrix. This is the form that
+        ``pdist`` returns.  Alternatively, a collection of
+        m observation vectors in n dimensions may be passed as
+        an m by n array.
+
+    Returns
+    -------
+    Z : ndarray
+        The hierarchical clustering encoded as a linkage matrix.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import median, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = median(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.11803399,  3.        ],
+           [ 5.        , 13.        ,  1.11803399,  3.        ],
+           [ 8.        , 15.        ,  1.11803399,  3.        ],
+           [11.        , 14.        ,  1.11803399,  3.        ],
+           [18.        , 19.        ,  3.        ,  6.        ],
+           [16.        , 17.        ,  3.5       ,  6.        ],
+           [20.        , 21.        ,  3.25      , 12.        ]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 7,  8,  9, 10, 11, 12,  1,  2,  3,  4,  5,  6], dtype=int32)
+    >>> fcluster(Z, 1.1, criterion='distance')
+    array([5, 5, 6, 7, 7, 8, 1, 1, 2, 3, 3, 4], dtype=int32)
+    >>> fcluster(Z, 2, criterion='distance')
+    array([3, 3, 3, 4, 4, 4, 1, 1, 1, 2, 2, 2], dtype=int32)
+    >>> fcluster(Z, 4, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+
+    """
+    return linkage(y, method='median', metric='euclidean')
+
+
+@lazy_cython
+def ward(y):
+    """
+    Perform Ward's linkage on a condensed distance matrix.
+
+    See `linkage` for more information on the return structure
+    and algorithm.
+
+    The following are common calling conventions:
+
+    1. ``Z = ward(y)``
+       Performs Ward's linkage on the condensed distance matrix ``y``.
+
+    2. ``Z = ward(X)``
+       Performs Ward's linkage on the observation matrix ``X`` using
+       Euclidean distance as the distance metric.
+
+    Parameters
+    ----------
+    y : ndarray
+        A condensed distance matrix. A condensed
+        distance matrix is a flat array containing the upper
+        triangular of the distance matrix. This is the form that
+        ``pdist`` returns.  Alternatively, a collection of
+        m observation vectors in n dimensions may be passed as
+        an m by n array.
+
+    Returns
+    -------
+    Z : ndarray
+        The hierarchical clustering encoded as a linkage matrix. See
+        `linkage` for more information on the return structure and
+        algorithm.
+
+    See Also
+    --------
+    linkage : for advanced creation of hierarchical clusterings.
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    First, we need a toy dataset to play with::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    Then, we get a condensed distance matrix from this dataset:
+
+    >>> y = pdist(X)
+
+    Finally, we can perform the clustering:
+
+    >>> Z = ward(y)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+
+    The linkage matrix ``Z`` represents a dendrogram - see
+    `scipy.cluster.hierarchy.linkage` for a detailed explanation of its
+    contents.
+
+    We can use `scipy.cluster.hierarchy.fcluster` to see to which cluster
+    each initial point would belong given a distance threshold:
+
+    >>> fcluster(Z, 0.9, criterion='distance')
+    array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12], dtype=int32)
+    >>> fcluster(Z, 1.1, criterion='distance')
+    array([1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8], dtype=int32)
+    >>> fcluster(Z, 3, criterion='distance')
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+    >>> fcluster(Z, 9, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    Also, `scipy.cluster.hierarchy.dendrogram` can be used to generate a
+    plot of the dendrogram.
+
+    """
+    return linkage(y, method='ward', metric='euclidean')
+
+
+@lazy_cython
+def linkage(y, method='single', metric='euclidean', optimal_ordering=False):
+    """
+    Perform hierarchical/agglomerative clustering.
+
+    The input y may be either a 1-D condensed distance matrix
+    or a 2-D array of observation vectors.
+
+    If y is a 1-D condensed distance matrix,
+    then y must be a :math:`\\binom{n}{2}` sized
+    vector, where n is the number of original observations paired
+    in the distance matrix. The behavior of this function is very
+    similar to the MATLAB linkage function.
+
+    A :math:`(n-1)` by 4 matrix ``Z`` is returned. At the
+    :math:`i`-th iteration, clusters with indices ``Z[i, 0]`` and
+    ``Z[i, 1]`` are combined to form cluster :math:`n + i`. A
+    cluster with an index less than :math:`n` corresponds to one of
+    the :math:`n` original observations. The distance between
+    clusters ``Z[i, 0]`` and ``Z[i, 1]`` is given by ``Z[i, 2]``. The
+    fourth value ``Z[i, 3]`` represents the number of original
+    observations in the newly formed cluster.
+
+    The following linkage methods are used to compute the distance
+    :math:`d(s, t)` between two clusters :math:`s` and
+    :math:`t`. The algorithm begins with a forest of clusters that
+    have yet to be used in the hierarchy being formed. When two
+    clusters :math:`s` and :math:`t` from this forest are combined
+    into a single cluster :math:`u`, :math:`s` and :math:`t` are
+    removed from the forest, and :math:`u` is added to the
+    forest. When only one cluster remains in the forest, the algorithm
+    stops, and this cluster becomes the root.
+
+    A distance matrix is maintained at each iteration. The ``d[i,j]``
+    entry corresponds to the distance between cluster :math:`i` and
+    :math:`j` in the original forest.
+
+    At each iteration, the algorithm must update the distance matrix
+    to reflect the distance of the newly formed cluster u with the
+    remaining clusters in the forest.
+
+    Suppose there are :math:`|u|` original observations
+    :math:`u[0], \\ldots, u[|u|-1]` in cluster :math:`u` and
+    :math:`|v|` original objects :math:`v[0], \\ldots, v[|v|-1]` in
+    cluster :math:`v`. Recall, :math:`s` and :math:`t` are
+    combined to form cluster :math:`u`. Let :math:`v` be any
+    remaining cluster in the forest that is not :math:`u`.
+
+    The following are methods for calculating the distance between the
+    newly formed cluster :math:`u` and each :math:`v`.
+
+      * method='single' assigns
+
+        .. math::
+           d(u,v) = \\min(dist(u[i],v[j]))
+
+        for all points :math:`i` in cluster :math:`u` and
+        :math:`j` in cluster :math:`v`. This is also known as the
+        Nearest Point Algorithm.
+
+      * method='complete' assigns
+
+        .. math::
+           d(u, v) = \\max(dist(u[i],v[j]))
+
+        for all points :math:`i` in cluster u and :math:`j` in
+        cluster :math:`v`. This is also known by the Farthest Point
+        Algorithm or Voor Hees Algorithm.
+
+      * method='average' assigns
+
+        .. math::
+           d(u,v) = \\sum_{ij} \\frac{d(u[i], v[j])}
+                                   {(|u|*|v|)}
+
+        for all points :math:`i` and :math:`j` where :math:`|u|`
+        and :math:`|v|` are the cardinalities of clusters :math:`u`
+        and :math:`v`, respectively. This is also called the UPGMA
+        algorithm.
+
+      * method='weighted' assigns
+
+        .. math::
+           d(u,v) = (dist(s,v) + dist(t,v))/2
+
+        where cluster u was formed with cluster s and t and v
+        is a remaining cluster in the forest (also called WPGMA).
+
+      * method='centroid' assigns
+
+        .. math::
+           dist(s,t) = ||c_s-c_t||_2
+
+        where :math:`c_s` and :math:`c_t` are the centroids of
+        clusters :math:`s` and :math:`t`, respectively. When two
+        clusters :math:`s` and :math:`t` are combined into a new
+        cluster :math:`u`, the new centroid is computed over all the
+        original objects in clusters :math:`s` and :math:`t`. The
+        distance then becomes the Euclidean distance between the
+        centroid of :math:`u` and the centroid of a remaining cluster
+        :math:`v` in the forest. This is also known as the UPGMC
+        algorithm.
+
+      * method='median' assigns :math:`d(s,t)` like the ``centroid``
+        method. When two clusters :math:`s` and :math:`t` are combined
+        into a new cluster :math:`u`, the average of centroids s and t
+        give the new centroid :math:`u`. This is also known as the
+        WPGMC algorithm.
+
+      * method='ward' uses the Ward variance minimization algorithm.
+        The new entry :math:`d(u,v)` is computed as follows,
+
+        .. math::
+
+           d(u,v) = \\sqrt{\\frac{|v|+|s|}
+                               {T}d(v,s)^2
+                        + \\frac{|v|+|t|}
+                               {T}d(v,t)^2
+                        - \\frac{|v|}
+                               {T}d(s,t)^2}
+
+        where :math:`u` is the newly joined cluster consisting of
+        clusters :math:`s` and :math:`t`, :math:`v` is an unused
+        cluster in the forest, :math:`T=|v|+|s|+|t|`, and
+        :math:`|*|` is the cardinality of its argument. This is also
+        known as the incremental algorithm.
+
+    Warning: When the minimum distance pair in the forest is chosen, there
+    may be two or more pairs with the same minimum distance. This
+    implementation may choose a different minimum than the MATLAB
+    version.
+
+    Parameters
+    ----------
+    y : ndarray
+        A condensed distance matrix. A condensed distance matrix
+        is a flat array containing the upper triangular of the distance matrix.
+        This is the form that ``pdist`` returns. Alternatively, a collection of
+        :math:`m` observation vectors in :math:`n` dimensions may be passed as
+        an :math:`m` by :math:`n` array. All elements of the condensed distance
+        matrix must be finite, i.e., no NaNs or infs.
+    method : str, optional
+        The linkage algorithm to use. See the ``Linkage Methods`` section below
+        for full descriptions.
+    metric : str or function, optional
+        The distance metric to use in the case that y is a collection of
+        observation vectors; ignored otherwise. See the ``pdist``
+        function for a list of valid distance metrics. A custom distance
+        function can also be used.
+    optimal_ordering : bool, optional
+        If True, the linkage matrix will be reordered so that the distance
+        between successive leaves is minimal. This results in a more intuitive
+        tree structure when the data are visualized. defaults to False, because
+        this algorithm can be slow, particularly on large datasets [2]_. See
+        also the `optimal_leaf_ordering` function.
+
+        .. versionadded:: 1.0.0
+
+    Returns
+    -------
+    Z : ndarray
+        The hierarchical clustering encoded as a linkage matrix.
+
+    Notes
+    -----
+    1. For method 'single', an optimized algorithm based on minimum spanning
+       tree is implemented. It has time complexity :math:`O(n^2)`.
+       For methods 'complete', 'average', 'weighted' and 'ward', an algorithm
+       called nearest-neighbors chain is implemented. It also has time
+       complexity :math:`O(n^2)`.
+       For other methods, a naive algorithm is implemented with :math:`O(n^3)`
+       time complexity.
+       All algorithms use :math:`O(n^2)` memory.
+       Refer to [1]_ for details about the algorithms.
+    2. Methods 'centroid', 'median', and 'ward' are correctly defined only if
+       Euclidean pairwise metric is used. If `y` is passed as precomputed
+       pairwise distances, then it is the user's responsibility to assure that
+       these distances are in fact Euclidean, otherwise the produced result
+       will be incorrect.
+
+    See Also
+    --------
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    References
+    ----------
+    .. [1] Daniel Mullner, "Modern hierarchical, agglomerative clustering
+           algorithms", :arXiv:`1109.2378v1`.
+    .. [2] Ziv Bar-Joseph, David K. Gifford, Tommi S. Jaakkola, "Fast optimal
+           leaf ordering for hierarchical clustering", 2001. Bioinformatics
+           :doi:`10.1093/bioinformatics/17.suppl_1.S22`
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import dendrogram, linkage
+    >>> from matplotlib import pyplot as plt
+    >>> X = [[i] for i in [2, 8, 0, 4, 1, 9, 9, 0]]
+
+    >>> Z = linkage(X, 'ward')
+    >>> fig = plt.figure(figsize=(25, 10))
+    >>> dn = dendrogram(Z)
+
+    >>> Z = linkage(X, 'single')
+    >>> fig = plt.figure(figsize=(25, 10))
+    >>> dn = dendrogram(Z)
+    >>> plt.show()
+    """
+    xp = array_namespace(y)
+    y = _asarray(y, order='C', dtype=xp.float64, xp=xp)
+    lazy = is_lazy_array(y)
+
+    if method not in _LINKAGE_METHODS:
+        raise ValueError(f"Invalid method: {method}")
+
+    if method in _EUCLIDEAN_METHODS and metric != 'euclidean' and y.ndim == 2:
+        msg = f"`method={method}` requires the distance metric to be Euclidean"
+        raise ValueError(msg)
+
+    if y.ndim == 1:
+        distance.is_valid_y(y, throw=True, name='y')
+    elif y.ndim == 2:
+        if (not lazy and y.shape[0] == y.shape[1]
+            and xp.all(xpx.isclose(xp.linalg.diagonal(y), 0))
+            and xp.all(y >= 0) and xp.all(xpx.isclose(y, y.T))):
+            warnings.warn('The symmetric non-negative hollow observation '
+                          'matrix looks suspiciously like an uncondensed '
+                          'distance matrix',
+                          ClusterWarning, stacklevel=2)
+        y = distance.pdist(y, metric)
+    else:
+        raise ValueError("`y` must be 1 or 2 dimensional.")
+
+    if not lazy and not xp.all(xp.isfinite(y)):
+        raise ValueError("The condensed distance matrix must contain only "
+                         "finite values.")
+
+    n = distance.num_obs_y(y)
+    method_code = _LINKAGE_METHODS[method]
+
+    def cy_linkage(y, validate):
+        if validate and not np.all(np.isfinite(y)):
+            raise ValueError("The condensed distance matrix must contain only "
+                            "finite values.")            
+
+        if method == 'single':
+            return _hierarchy.mst_single_linkage(y, n)
+        elif method in ('complete', 'average', 'weighted', 'ward'):
+            return _hierarchy.nn_chain(y, n, method_code)
+        else:
+            return _hierarchy.fast_linkage(y, n, method_code)
+
+    result = xpx.lazy_apply(cy_linkage, y, validate=lazy,
+                            shape=(n - 1, 4), dtype=xp.float64,
+                            as_numpy=True, xp=xp)
+
+    if optimal_ordering:
+        return optimal_leaf_ordering(result, y)
+    else:
+        return result
+
+
+class ClusterNode:
+    """
+    A tree node class for representing a cluster.
+
+    Leaf nodes correspond to original observations, while non-leaf nodes
+    correspond to non-singleton clusters.
+
+    The `to_tree` function converts a matrix returned by the linkage
+    function into an easy-to-use tree representation.
+
+    All parameter names are also attributes.
+
+    Parameters
+    ----------
+    id : int
+        The node id.
+    left : ClusterNode instance, optional
+        The left child tree node.
+    right : ClusterNode instance, optional
+        The right child tree node.
+    dist : float, optional
+        Distance for this cluster in the linkage matrix.
+    count : int, optional
+        The number of samples in this cluster.
+
+    See Also
+    --------
+    to_tree : for converting a linkage matrix ``Z`` into a tree object.
+
+    """
+
+    def __init__(self, id, left=None, right=None, dist=0.0, count=1):
+        if id < 0:
+            raise ValueError('The id must be non-negative.')
+        if dist < 0:
+            raise ValueError('The distance must be non-negative.')
+        if (left is None and right is not None) or \
+           (left is not None and right is None):
+            raise ValueError('Only full or proper binary trees are permitted.'
+                             '  This node has one child.')
+        if count < 1:
+            raise ValueError('A cluster must contain at least one original '
+                             'observation.')
+        self.id = id
+        self.left = left
+        self.right = right
+        self.dist = dist
+        if self.left is None:
+            self.count = count
+        else:
+            self.count = left.count + right.count
+
+    def __lt__(self, node):
+        if not isinstance(node, ClusterNode):
+            raise ValueError("Can't compare ClusterNode "
+                             f"to type {type(node)}")
+        return self.dist < node.dist
+
+    def __gt__(self, node):
+        if not isinstance(node, ClusterNode):
+            raise ValueError("Can't compare ClusterNode "
+                             f"to type {type(node)}")
+        return self.dist > node.dist
+
+    def __eq__(self, node):
+        if not isinstance(node, ClusterNode):
+            raise ValueError("Can't compare ClusterNode "
+                             f"to type {type(node)}")
+        return self.dist == node.dist
+
+    def get_id(self):
+        """
+        The identifier of the target node.
+
+        For ``0 <= i < n``, `i` corresponds to original observation i.
+        For ``n <= i < 2n-1``, `i` corresponds to non-singleton cluster formed
+        at iteration ``i-n``.
+
+        Returns
+        -------
+        id : int
+            The identifier of the target node.
+
+        """
+        return self.id
+
+    def get_count(self):
+        """
+        The number of leaf nodes (original observations) belonging to
+        the cluster node nd. If the target node is a leaf, 1 is
+        returned.
+
+        Returns
+        -------
+        get_count : int
+            The number of leaf nodes below the target node.
+
+        """
+        return self.count
+
+    def get_left(self):
+        """
+        Return a reference to the left child tree object.
+
+        Returns
+        -------
+        left : ClusterNode
+            The left child of the target node. If the node is a leaf,
+            None is returned.
+
+        """
+        return self.left
+
+    def get_right(self):
+        """
+        Return a reference to the right child tree object.
+
+        Returns
+        -------
+        right : ClusterNode
+            The left child of the target node. If the node is a leaf,
+            None is returned.
+
+        """
+        return self.right
+
+    def is_leaf(self):
+        """
+        Return True if the target node is a leaf.
+
+        Returns
+        -------
+        leafness : bool
+            True if the target node is a leaf node.
+
+        """
+        return self.left is None
+
+    def pre_order(self, func=(lambda x: x.id)):
+        """
+        Perform pre-order traversal without recursive function calls.
+
+        When a leaf node is first encountered, ``func`` is called with
+        the leaf node as its argument, and its result is appended to
+        the list.
+
+        For example, the statement::
+
+           ids = root.pre_order(lambda x: x.id)
+
+        returns a list of the node ids corresponding to the leaf nodes
+        of the tree as they appear from left to right.
+
+        Parameters
+        ----------
+        func : function
+            Applied to each leaf ClusterNode object in the pre-order traversal.
+            Given the ``i``-th leaf node in the pre-order traversal ``n[i]``,
+            the result of ``func(n[i])`` is stored in ``L[i]``. If not
+            provided, the index of the original observation to which the node
+            corresponds is used.
+
+        Returns
+        -------
+        L : list
+            The pre-order traversal.
+
+        """
+        # Do a preorder traversal, caching the result. To avoid having to do
+        # recursion, we'll store the previous index we've visited in a vector.
+        n = self.count
+
+        curNode = [None] * (2 * n)
+        lvisited = set()
+        rvisited = set()
+        curNode[0] = self
+        k = 0
+        preorder = []
+        while k >= 0:
+            nd = curNode[k]
+            ndid = nd.id
+            if nd.is_leaf():
+                preorder.append(func(nd))
+                k = k - 1
+            else:
+                if ndid not in lvisited:
+                    curNode[k + 1] = nd.left
+                    lvisited.add(ndid)
+                    k = k + 1
+                elif ndid not in rvisited:
+                    curNode[k + 1] = nd.right
+                    rvisited.add(ndid)
+                    k = k + 1
+                # If we've visited the left and right of this non-leaf
+                # node already, go up in the tree.
+                else:
+                    k = k - 1
+
+        return preorder
+
+
+_cnode_bare = ClusterNode(0)
+_cnode_type = type(ClusterNode)
+
+
+def _order_cluster_tree(Z):
+    """
+    Return clustering nodes in bottom-up order by distance.
+
+    Parameters
+    ----------
+    Z : scipy.cluster.linkage array
+        The linkage matrix.
+
+    Returns
+    -------
+    nodes : list
+        A list of ClusterNode objects.
+    """
+    q = deque()
+    tree = to_tree(Z)
+    q.append(tree)
+    nodes = []
+
+    while q:
+        node = q.popleft()
+        if not node.is_leaf():
+            bisect.insort_left(nodes, node)
+            q.append(node.get_right())
+            q.append(node.get_left())
+    return nodes
+
+
+@xp_capabilities(np_only=True, reason="non-standard indexing")
+def cut_tree(Z, n_clusters=None, height=None):
+    """
+    Given a linkage matrix Z, return the cut tree.
+
+    Parameters
+    ----------
+    Z : scipy.cluster.linkage array
+        The linkage matrix.
+    n_clusters : array_like, optional
+        Number of clusters in the tree at the cut point.
+    height : array_like, optional
+        The height at which to cut the tree. Only possible for ultrametric
+        trees.
+
+    Returns
+    -------
+    cutree : array
+        An array indicating group membership at each agglomeration step. I.e.,
+        for a full cut tree, in the first column each data point is in its own
+        cluster. At the next step, two nodes are merged. Finally, all
+        singleton and non-singleton clusters are in one group. If `n_clusters`
+        or `height` are given, the columns correspond to the columns of
+        `n_clusters` or `height`.
+
+    Examples
+    --------
+    >>> from scipy import cluster
+    >>> import numpy as np
+    >>> from numpy.random import default_rng
+    >>> rng = default_rng()
+    >>> X = rng.random((50, 4))
+    >>> Z = cluster.hierarchy.ward(X)
+    >>> cutree = cluster.hierarchy.cut_tree(Z, n_clusters=[5, 10])
+    >>> cutree[:10]
+    array([[0, 0],
+           [1, 1],
+           [2, 2],
+           [3, 3],
+           [3, 4],
+           [2, 2],
+           [0, 0],
+           [1, 5],
+           [3, 6],
+           [4, 7]])  # random
+
+    """
+    xp = array_namespace(Z)
+    nobs = num_obs_linkage(Z)
+    nodes = _order_cluster_tree(Z)
+
+    if height is not None and n_clusters is not None:
+        raise ValueError("At least one of either height or n_clusters "
+                         "must be None")
+    elif height is None and n_clusters is None:  # return the full cut tree
+        cols_idx = xp.arange(nobs)
+    elif height is not None:
+        height = xp.asarray(height)
+        heights = xp.asarray([x.dist for x in nodes])
+        cols_idx = xp.searchsorted(heights, height)
+    else:
+        n_clusters = xp.asarray(n_clusters)
+        cols_idx = nobs - xp.searchsorted(xp.arange(nobs), n_clusters)
+
+    try:
+        n_cols = len(cols_idx)
+    except TypeError:  # scalar
+        n_cols = 1
+        cols_idx = xp.asarray([cols_idx])
+
+    groups = xp.zeros((n_cols, nobs), dtype=xp.int64)
+    last_group = xp.arange(nobs)
+    if 0 in cols_idx:
+        groups[0] = last_group
+
+    for i, node in enumerate(nodes):
+        idx = node.pre_order()
+        this_group = xp_copy(last_group, xp=xp)
+        # TODO ARRAY_API complex indexing not supported
+        this_group[idx] = xp.min(last_group[idx])
+        this_group[this_group > xp.max(last_group[idx])] -= 1
+        if i + 1 in cols_idx:
+            groups[np.nonzero(i + 1 == cols_idx)[0]] = this_group
+        last_group = this_group
+
+    return groups.T
+
+
+@xp_capabilities(jax_jit=False, allow_dask_compute=True)
+def to_tree(Z, rd=False):
+    """
+    Convert a linkage matrix into an easy-to-use tree object.
+
+    The reference to the root `ClusterNode` object is returned (by default).
+
+    Each `ClusterNode` object has a ``left``, ``right``, ``dist``, ``id``,
+    and ``count`` attribute. The left and right attributes point to
+    ClusterNode objects that were combined to generate the cluster.
+    If both are None then the `ClusterNode` object is a leaf node, its count
+    must be 1, and its distance is meaningless but set to 0.
+
+    *Note: This function is provided for the convenience of the library
+    user. ClusterNodes are not used as input to any of the functions in this
+    library.*
+
+    Parameters
+    ----------
+    Z : ndarray
+        The linkage matrix in proper form (see the `linkage`
+        function documentation).
+    rd : bool, optional
+        When False (default), a reference to the root `ClusterNode` object is
+        returned.  Otherwise, a tuple ``(r, d)`` is returned. ``r`` is a
+        reference to the root node while ``d`` is a list of `ClusterNode`
+        objects - one per original entry in the linkage matrix plus entries
+        for all clustering steps. If a cluster id is
+        less than the number of samples ``n`` in the data that the linkage
+        matrix describes, then it corresponds to a singleton cluster (leaf
+        node).
+        See `linkage` for more information on the assignment of cluster ids
+        to clusters.
+
+    Returns
+    -------
+    tree : ClusterNode or tuple (ClusterNode, list of ClusterNode)
+        If ``rd`` is False, a `ClusterNode`.
+        If ``rd`` is True, a list of length ``2*n - 1``, with ``n`` the number
+        of samples.  See the description of `rd` above for more details.
+
+    See Also
+    --------
+    linkage, is_valid_linkage, ClusterNode
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster import hierarchy
+    >>> rng = np.random.default_rng()
+    >>> x = rng.random((5, 2))
+    >>> Z = hierarchy.linkage(x)
+    >>> hierarchy.to_tree(Z)
+    >> rootnode, nodelist = hierarchy.to_tree(Z, rd=True)
+    >>> rootnode
+    >> len(nodelist)
+    9
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', materialize=True, xp=xp)
+
+    # Number of original objects is equal to the number of rows plus 1.
+    n = Z.shape[0] + 1
+
+    # Create a list full of None's to store the node objects
+    d = [None] * (n * 2 - 1)
+
+    # Create the nodes corresponding to the n original objects.
+    for i in range(0, n):
+        d[i] = ClusterNode(i)
+
+    nd = None
+
+    for i in range(Z.shape[0]):
+        row = Z[i, :]
+
+        fi = int_floor(row[0], xp)
+        fj = int_floor(row[1], xp)
+        if fi > i + n:
+            raise ValueError('Corrupt matrix Z. Index to derivative cluster '
+                              f'is used before it is formed. See row {fi}, '
+                              'column 0')
+        if fj > i + n:
+            raise ValueError('Corrupt matrix Z. Index to derivative cluster '
+                              f'is used before it is formed. See row {fj}, '
+                              'column 1')
+
+        nd = ClusterNode(i + n, d[fi], d[fj], row[2])
+        #                ^ id   ^ left ^ right ^ dist
+        if row[3] != nd.count:
+            raise ValueError(f'Corrupt matrix Z. The count Z[{i},3] is '
+                              'incorrect.')
+        d[n + i] = nd
+
+    if rd:
+        return (nd, d)
+    else:
+        return nd
+
+
+@lazy_cython
+def optimal_leaf_ordering(Z, y, metric='euclidean'):
+    """
+    Given a linkage matrix Z and distance, reorder the cut tree.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as a linkage matrix. See
+        `linkage` for more information on the return structure and
+        algorithm.
+    y : ndarray
+        The condensed distance matrix from which Z was generated.
+        Alternatively, a collection of m observation vectors in n
+        dimensions may be passed as an m by n array.
+    metric : str or function, optional
+        The distance metric to use in the case that y is a collection of
+        observation vectors; ignored otherwise. See the ``pdist``
+        function for a list of valid distance metrics. A custom distance
+        function can also be used.
+
+    Returns
+    -------
+    Z_ordered : ndarray
+        A copy of the linkage matrix Z, reordered to minimize the distance
+        between adjacent leaves.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster import hierarchy
+    >>> rng = np.random.default_rng()
+    >>> X = rng.standard_normal((10, 10))
+    >>> Z = hierarchy.ward(X)
+    >>> hierarchy.leaves_list(Z)
+    array([0, 3, 1, 9, 2, 5, 7, 4, 6, 8], dtype=int32)
+    >>> hierarchy.leaves_list(hierarchy.optimal_leaf_ordering(Z, X))
+    array([3, 0, 2, 5, 7, 4, 8, 6, 9, 1], dtype=int32)
+
+    """
+    xp = array_namespace(Z, y)
+    Z = _asarray(Z, order='C', xp=xp)
+    y = _asarray(y, order='C', dtype=xp.float64, xp=xp)
+    lazy = is_lazy_array(Z)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    if y.ndim == 1:
+        distance.is_valid_y(y, throw=True, name='y')
+    elif y.ndim == 2:
+        if (not lazy and y.shape[0] == y.shape[1]
+            and xp.all(xpx.isclose(xp.linalg.diagonal(y), 0))
+            and xp.all(y >= 0) and xp.all(xpx.isclose(y, y.T))):
+            warnings.warn('The symmetric non-negative hollow observation '
+                          'matrix looks suspiciously like an uncondensed '
+                          'distance matrix',
+                          ClusterWarning, stacklevel=2)
+        y = distance.pdist(y, metric)
+    else:
+        raise ValueError("`y` must be 1 or 2 dimensional.")
+    if not lazy and not xp.all(xp.isfinite(y)):
+        raise ValueError("The condensed distance matrix must contain only "
+                         "finite values.")
+
+    # The function name is prominently visible on the user-facing Dask dashboard;
+    # make sure it is meaningful.
+    def cy_optimal_leaf_ordering(Z, y, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+            if not np.all(np.isfinite(y)):
+                raise ValueError("The condensed distance matrix must contain only "
+                                 "finite values.")
+        return _optimal_leaf_ordering.optimal_leaf_ordering(Z, y)
+
+    return xpx.lazy_apply(cy_optimal_leaf_ordering, Z, y, validate=lazy,
+                          shape=Z.shape, dtype=Z.dtype, as_numpy=True, xp=xp)
+
+
+@lazy_cython
+def cophenet(Z, Y=None):
+    """
+    Calculate the cophenetic distances between each observation in
+    the hierarchical clustering defined by the linkage ``Z``.
+
+    Suppose ``p`` and ``q`` are original observations in
+    disjoint clusters ``s`` and ``t``, respectively and
+    ``s`` and ``t`` are joined by a direct parent cluster
+    ``u``. The cophenetic distance between observations
+    ``i`` and ``j`` is simply the distance between
+    clusters ``s`` and ``t``.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as an array
+        (see `linkage` function).
+    Y : ndarray (optional)
+        Calculates the cophenetic correlation coefficient ``c`` of a
+        hierarchical clustering defined by the linkage matrix `Z`
+        of a set of :math:`n` observations in :math:`m`
+        dimensions. `Y` is the condensed distance matrix from which
+        `Z` was generated.
+
+    Returns
+    -------
+    c : ndarray
+        The cophentic correlation distance (if ``Y`` is passed).
+    d : ndarray
+        The cophenetic distance matrix in condensed form. The
+        :math:`ij` th entry is the cophenetic distance between
+        original observations :math:`i` and :math:`j`.
+
+    See Also
+    --------
+    linkage :
+        for a description of what a linkage matrix is.
+    scipy.spatial.distance.squareform :
+        transforming condensed matrices into square ones.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import single, cophenet
+    >>> from scipy.spatial.distance import pdist, squareform
+
+    Given a dataset ``X`` and a linkage matrix ``Z``, the cophenetic distance
+    between two points of ``X`` is the distance between the largest two
+    distinct clusters that each of the points:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    ``X`` corresponds to this dataset ::
+
+        x x    x x
+        x        x
+
+        x        x
+        x x    x x
+
+    >>> Z = single(pdist(X))
+    >>> Z
+    array([[ 0.,  1.,  1.,  2.],
+           [ 2., 12.,  1.,  3.],
+           [ 3.,  4.,  1.,  2.],
+           [ 5., 14.,  1.,  3.],
+           [ 6.,  7.,  1.,  2.],
+           [ 8., 16.,  1.,  3.],
+           [ 9., 10.,  1.,  2.],
+           [11., 18.,  1.,  3.],
+           [13., 15.,  2.,  6.],
+           [17., 20.,  2.,  9.],
+           [19., 21.,  2., 12.]])
+    >>> cophenet(Z)
+    array([1., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 2., 2., 2., 2., 2.,
+           2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 1., 2., 2.,
+           2., 2., 2., 2., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.,
+           1., 1., 2., 2., 2., 1., 2., 2., 2., 2., 2., 2., 1., 1., 1.])
+
+    The output of the `scipy.cluster.hierarchy.cophenet` method is
+    represented in condensed form. We can use
+    `scipy.spatial.distance.squareform` to see the output as a
+    regular matrix (where each element ``ij`` denotes the cophenetic distance
+    between each ``i``, ``j`` pair of points in ``X``):
+
+    >>> squareform(cophenet(Z))
+    array([[0., 1., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
+           [1., 0., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
+           [1., 1., 0., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
+           [2., 2., 2., 0., 1., 1., 2., 2., 2., 2., 2., 2.],
+           [2., 2., 2., 1., 0., 1., 2., 2., 2., 2., 2., 2.],
+           [2., 2., 2., 1., 1., 0., 2., 2., 2., 2., 2., 2.],
+           [2., 2., 2., 2., 2., 2., 0., 1., 1., 2., 2., 2.],
+           [2., 2., 2., 2., 2., 2., 1., 0., 1., 2., 2., 2.],
+           [2., 2., 2., 2., 2., 2., 1., 1., 0., 2., 2., 2.],
+           [2., 2., 2., 2., 2., 2., 2., 2., 2., 0., 1., 1.],
+           [2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 0., 1.],
+           [2., 2., 2., 2., 2., 2., 2., 2., 2., 1., 1., 0.]])
+
+    In this example, the cophenetic distance between points on ``X`` that are
+    very close (i.e., in the same corner) is 1. For other pairs of points is 2,
+    because the points will be located in clusters at different
+    corners - thus, the distance between these clusters will be larger.
+
+    """
+    xp = array_namespace(Z, Y)
+    # Ensure float64 C-contiguous array. Cython code doesn't deal with striding.
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    def cy_cophenet(Z, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+        n = Z.shape[0] + 1
+        zz = np.zeros((n * (n-1)) // 2, dtype=np.float64)
+        _hierarchy.cophenetic_distances(Z, zz, n)
+        return zz
+    
+    n = Z.shape[0] + 1
+    zz = xpx.lazy_apply(cy_cophenet, Z, validate=is_lazy_array(Z),
+                        shape=((n * (n-1)) // 2, ), dtype=xp.float64,
+                        as_numpy=True, xp=xp)
+                        
+    if Y is None:
+        return zz
+
+    Y = _asarray(Y, order='C', xp=xp)
+    distance.is_valid_y(Y, throw=True, name='Y')
+
+    z = xp.mean(zz)
+    y = xp.mean(Y)
+    Yy = Y - y
+    Zz = zz - z
+    numerator = (Yy * Zz)
+    denomA = Yy**2
+    denomB = Zz**2
+    c = xp.sum(numerator) / xp.sqrt(xp.sum(denomA) * xp.sum(denomB))
+    return (c, zz)
+
+
+@lazy_cython
+def inconsistent(Z, d=2):
+    r"""
+    Calculate inconsistency statistics on a linkage matrix.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The :math:`(n-1)` by 4 matrix encoding the linkage (hierarchical
+        clustering).  See `linkage` documentation for more information on its
+        form.
+    d : int, optional
+        The number of links up to `d` levels below each non-singleton cluster.
+
+    Returns
+    -------
+    R : ndarray
+        A :math:`(n-1)` by 4 matrix where the ``i``'th row contains the link
+        statistics for the non-singleton cluster ``i``. The link statistics are
+        computed over the link heights for links :math:`d` levels below the
+        cluster ``i``. ``R[i,0]`` and ``R[i,1]`` are the mean and standard
+        deviation of the link heights, respectively; ``R[i,2]`` is the number
+        of links included in the calculation; and ``R[i,3]`` is the
+        inconsistency coefficient,
+
+        .. math:: \frac{\mathtt{Z[i,2]} - \mathtt{R[i,0]}} {R[i,1]}
+
+    Notes
+    -----
+    This function behaves similarly to the MATLAB(TM) ``inconsistent``
+    function.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import inconsistent, linkage
+    >>> from matplotlib import pyplot as plt
+    >>> X = [[i] for i in [2, 8, 0, 4, 1, 9, 9, 0]]
+    >>> Z = linkage(X, 'ward')
+    >>> print(Z)
+    [[ 5.          6.          0.          2.        ]
+     [ 2.          7.          0.          2.        ]
+     [ 0.          4.          1.          2.        ]
+     [ 1.          8.          1.15470054  3.        ]
+     [ 9.         10.          2.12132034  4.        ]
+     [ 3.         12.          4.11096096  5.        ]
+     [11.         13.         14.07183949  8.        ]]
+    >>> inconsistent(Z)
+    array([[ 0.        ,  0.        ,  1.        ,  0.        ],
+           [ 0.        ,  0.        ,  1.        ,  0.        ],
+           [ 1.        ,  0.        ,  1.        ,  0.        ],
+           [ 0.57735027,  0.81649658,  2.        ,  0.70710678],
+           [ 1.04044011,  1.06123822,  3.        ,  1.01850858],
+           [ 3.11614065,  1.40688837,  2.        ,  0.70710678],
+           [ 6.44583366,  6.76770586,  3.        ,  1.12682288]])
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    if d != np.floor(d) or d < 0:
+        raise ValueError('The second argument d must be a nonnegative '
+                         'integer value.')
+
+    def cy_inconsistent(Z, d, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+        R = np.zeros((Z.shape[0], 4), dtype=np.float64)
+        n = Z.shape[0] + 1
+        _hierarchy.inconsistent(Z, R, n, d)
+        return R
+
+    return xpx.lazy_apply(cy_inconsistent, Z, d=int(d), validate=is_lazy_array(Z),
+                          shape=(Z.shape[0], 4), dtype=xp.float64,
+                          as_numpy=True, xp=xp)
+
+
+@lazy_cython
+def from_mlab_linkage(Z):
+    """
+    Convert a linkage matrix generated by MATLAB(TM) to a new
+    linkage matrix compatible with this module.
+
+    The conversion does two things:
+
+     * the indices are converted from ``1..N`` to ``0..(N-1)`` form,
+       and
+
+     * a fourth column ``Z[:,3]`` is added where ``Z[i,3]`` represents the
+       number of original observations (leaves) in the non-singleton
+       cluster ``i``.
+
+    This function is useful when loading in linkages from legacy data
+    files generated by MATLAB.
+
+    Parameters
+    ----------
+    Z : ndarray
+        A linkage matrix generated by MATLAB(TM).
+
+    Returns
+    -------
+    ZS : ndarray
+        A linkage matrix compatible with ``scipy.cluster.hierarchy``.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    to_mlab_linkage : transform from SciPy to MATLAB format.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster.hierarchy import ward, from_mlab_linkage
+
+    Given a linkage matrix in MATLAB format ``mZ``, we can use
+    `scipy.cluster.hierarchy.from_mlab_linkage` to import
+    it into SciPy format:
+
+    >>> mZ = np.array([[1, 2, 1], [4, 5, 1], [7, 8, 1],
+    ...                [10, 11, 1], [3, 13, 1.29099445],
+    ...                [6, 14, 1.29099445],
+    ...                [9, 15, 1.29099445],
+    ...                [12, 16, 1.29099445],
+    ...                [17, 18, 5.77350269],
+    ...                [19, 20, 5.77350269],
+    ...                [21, 22,  8.16496581]])
+
+    >>> Z = from_mlab_linkage(mZ)
+    >>> Z
+    array([[  0.        ,   1.        ,   1.        ,   2.        ],
+           [  3.        ,   4.        ,   1.        ,   2.        ],
+           [  6.        ,   7.        ,   1.        ,   2.        ],
+           [  9.        ,  10.        ,   1.        ,   2.        ],
+           [  2.        ,  12.        ,   1.29099445,   3.        ],
+           [  5.        ,  13.        ,   1.29099445,   3.        ],
+           [  8.        ,  14.        ,   1.29099445,   3.        ],
+           [ 11.        ,  15.        ,   1.29099445,   3.        ],
+           [ 16.        ,  17.        ,   5.77350269,   6.        ],
+           [ 18.        ,  19.        ,   5.77350269,   6.        ],
+           [ 20.        ,  21.        ,   8.16496581,  12.        ]])
+
+    As expected, the linkage matrix ``Z`` returned includes an
+    additional column counting the number of original samples in
+    each cluster. Also, all cluster indices are reduced by 1
+    (MATLAB format uses 1-indexing, whereas SciPy uses 0-indexing).
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, dtype=xp.float64, order='C', xp=xp)
+
+    # If it's empty, return it.
+    if Z.shape in ((), (0, )):
+        return xp_copy(Z, xp=xp)
+
+    if Z.ndim != 2:
+        raise ValueError("The linkage array must be rectangular.")
+
+    # If it contains no rows, return it.
+    n = Z.shape[0]
+    if n == 0:
+        return xp_copy(Z, xp=xp)
+
+    lazy = is_lazy_array(Z)
+
+    if not lazy and xp.min(Z[:, :2]) != 1.0 and xp.max(Z[:, :2]) != 2 * n:
+        raise ValueError('The format of the indices is not 1..N')
+
+    res = xp.empty((Z.shape[0], Z.shape[1] + 1), dtype=Z.dtype)
+    res = xpx.at(res)[:, :2].set(Z[:, :2] - 1.0)
+    res = xpx.at(res)[:, 2:-1].set(Z[:, 2:])
+
+    def cy_from_mlab_linkage(Zpart, validate):
+        n = Zpart.shape[0]
+        if validate and np.min(Zpart[:, :2]) != 0.0 and np.max(Zpart[:, :2]) != 2 * n:
+            raise ValueError('The format of the indices is not 1..N')
+
+        if not Zpart.flags.writeable:
+            Zpart = Zpart.copy()  # xp=jax.numpy
+
+        CS = np.zeros((n,))
+        _hierarchy.calculate_cluster_sizes(Zpart, CS, n + 1)
+        return CS
+
+    CS = xpx.lazy_apply(cy_from_mlab_linkage, res[:, :-1], validate=lazy,
+                        shape=(res.shape[0],), dtype=xp.float64,
+                        as_numpy=True, xp=xp)
+
+    return xpx.at(res)[:, -1].set(CS)
+
+
+@xp_capabilities()
+def to_mlab_linkage(Z):
+    """
+    Convert a linkage matrix to a MATLAB(TM) compatible one.
+
+    Converts a linkage matrix ``Z`` generated by the linkage function
+    of this module to a MATLAB(TM) compatible one. The return linkage
+    matrix has the last column removed and the cluster indices are
+    converted to ``1..N`` indexing.
+
+    Parameters
+    ----------
+    Z : ndarray
+        A linkage matrix generated by ``scipy.cluster.hierarchy``.
+
+    Returns
+    -------
+    to_mlab_linkage : ndarray
+        A linkage matrix compatible with MATLAB(TM)'s hierarchical
+        clustering functions.
+
+        The return linkage matrix has the last column removed
+        and the cluster indices are converted to ``1..N`` indexing.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    from_mlab_linkage : transform from Matlab to SciPy format.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, to_mlab_linkage
+    >>> from scipy.spatial.distance import pdist
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+
+    After a linkage matrix ``Z`` has been created, we can use
+    `scipy.cluster.hierarchy.to_mlab_linkage` to convert it
+    into MATLAB format:
+
+    >>> mZ = to_mlab_linkage(Z)
+    >>> mZ
+    array([[  1.        ,   2.        ,   1.        ],
+           [  4.        ,   5.        ,   1.        ],
+           [  7.        ,   8.        ,   1.        ],
+           [ 10.        ,  11.        ,   1.        ],
+           [  3.        ,  13.        ,   1.29099445],
+           [  6.        ,  14.        ,   1.29099445],
+           [  9.        ,  15.        ,   1.29099445],
+           [ 12.        ,  16.        ,   1.29099445],
+           [ 17.        ,  18.        ,   5.77350269],
+           [ 19.        ,  20.        ,   5.77350269],
+           [ 21.        ,  22.        ,   8.16496581]])
+
+    The new linkage matrix ``mZ`` uses 1-indexing for all the
+    clusters (instead of 0-indexing). Also, the last column of
+    the original linkage matrix has been dropped.
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, dtype=xp.float64, xp=xp)
+    if Z.shape in ((), (0, )):
+        return xp_copy(Z, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    return xp.concat((Z[:, :2] + 1.0, Z[:, 2:3]), axis=1)
+
+
+@xp_capabilities()
+def is_monotonic(Z):
+    """
+    Return True if the linkage passed is monotonic.
+
+    The linkage is monotonic if for every cluster :math:`s` and :math:`t`
+    joined, the distance between them is no less than the distance
+    between any previously joined clusters.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The linkage matrix to check for monotonicity.
+
+    Returns
+    -------
+    b : bool
+        A boolean indicating whether the linkage is monotonic.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import median, ward, is_monotonic
+    >>> from scipy.spatial.distance import pdist
+
+    By definition, some hierarchical clustering algorithms - such as
+    `scipy.cluster.hierarchy.ward` - produce monotonic assignments of
+    samples to clusters; however, this is not always true for other
+    hierarchical methods - e.g. `scipy.cluster.hierarchy.median`.
+
+    Given a linkage matrix ``Z`` (as the result of a hierarchical clustering
+    method) we can test programmatically whether it has the monotonicity
+    property or not, using `scipy.cluster.hierarchy.is_monotonic`:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+    >>> is_monotonic(Z)
+    True
+
+    >>> Z = median(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.11803399,  3.        ],
+           [ 5.        , 13.        ,  1.11803399,  3.        ],
+           [ 8.        , 15.        ,  1.11803399,  3.        ],
+           [11.        , 14.        ,  1.11803399,  3.        ],
+           [18.        , 19.        ,  3.        ,  6.        ],
+           [16.        , 17.        ,  3.5       ,  6.        ],
+           [20.        , 21.        ,  3.25      , 12.        ]])
+    >>> is_monotonic(Z)
+    False
+
+    Note that this method is equivalent to just verifying that the distances
+    in the third column of the linkage matrix appear in a monotonically
+    increasing order.
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    # We expect the i'th value to be greater than its successor.
+    return xp.all(Z[1:, 2] >= Z[:-1, 2])
+
+
+@xp_capabilities(warnings=[("dask.array", "see notes"), ("jax.numpy", "see notes")])
+def is_valid_im(R, warning=False, throw=False, name=None):
+    """Return True if the inconsistency matrix passed is valid.
+
+    It must be a :math:`n` by 4 array of doubles. The standard
+    deviations ``R[:,1]`` must be nonnegative. The link counts
+    ``R[:,2]`` must be positive and no greater than :math:`n-1`.
+
+    Parameters
+    ----------
+    R : ndarray
+        The inconsistency matrix to check for validity.
+    warning : bool, optional
+        When True, issues a Python warning if the linkage
+        matrix passed is invalid.
+    throw : bool, optional
+        When True, throws a Python exception if the linkage
+        matrix passed is invalid.
+    name : str, optional
+        This string refers to the variable name of the invalid
+        linkage matrix.
+
+    Returns
+    -------
+    b : bool
+        True if the inconsistency matrix is valid; False otherwise.
+
+    Notes
+    -----
+    *Array API support (experimental):* If the input is a lazy Array (e.g. Dask
+    or JAX), the return value may be a 0-dimensional bool Array. When warning=True
+    or throw=True, calling this function materializes the array.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    inconsistent : for the creation of a inconsistency matrix.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, inconsistent, is_valid_im
+    >>> from scipy.spatial.distance import pdist
+
+    Given a data set ``X``, we can apply a clustering method to obtain a
+    linkage matrix ``Z``. `scipy.cluster.hierarchy.inconsistent` can
+    be also used to obtain the inconsistency matrix ``R`` associated to
+    this clustering process:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+    >>> R = inconsistent(Z)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+    >>> R
+    array([[1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.14549722, 0.20576415, 2.        , 0.70710678],
+           [1.14549722, 0.20576415, 2.        , 0.70710678],
+           [1.14549722, 0.20576415, 2.        , 0.70710678],
+           [1.14549722, 0.20576415, 2.        , 0.70710678],
+           [2.78516386, 2.58797734, 3.        , 1.15470054],
+           [2.78516386, 2.58797734, 3.        , 1.15470054],
+           [6.57065706, 1.38071187, 3.        , 1.15470054]])
+
+    Now we can use `scipy.cluster.hierarchy.is_valid_im` to verify that
+    ``R`` is correct:
+
+    >>> is_valid_im(R)
+    True
+
+    However, if ``R`` is wrongly constructed (e.g., one of the standard
+    deviations is set to a negative value), then the check will fail:
+
+    >>> R[-1,1] = R[-1,1] * -1
+    >>> is_valid_im(R)
+    False
+
+    """
+    xp = array_namespace(R)
+    R = _asarray(R, xp=xp)
+    return _is_valid_im(R, warning=warning, throw=throw, name=name,
+                        materialize=True, xp=xp)
+
+
+def _is_valid_im(R, warning=False, throw=False, name=None, materialize=False, *, xp):
+    """Variant of `is_valid_im` to be called internally by other scipy functions,
+    which by default does not materialize lazy input arrays (Dask, JAX, etc.) when
+    warning=True or throw=True.
+    """
+    name_str = f"{name!r} " if name else ''
+    try:
+        if R.dtype != xp.float64:
+            raise TypeError(f'Inconsistency matrix {name_str}must contain doubles '
+                            '(double).')
+        if len(R.shape) != 2:
+            raise ValueError(f'Inconsistency matrix {name_str}must have shape=2 (i.e. '
+                             'be two-dimensional).')
+        if R.shape[1] != 4:
+            raise ValueError(f'Inconsistency matrix {name_str}'
+                             'must have 4 columns.')
+        if R.shape[0] < 1:
+            raise ValueError(f'Inconsistency matrix {name_str}'
+                             'must have at least one row.')
+    except (TypeError, ValueError) as e:
+        if throw:
+            raise
+        if warning:
+            _warning(str(e))
+        return False
+
+    return _lazy_valid_checks(
+        (xp.any(R[:, 0] < 0),
+         f'Inconsistency matrix {name_str} contains negative link height means.'),
+        (xp.any(R[:, 1] < 0),
+         f'Inconsistency matrix {name_str} contains negative link height standard '
+         'deviations.'),
+        (xp.any(R[:, 2] < 0),
+         f'Inconsistency matrix {name_str} contains negative link counts.'),
+        throw=throw, warning=warning, materialize=materialize, xp=xp
+    )
+
+
+@xp_capabilities(warnings=[("dask.array", "see notes"), ("jax.numpy", "see notes")])
+def is_valid_linkage(Z, warning=False, throw=False, name=None):
+    """
+    Check the validity of a linkage matrix.
+
+    A linkage matrix is valid if it is a 2-D array (type double)
+    with :math:`n` rows and 4 columns. The first two columns must contain
+    indices between 0 and :math:`2n-1`. For a given row ``i``, the following
+    two expressions have to hold:
+
+    .. math::
+
+        0 \\leq \\mathtt{Z[i,0]} \\leq i+n-1
+        0 \\leq Z[i,1] \\leq i+n-1
+
+    I.e., a cluster cannot join another cluster unless the cluster being joined
+    has been generated.
+
+    The fourth column of `Z` represents the number of original observations
+    in a cluster, so a valid ``Z[i, 3]`` value may not exceed the number of
+    original observations.
+
+    Parameters
+    ----------
+    Z : array_like
+        Linkage matrix.
+    warning : bool, optional
+        When True, issues a Python warning if the linkage
+        matrix passed is invalid.
+    throw : bool, optional
+        When True, throws a Python exception if the linkage
+        matrix passed is invalid.
+    name : str, optional
+        This string refers to the variable name of the invalid
+        linkage matrix.
+
+    Returns
+    -------
+    b : bool
+        True if the inconsistency matrix is valid; False otherwise.
+
+    Notes
+    -----
+    *Array API support (experimental):* If the input is a lazy Array (e.g. Dask
+    or JAX), the return value may be a 0-dimensional bool Array. When warning=True
+    or throw=True, calling this function materializes the array.
+
+    See Also
+    --------
+    linkage: for a description of what a linkage matrix is.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, is_valid_linkage
+    >>> from scipy.spatial.distance import pdist
+
+    All linkage matrices generated by the clustering methods in this module
+    will be valid (i.e., they will have the appropriate dimensions and the two
+    required expressions will hold for all the rows).
+
+    We can check this using `scipy.cluster.hierarchy.is_valid_linkage`:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+    >>> is_valid_linkage(Z)
+    True
+
+    However, if we create a linkage matrix in a wrong way - or if we modify
+    a valid one in a way that any of the required expressions don't hold
+    anymore, then the check will fail:
+
+    >>> Z[3][1] = 20    # the cluster number 20 is not defined at this point
+    >>> is_valid_linkage(Z)
+    False
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, xp=xp)
+    return _is_valid_linkage(Z, warning=warning, throw=throw,
+                             name=name, materialize=True, xp=xp)
+
+
+def _is_valid_linkage(Z, warning=False, throw=False, name=None,
+                      materialize=False, *, xp):
+    """Variant of `is_valid_linkage` to be called internally by other scipy functions,
+    which by default does not materialize lazy input arrays (Dask, JAX, etc.) when
+    warning=True or throw=True.
+    """
+    name_str = f"{name!r} " if name else ''
+    try:
+        if Z.dtype != xp.float64:
+            raise TypeError(f'Linkage matrix {name_str}must contain doubles.')
+        if len(Z.shape) != 2:
+            raise ValueError(f'Linkage matrix {name_str}must have shape=2 (i.e. be'
+                             ' two-dimensional).')
+        if Z.shape[1] != 4:
+            raise ValueError(f'Linkage matrix {name_str}must have 4 columns.')
+        if Z.shape[0] == 0:
+            raise ValueError('Linkage must be computed on at least two '
+                             'observations.')
+    except (TypeError, ValueError) as e:
+        if throw:
+            raise
+        if warning:
+            _warning(str(e))
+        return False
+
+    n = Z.shape[0]
+    if n < 2:
+        return True
+
+    return _lazy_valid_checks(
+        (xp.any(Z[:, :2] < 0),
+         f'Linkage {name_str}contains negative indices.'),
+        (xp.any(Z[:, 2] < 0),
+         f'Linkage {name_str}contains negative distances.'),
+        (xp.any(Z[:, 3] < 0),
+         f'Linkage {name_str}contains negative counts.'),
+        (xp.any(Z[:, 3] > n + 1),
+         f'Linkage {name_str}contains excessive observations in a cluster'),
+        (xp.any(xp.max(Z[:, :2], axis=1) >= xp.arange(n + 1, 2 * n + 1, dtype=Z.dtype)),
+         f'Linkage {name_str}uses non-singleton cluster before it is formed.'),
+        (xpx.nunique(Z[:, :2]) < n * 2,
+         f'Linkage {name_str}uses the same cluster more than once.'),
+        throw=throw, warning=warning, materialize=materialize, xp=xp
+    )
+
+
+def _lazy_valid_checks(*args, throw=False, warning=False, materialize=False, xp):
+    """Validate a set of conditions on the contents of possibly lazy arrays.
+
+    Parameters
+    ----------
+    args : tuples of (Array, str)
+        The first element of each tuple must be a 0-dimensional Array
+        that evaluates to bool; the second element must be the message to convey
+        if the  first element evaluates to True.
+    throw: bool
+        Set to True to `raise ValueError(args[i][1])` if `args[i][0]` is True.
+    warning: bool
+        Set to True to issue a warning with message `args[i][1]` if `args[i][0]`
+        is True.
+    materialize: bool
+        Set to True to force materialization of lazy arrays when throw=True or
+        warning=True. If the inputs are lazy and materialize=False, ignore the
+        `throw` and `warning` flags.
+    xp: module
+        Array API namespace
+
+    Returns
+    -------
+    If xp is an eager backend (e.g. numpy) and all conditions are False, return True.
+    If throw is True, raise. Otherwise, return False.
+
+    If xp is a lazy backend (e.g. Dask or JAX), return a 0-dimensional bool Array.
+    """
+    conds = xp.concat([xp.reshape(cond, (1, )) for cond, _ in args])
+
+    lazy = is_lazy_array(conds)
+    if not throw and not warning or (lazy and not materialize):
+        out = ~xp.any(conds)
+        return out if lazy else bool(out)
+
+    if is_dask(xp):
+        # Only materialize the graph once, instead of once per check
+        conds = conds.compute()
+
+    # Don't call np.asarray(conds), as it would be blocked by the device transfer
+    # guard on CuPy and PyTorch and the densification guard on Sparse, whereas
+    # bool() will not.
+    conds = [bool(cond) for cond in conds]
+
+    for cond, (_, msg) in zip(conds, args):
+        if throw and cond:
+            raise ValueError(msg)
+        elif warning and cond:
+            warnings.warn(msg, ClusterWarning, stacklevel=3)
+
+    return not any(conds)
+
+
+@xp_capabilities()
+def num_obs_linkage(Z):
+    """
+    Return the number of original observations of the linkage matrix passed.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The linkage matrix on which to perform the operation.
+
+    Returns
+    -------
+    n : int
+        The number of original observations in the linkage.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, num_obs_linkage
+    >>> from scipy.spatial.distance import pdist
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+
+    ``Z`` is a linkage matrix obtained after using the Ward clustering method
+    with ``X``, a dataset with 12 data points.
+
+    >>> num_obs_linkage(Z)
+    12
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+    return Z.shape[0] + 1
+
+
+@xp_capabilities()
+def correspond(Z, Y):
+    """
+    Check for correspondence between linkage and condensed distance matrices.
+
+    They must have the same number of original observations for
+    the check to succeed.
+
+    This function is useful as a sanity check in algorithms that make
+    extensive use of linkage and distance matrices that must
+    correspond to the same set of original observations.
+
+    Parameters
+    ----------
+    Z : array_like
+        The linkage matrix to check for correspondence.
+    Y : array_like
+        The condensed distance matrix to check for correspondence.
+
+    Returns
+    -------
+    b : bool
+        A boolean indicating whether the linkage matrix and distance
+        matrix could possibly correspond to one another.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, correspond
+    >>> from scipy.spatial.distance import pdist
+
+    This method can be used to check if a given linkage matrix ``Z`` has been
+    obtained from the application of a cluster method over a dataset ``X``:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+    >>> X_condensed = pdist(X)
+    >>> Z = ward(X_condensed)
+
+    Here, we can compare ``Z`` and ``X`` (in condensed form):
+
+    >>> correspond(Z, X_condensed)
+    True
+
+    """
+    xp = array_namespace(Z, Y)
+    Z = _asarray(Z, xp=xp)
+    Y = _asarray(Y, xp=xp)
+    _is_valid_linkage(Z, throw=True, xp=xp)
+    distance.is_valid_y(Y, throw=True)
+    return distance.num_obs_y(Y) == num_obs_linkage(Z)
+
+
+@xp_capabilities(cpu_only=True, reason="Cython code",
+                 jax_jit=False, allow_dask_compute=True)
+def fcluster(Z, t, criterion='inconsistent', depth=2, R=None, monocrit=None):
+    """
+    Form flat clusters from the hierarchical clustering defined by
+    the given linkage matrix.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded with the matrix returned
+        by the `linkage` function.
+    t : scalar
+        For criteria 'inconsistent', 'distance' or 'monocrit',
+         this is the threshold to apply when forming flat clusters.
+        For 'maxclust' or 'maxclust_monocrit' criteria,
+         this would be max number of clusters requested.
+    criterion : str, optional
+        The criterion to use in forming flat clusters. This can
+        be any of the following values:
+
+          ``inconsistent`` :
+              If a cluster node and all its
+              descendants have an inconsistent value less than or equal
+              to `t`, then all its leaf descendants belong to the
+              same flat cluster. When no non-singleton cluster meets
+              this criterion, every node is assigned to its own
+              cluster. (Default)
+
+          ``distance`` :
+              Forms flat clusters so that the original
+              observations in each flat cluster have no greater a
+              cophenetic distance than `t`.
+
+          ``maxclust`` :
+              Finds a minimum threshold ``r`` so that
+              the cophenetic distance between any two original
+              observations in the same flat cluster is no more than
+              ``r`` and no more than `t` flat clusters are formed.
+
+          ``monocrit`` :
+              Forms a flat cluster from a cluster node c
+              with index i when ``monocrit[j] <= t``.
+
+              For example, to threshold on the maximum mean distance
+              as computed in the inconsistency matrix R with a
+              threshold of 0.8 do::
+
+                  MR = maxRstat(Z, R, 3)
+                  fcluster(Z, t=0.8, criterion='monocrit', monocrit=MR)
+
+          ``maxclust_monocrit`` :
+              Forms a flat cluster from a
+              non-singleton cluster node ``c`` when ``monocrit[i] <=
+              r`` for all cluster indices ``i`` below and including
+              ``c``. ``r`` is minimized such that no more than ``t``
+              flat clusters are formed. monocrit must be
+              monotonic. For example, to minimize the threshold t on
+              maximum inconsistency values so that no more than 3 flat
+              clusters are formed, do::
+
+                  MI = maxinconsts(Z, R)
+                  fcluster(Z, t=3, criterion='maxclust_monocrit', monocrit=MI)
+    depth : int, optional
+        The maximum depth to perform the inconsistency calculation.
+        It has no meaning for the other criteria. Default is 2.
+    R : ndarray, optional
+        The inconsistency matrix to use for the ``'inconsistent'``
+        criterion. This matrix is computed if not provided.
+    monocrit : ndarray, optional
+        An array of length n-1. `monocrit[i]` is the
+        statistics upon which non-singleton i is thresholded. The
+        monocrit vector must be monotonic, i.e., given a node c with
+        index i, for all node indices j corresponding to nodes
+        below c, ``monocrit[i] >= monocrit[j]``.
+
+    Returns
+    -------
+    fcluster : ndarray
+        An array of length ``n``. ``T[i]`` is the flat cluster number to
+        which original observation ``i`` belongs.
+
+    See Also
+    --------
+    linkage : for information about hierarchical clustering methods work.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, fcluster
+    >>> from scipy.spatial.distance import pdist
+
+    All cluster linkage methods - e.g., `scipy.cluster.hierarchy.ward`
+    generate a linkage matrix ``Z`` as their output:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+
+    This matrix represents a dendrogram, where the first and second elements
+    are the two clusters merged at each step, the third element is the
+    distance between these clusters, and the fourth element is the size of
+    the new cluster - the number of original data points included.
+
+    `scipy.cluster.hierarchy.fcluster` can be used to flatten the
+    dendrogram, obtaining as a result an assignation of the original data
+    points to single clusters.
+
+    This assignation mostly depends on a distance threshold ``t`` - the maximum
+    inter-cluster distance allowed:
+
+    >>> fcluster(Z, t=0.9, criterion='distance')
+    array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12], dtype=int32)
+
+    >>> fcluster(Z, t=1.1, criterion='distance')
+    array([1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8], dtype=int32)
+
+    >>> fcluster(Z, t=3, criterion='distance')
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+
+    >>> fcluster(Z, t=9, criterion='distance')
+    array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
+
+    In the first case, the threshold ``t`` is too small to allow any two
+    samples in the data to form a cluster, so 12 different clusters are
+    returned.
+
+    In the second case, the threshold is large enough to allow the first
+    4 points to be merged with their nearest neighbors. So, here, only 8
+    clusters are returned.
+
+    The third case, with a much higher threshold, allows for up to 8 data
+    points to be connected - so 4 clusters are returned here.
+
+    Lastly, the threshold of the fourth case is large enough to allow for
+    all data points to be merged together - so a single cluster is returned.
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', materialize=True, xp=xp)
+
+    n = Z.shape[0] + 1
+    T = np.zeros((n,), dtype='i')
+
+    if monocrit is not None:
+        monocrit = np.asarray(monocrit, order='C', dtype=np.float64)
+
+    Z = np.asarray(Z)
+    monocrit = np.asarray(monocrit)
+    if criterion == 'inconsistent':
+        if R is None:
+            R = inconsistent(Z, depth)
+        else:
+            R = _asarray(R, order='C', dtype=xp.float64, xp=xp)
+            _is_valid_im(R, throw=True, name='R', materialize=True, xp=xp)
+            # Since the C code does not support striding using strides.
+            # The dimensions are used instead.
+            R = np.asarray(R)
+        _hierarchy.cluster_in(Z, R, T, float(t), int(n))
+    elif criterion == 'distance':
+        _hierarchy.cluster_dist(Z, T, float(t), int(n))
+    elif criterion == 'maxclust':
+        _hierarchy.cluster_maxclust_dist(Z, T, int(n), t)
+    elif criterion == 'monocrit':
+        _hierarchy.cluster_monocrit(Z, monocrit, T, float(t), int(n))
+    elif criterion == 'maxclust_monocrit':
+        _hierarchy.cluster_maxclust_monocrit(Z, monocrit, T, int(n), int(t))
+    else:
+        raise ValueError(f'Invalid cluster formation criterion: {str(criterion)}')
+    return xp.asarray(T)
+
+
+@xp_capabilities(cpu_only=True, reason="Cython code",
+                 jax_jit=False, allow_dask_compute=True)
+def fclusterdata(X, t, criterion='inconsistent',
+                 metric='euclidean', depth=2, method='single', R=None):
+    """
+    Cluster observation data using a given metric.
+
+    Clusters the original observations in the n-by-m data
+    matrix X (n observations in m dimensions), using the euclidean
+    distance metric to calculate distances between original observations,
+    performs hierarchical clustering using the single linkage algorithm,
+    and forms flat clusters using the inconsistency method with `t` as the
+    cut-off threshold.
+
+    A 1-D array ``T`` of length ``n`` is returned. ``T[i]`` is
+    the index of the flat cluster to which the original observation ``i``
+    belongs.
+
+    Parameters
+    ----------
+    X : (N, M) ndarray
+        N by M data matrix with N observations in M dimensions.
+    t : scalar
+        For criteria 'inconsistent', 'distance' or 'monocrit',
+         this is the threshold to apply when forming flat clusters.
+        For 'maxclust' or 'maxclust_monocrit' criteria,
+         this would be max number of clusters requested.
+    criterion : str, optional
+        Specifies the criterion for forming flat clusters. Valid
+        values are 'inconsistent' (default), 'distance', or 'maxclust'
+        cluster formation algorithms. See `fcluster` for descriptions.
+    metric : str or function, optional
+        The distance metric for calculating pairwise distances. See
+        ``distance.pdist`` for descriptions and linkage to verify
+        compatibility with the linkage method.
+    depth : int, optional
+        The maximum depth for the inconsistency calculation. See
+        `inconsistent` for more information.
+    method : str, optional
+        The linkage method to use (single, complete, average,
+        weighted, median centroid, ward). See `linkage` for more
+        information. Default is "single".
+    R : ndarray, optional
+        The inconsistency matrix. It will be computed if necessary
+        if it is not passed.
+
+    Returns
+    -------
+    fclusterdata : ndarray
+        A vector of length n. T[i] is the flat cluster number to
+        which original observation i belongs.
+
+    See Also
+    --------
+    scipy.spatial.distance.pdist : pairwise distance metrics
+
+    Notes
+    -----
+    This function is similar to the MATLAB function ``clusterdata``.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import fclusterdata
+
+    This is a convenience method that abstracts all the steps to perform in a
+    typical SciPy's hierarchical clustering workflow.
+
+    * Transform the input data into a condensed matrix with
+      `scipy.spatial.distance.pdist`.
+
+    * Apply a clustering method.
+
+    * Obtain flat clusters at a user defined distance threshold ``t`` using
+      `scipy.cluster.hierarchy.fcluster`.
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> fclusterdata(X, t=1)
+    array([3, 3, 3, 4, 4, 4, 2, 2, 2, 1, 1, 1], dtype=int32)
+
+    The output here (for the dataset ``X``, distance threshold ``t``, and the
+    default settings) is four clusters with three data points each.
+
+    """
+    xp = array_namespace(X)
+    X = _asarray(X, order='C', dtype=xp.float64, xp=xp)
+
+    if X.ndim != 2:
+        raise TypeError('The observation matrix X must be an n by m array.')
+
+    Y = distance.pdist(X, metric=metric)
+    Z = linkage(Y, method=method)
+    if R is None:
+        R = inconsistent(Z, d=depth)
+    else:
+        R = _asarray(R, order='C', xp=xp)
+    T = fcluster(Z, criterion=criterion, depth=depth, R=R, t=t)
+    return T
+
+
+@lazy_cython
+def leaves_list(Z):
+    """
+    Return a list of leaf node ids.
+
+    The return corresponds to the observation vector index as it appears
+    in the tree from left to right. Z is a linkage matrix.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as a matrix.  `Z` is
+        a linkage matrix.  See `linkage` for more information.
+
+    Returns
+    -------
+    leaves_list : ndarray
+        The list of leaf node ids.
+
+    See Also
+    --------
+    dendrogram : for information about dendrogram structure.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, dendrogram, leaves_list
+    >>> from scipy.spatial.distance import pdist
+    >>> from matplotlib import pyplot as plt
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+
+    The linkage matrix ``Z`` represents a dendrogram, that is, a tree that
+    encodes the structure of the clustering performed.
+    `scipy.cluster.hierarchy.leaves_list` shows the mapping between
+    indices in the ``X`` dataset and leaves in the dendrogram:
+
+    >>> leaves_list(Z)
+    array([ 2,  0,  1,  5,  3,  4,  8,  6,  7, 11,  9, 10], dtype=int32)
+
+    >>> fig = plt.figure(figsize=(25, 10))
+    >>> dn = dendrogram(Z)
+    >>> plt.show()
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    def cy_leaves_list(Z, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+        n = Z.shape[0] + 1
+        ML = np.zeros((n,), dtype=np.int32)
+        _hierarchy.prelist(Z, ML, n)
+        return ML
+
+    n = Z.shape[0] + 1
+    return xpx.lazy_apply(cy_leaves_list, Z, validate=is_lazy_array(Z),
+                          shape=(n, ), dtype=xp.int32,
+                          as_numpy=True, xp=xp)
+
+
+# Maps number of leaves to text size.
+#
+# p <= 20, size="12"
+# 20 < p <= 30, size="10"
+# 30 < p <= 50, size="8"
+# 50 < p <= np.inf, size="6"
+
+_dtextsizes = {20: 12, 30: 10, 50: 8, 85: 6, np.inf: 5}
+_drotation = {20: 0, 40: 45, np.inf: 90}
+_dtextsortedkeys = list(_dtextsizes.keys())
+_dtextsortedkeys.sort()
+_drotationsortedkeys = list(_drotation.keys())
+_drotationsortedkeys.sort()
+
+
+def _remove_dups(L):
+    """
+    Remove duplicates AND preserve the original order of the elements.
+
+    The set class is not guaranteed to do this.
+    """
+    seen_before = set()
+    L2 = []
+    for i in L:
+        if i not in seen_before:
+            seen_before.add(i)
+            L2.append(i)
+    return L2
+
+
+def _get_tick_text_size(p):
+    for k in _dtextsortedkeys:
+        if p <= k:
+            return _dtextsizes[k]
+
+
+def _get_tick_rotation(p):
+    for k in _drotationsortedkeys:
+        if p <= k:
+            return _drotation[k]
+
+
+def _plot_dendrogram(icoords, dcoords, ivl, p, n, mh, orientation,
+                     no_labels, color_list, leaf_font_size=None,
+                     leaf_rotation=None, contraction_marks=None,
+                     ax=None, above_threshold_color='C0'):
+    # Import matplotlib here so that it's not imported unless dendrograms
+    # are plotted. Raise an informative error if importing fails.
+    try:
+        # if an axis is provided, don't use pylab at all
+        if ax is None:
+            import matplotlib.pylab
+        import matplotlib.patches
+        import matplotlib.collections
+    except ImportError as e:
+        raise ImportError("You must install the matplotlib library to plot "
+                          "the dendrogram. Use no_plot=True to calculate the "
+                          "dendrogram without plotting.") from e
+
+    if ax is None:
+        ax = matplotlib.pylab.gca()
+        # if we're using pylab, we want to trigger a draw at the end
+        trigger_redraw = True
+    else:
+        trigger_redraw = False
+
+    # Independent variable plot width
+    ivw = len(ivl) * 10
+    # Dependent variable plot height
+    dvw = mh + mh * 0.05
+
+    iv_ticks = np.arange(5, len(ivl) * 10 + 5, 10)
+    if orientation in ('top', 'bottom'):
+        if orientation == 'top':
+            ax.set_ylim([0, dvw])
+            ax.set_xlim([0, ivw])
+        else:
+            ax.set_ylim([dvw, 0])
+            ax.set_xlim([0, ivw])
+
+        xlines = icoords
+        ylines = dcoords
+        if no_labels:
+            ax.set_xticks([])
+            ax.set_xticklabels([])
+        else:
+            ax.set_xticks(iv_ticks)
+
+            if orientation == 'top':
+                ax.xaxis.set_ticks_position('bottom')
+            else:
+                ax.xaxis.set_ticks_position('top')
+
+            # Make the tick marks invisible because they cover up the links
+            for line in ax.get_xticklines():
+                line.set_visible(False)
+
+            leaf_rot = (float(_get_tick_rotation(len(ivl)))
+                        if (leaf_rotation is None) else leaf_rotation)
+            leaf_font = (float(_get_tick_text_size(len(ivl)))
+                         if (leaf_font_size is None) else leaf_font_size)
+            ax.set_xticklabels(ivl, rotation=leaf_rot, size=leaf_font)
+
+    elif orientation in ('left', 'right'):
+        if orientation == 'left':
+            ax.set_xlim([dvw, 0])
+            ax.set_ylim([0, ivw])
+        else:
+            ax.set_xlim([0, dvw])
+            ax.set_ylim([0, ivw])
+
+        xlines = dcoords
+        ylines = icoords
+        if no_labels:
+            ax.set_yticks([])
+            ax.set_yticklabels([])
+        else:
+            ax.set_yticks(iv_ticks)
+
+            if orientation == 'left':
+                ax.yaxis.set_ticks_position('right')
+            else:
+                ax.yaxis.set_ticks_position('left')
+
+            # Make the tick marks invisible because they cover up the links
+            for line in ax.get_yticklines():
+                line.set_visible(False)
+
+            leaf_font = (float(_get_tick_text_size(len(ivl)))
+                         if (leaf_font_size is None) else leaf_font_size)
+
+            if leaf_rotation is not None:
+                ax.set_yticklabels(ivl, rotation=leaf_rotation, size=leaf_font)
+            else:
+                ax.set_yticklabels(ivl, size=leaf_font)
+
+    # Let's use collections instead. This way there is a separate legend item
+    # for each tree grouping, rather than stupidly one for each line segment.
+    colors_used = _remove_dups(color_list)
+    color_to_lines = {}
+    for color in colors_used:
+        color_to_lines[color] = []
+    for (xline, yline, color) in zip(xlines, ylines, color_list):
+        color_to_lines[color].append(list(zip(xline, yline)))
+
+    colors_to_collections = {}
+    # Construct the collections.
+    for color in colors_used:
+        coll = matplotlib.collections.LineCollection(color_to_lines[color],
+                                                     colors=(color,))
+        colors_to_collections[color] = coll
+
+    # Add all the groupings below the color threshold.
+    for color in colors_used:
+        if color != above_threshold_color:
+            ax.add_collection(colors_to_collections[color])
+    # If there's a grouping of links above the color threshold, it goes last.
+    if above_threshold_color in colors_to_collections:
+        ax.add_collection(colors_to_collections[above_threshold_color])
+
+    if contraction_marks is not None:
+        Ellipse = matplotlib.patches.Ellipse
+        for (x, y) in contraction_marks:
+            if orientation in ('left', 'right'):
+                e = Ellipse((y, x), width=dvw / 100, height=1.0)
+            else:
+                e = Ellipse((x, y), width=1.0, height=dvw / 100)
+            ax.add_artist(e)
+            e.set_clip_box(ax.bbox)
+            e.set_alpha(0.5)
+            e.set_facecolor('k')
+
+    if trigger_redraw:
+        matplotlib.pylab.draw_if_interactive()
+
+
+# C0  is used for above threshold color
+_link_line_colors_default = ('C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9')
+_link_line_colors = list(_link_line_colors_default)
+
+
+def set_link_color_palette(palette):
+    """
+    Set list of matplotlib color codes for use by dendrogram.
+
+    Note that this palette is global (i.e., setting it once changes the colors
+    for all subsequent calls to `dendrogram`) and that it affects only the
+    the colors below ``color_threshold``.
+
+    Note that `dendrogram` also accepts a custom coloring function through its
+    ``link_color_func`` keyword, which is more flexible and non-global.
+
+    Parameters
+    ----------
+    palette : list of str or None
+        A list of matplotlib color codes.  The order of the color codes is the
+        order in which the colors are cycled through when color thresholding in
+        the dendrogram.
+
+        If ``None``, resets the palette to its default (which are matplotlib
+        default colors C1 to C9).
+
+    Returns
+    -------
+    None
+
+    See Also
+    --------
+    dendrogram
+
+    Notes
+    -----
+    Ability to reset the palette with ``None`` added in SciPy 0.17.0.
+
+    Thread safety: using this function in a multi-threaded fashion may
+    result in `dendrogram` producing plots with unexpected colors.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster import hierarchy
+    >>> ytdist = np.array([662., 877., 255., 412., 996., 295., 468., 268.,
+    ...                    400., 754., 564., 138., 219., 869., 669.])
+    >>> Z = hierarchy.linkage(ytdist, 'single')
+    >>> dn = hierarchy.dendrogram(Z, no_plot=True)
+    >>> dn['color_list']
+    ['C1', 'C0', 'C0', 'C0', 'C0']
+    >>> hierarchy.set_link_color_palette(['c', 'm', 'y', 'k'])
+    >>> dn = hierarchy.dendrogram(Z, no_plot=True, above_threshold_color='b')
+    >>> dn['color_list']
+    ['c', 'b', 'b', 'b', 'b']
+    >>> dn = hierarchy.dendrogram(Z, no_plot=True, color_threshold=267,
+    ...                           above_threshold_color='k')
+    >>> dn['color_list']
+    ['c', 'm', 'm', 'k', 'k']
+
+    Now, reset the color palette to its default:
+
+    >>> hierarchy.set_link_color_palette(None)
+
+    """
+    if palette is None:
+        # reset to its default
+        palette = _link_line_colors_default
+    elif not isinstance(palette, list | tuple):
+        raise TypeError("palette must be a list or tuple")
+    _ptypes = [isinstance(p, str) for p in palette]
+
+    if False in _ptypes:
+        raise TypeError("all palette list elements must be color strings")
+
+    global _link_line_colors
+    _link_line_colors = palette
+
+
+@xp_capabilities(cpu_only=True, jax_jit=False, allow_dask_compute=True)
+def dendrogram(Z, p=30, truncate_mode=None, color_threshold=None,
+               get_leaves=True, orientation='top', labels=None,
+               count_sort=False, distance_sort=False, show_leaf_counts=True,
+               no_plot=False, no_labels=False, leaf_font_size=None,
+               leaf_rotation=None, leaf_label_func=None,
+               show_contracted=False, link_color_func=None, ax=None,
+               above_threshold_color='C0'):
+    """
+    Plot the hierarchical clustering as a dendrogram.
+
+    The dendrogram illustrates how each cluster is
+    composed by drawing a U-shaped link between a non-singleton
+    cluster and its children. The top of the U-link indicates a
+    cluster merge. The two legs of the U-link indicate which clusters
+    were merged. The length of the two legs of the U-link represents
+    the distance between the child clusters. It is also the
+    cophenetic distance between original observations in the two
+    children clusters.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The linkage matrix encoding the hierarchical clustering to
+        render as a dendrogram. See the ``linkage`` function for more
+        information on the format of ``Z``.
+    p : int, optional
+        The ``p`` parameter for ``truncate_mode``.
+    truncate_mode : str, optional
+        The dendrogram can be hard to read when the original
+        observation matrix from which the linkage is derived is
+        large. Truncation is used to condense the dendrogram. There
+        are several modes:
+
+        ``None``
+          No truncation is performed (default).
+          Note: ``'none'`` is an alias for ``None`` that's kept for
+          backward compatibility.
+
+        ``'lastp'``
+          The last ``p`` non-singleton clusters formed in the linkage are the
+          only non-leaf nodes in the linkage; they correspond to rows
+          ``Z[n-p-2:end]`` in ``Z``. All other non-singleton clusters are
+          contracted into leaf nodes.
+
+        ``'level'``
+          No more than ``p`` levels of the dendrogram tree are displayed.
+          A "level" includes all nodes with ``p`` merges from the final merge.
+
+          Note: ``'mtica'`` is an alias for ``'level'`` that's kept for
+          backward compatibility.
+
+    color_threshold : double, optional
+        For brevity, let :math:`t` be the ``color_threshold``.
+        Colors all the descendent links below a cluster node
+        :math:`k` the same color if :math:`k` is the first node below
+        the cut threshold :math:`t`. All links connecting nodes with
+        distances greater than or equal to the threshold are colored
+        with de default matplotlib color ``'C0'``. If :math:`t` is less
+        than or equal to zero, all nodes are colored ``'C0'``.
+        If ``color_threshold`` is None or 'default',
+        corresponding with MATLAB(TM) behavior, the threshold is set to
+        ``0.7*max(Z[:,2])``.
+
+    get_leaves : bool, optional
+        Includes a list ``R['leaves']=H`` in the result
+        dictionary. For each :math:`i`, ``H[i] == j``, cluster node
+        ``j`` appears in position ``i`` in the left-to-right traversal
+        of the leaves, where :math:`j < 2n-1` and :math:`i < n`.
+    orientation : str, optional
+        The direction to plot the dendrogram, which can be any
+        of the following strings:
+
+        ``'top'``
+          Plots the root at the top, and plot descendent links going downwards.
+          (default).
+
+        ``'bottom'``
+          Plots the root at the bottom, and plot descendent links going
+          upwards.
+
+        ``'left'``
+          Plots the root at the left, and plot descendent links going right.
+
+        ``'right'``
+          Plots the root at the right, and plot descendent links going left.
+
+    labels : ndarray, optional
+        By default, ``labels`` is None so the index of the original observation
+        is used to label the leaf nodes.  Otherwise, this is an :math:`n`-sized
+        sequence, with ``n == Z.shape[0] + 1``. The ``labels[i]`` value is the
+        text to put under the :math:`i` th leaf node only if it corresponds to
+        an original observation and not a non-singleton cluster.
+    count_sort : str or bool, optional
+        For each node n, the order (visually, from left-to-right) n's
+        two descendent links are plotted is determined by this
+        parameter, which can be any of the following values:
+
+        ``False``
+          Nothing is done.
+
+        ``'ascending'`` or ``True``
+          The child with the minimum number of original objects in its cluster
+          is plotted first.
+
+        ``'descending'``
+          The child with the maximum number of original objects in its cluster
+          is plotted first.
+
+        Note, ``distance_sort`` and ``count_sort`` cannot both be True.
+    distance_sort : str or bool, optional
+        For each node n, the order (visually, from left-to-right) n's
+        two descendent links are plotted is determined by this
+        parameter, which can be any of the following values:
+
+        ``False``
+          Nothing is done.
+
+        ``'ascending'`` or ``True``
+          The child with the minimum distance between its direct descendents is
+          plotted first.
+
+        ``'descending'``
+          The child with the maximum distance between its direct descendents is
+          plotted first.
+
+        Note ``distance_sort`` and ``count_sort`` cannot both be True.
+    show_leaf_counts : bool, optional
+         When True, leaf nodes representing :math:`k>1` original
+         observation are labeled with the number of observations they
+         contain in parentheses.
+    no_plot : bool, optional
+        When True, the final rendering is not performed. This is
+        useful if only the data structures computed for the rendering
+        are needed or if matplotlib is not available.
+    no_labels : bool, optional
+        When True, no labels appear next to the leaf nodes in the
+        rendering of the dendrogram.
+    leaf_rotation : double, optional
+        Specifies the angle (in degrees) to rotate the leaf
+        labels. When unspecified, the rotation is based on the number of
+        nodes in the dendrogram (default is 0).
+    leaf_font_size : int, optional
+        Specifies the font size (in points) of the leaf labels. When
+        unspecified, the size based on the number of nodes in the
+        dendrogram.
+    leaf_label_func : lambda or function, optional
+        When ``leaf_label_func`` is a callable function, for each
+        leaf with cluster index :math:`k < 2n-1`. The function
+        is expected to return a string with the label for the
+        leaf.
+
+        Indices :math:`k < n` correspond to original observations
+        while indices :math:`k \\geq n` correspond to non-singleton
+        clusters.
+
+        For example, to label singletons with their node id and
+        non-singletons with their id, count, and inconsistency
+        coefficient, simply do::
+
+            # First define the leaf label function.
+            def llf(id):
+                if id < n:
+                    return str(id)
+                else:
+                    return '[%d %d %1.2f]' % (id, count, R[n-id,3])
+
+            # The text for the leaf nodes is going to be big so force
+            # a rotation of 90 degrees.
+            dendrogram(Z, leaf_label_func=llf, leaf_rotation=90)
+
+            # leaf_label_func can also be used together with ``truncate_mode``,
+            # in which case you will get your leaves labeled after truncation:
+            dendrogram(Z, leaf_label_func=llf, leaf_rotation=90,
+                       truncate_mode='level', p=2)
+
+    show_contracted : bool, optional
+        When True the heights of non-singleton nodes contracted
+        into a leaf node are plotted as crosses along the link
+        connecting that leaf node.  This really is only useful when
+        truncation is used (see ``truncate_mode`` parameter).
+    link_color_func : callable, optional
+        If given, `link_color_function` is called with each non-singleton id
+        corresponding to each U-shaped link it will paint. The function is
+        expected to return the color to paint the link, encoded as a matplotlib
+        color string code. For example::
+
+            dendrogram(Z, link_color_func=lambda k: colors[k])
+
+        colors the direct links below each untruncated non-singleton node
+        ``k`` using ``colors[k]``.
+    ax : matplotlib Axes instance, optional
+        If None and `no_plot` is not True, the dendrogram will be plotted
+        on the current axes.  Otherwise if `no_plot` is not True the
+        dendrogram will be plotted on the given ``Axes`` instance. This can be
+        useful if the dendrogram is part of a more complex figure.
+    above_threshold_color : str, optional
+        This matplotlib color string sets the color of the links above the
+        color_threshold. The default is ``'C0'``.
+
+    Returns
+    -------
+    R : dict
+        A dictionary of data structures computed to render the
+        dendrogram. Its has the following keys:
+
+        ``'color_list'``
+          A list of color names. The k'th element represents the color of the
+          k'th link.
+
+        ``'icoord'`` and ``'dcoord'``
+          Each of them is a list of lists. Let ``icoord = [I1, I2, ..., Ip]``
+          where ``Ik = [xk1, xk2, xk3, xk4]`` and ``dcoord = [D1, D2, ..., Dp]``
+          where ``Dk = [yk1, yk2, yk3, yk4]``, then the k'th link painted is
+          ``(xk1, yk1)`` - ``(xk2, yk2)`` - ``(xk3, yk3)`` - ``(xk4, yk4)``.
+
+        ``'ivl'``
+          A list of labels corresponding to the leaf nodes.
+
+        ``'leaves'``
+          For each i, ``H[i] == j``, cluster node ``j`` appears in position
+          ``i`` in the left-to-right traversal of the leaves, where
+          :math:`j < 2n-1` and :math:`i < n`. If ``j`` is less than ``n``, the
+          ``i``-th leaf node corresponds to an original observation.
+          Otherwise, it corresponds to a non-singleton cluster.
+
+        ``'leaves_color_list'``
+          A list of color names. The k'th element represents the color of the
+          k'th leaf.
+
+    See Also
+    --------
+    linkage, set_link_color_palette
+
+    Notes
+    -----
+    It is expected that the distances in ``Z[:,2]`` be monotonic, otherwise
+    crossings appear in the dendrogram.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster import hierarchy
+    >>> import matplotlib.pyplot as plt
+
+    A very basic example:
+
+    >>> ytdist = np.array([662., 877., 255., 412., 996., 295., 468., 268.,
+    ...                    400., 754., 564., 138., 219., 869., 669.])
+    >>> Z = hierarchy.linkage(ytdist, 'single')
+    >>> plt.figure()
+    >>> dn = hierarchy.dendrogram(Z)
+
+    Now, plot in given axes, improve the color scheme and use both vertical and
+    horizontal orientations:
+
+    >>> hierarchy.set_link_color_palette(['m', 'c', 'y', 'k'])
+    >>> fig, axes = plt.subplots(1, 2, figsize=(8, 3))
+    >>> dn1 = hierarchy.dendrogram(Z, ax=axes[0], above_threshold_color='y',
+    ...                            orientation='top')
+    >>> dn2 = hierarchy.dendrogram(Z, ax=axes[1],
+    ...                            above_threshold_color='#bcbddc',
+    ...                            orientation='right')
+    >>> hierarchy.set_link_color_palette(None)  # reset to default after use
+    >>> plt.show()
+
+    """
+    # This feature was thought about but never implemented (still useful?):
+    #
+    #         ... = dendrogram(..., leaves_order=None)
+    #
+    #         Plots the leaves in the order specified by a vector of
+    #         original observation indices. If the vector contains duplicates
+    #         or results in a crossing, an exception will be thrown. Passing
+    #         None orders leaf nodes based on the order they appear in the
+    #         pre-order traversal.
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', xp=xp)
+
+    if orientation not in ["top", "left", "bottom", "right"]:
+        raise ValueError("orientation must be one of 'top', 'left', "
+                         "'bottom', or 'right'")
+
+    if labels is not None:
+        try:
+            len_labels = len(labels)
+        except (TypeError, AttributeError):
+            len_labels = labels.shape[0]
+        if Z.shape[0] + 1 != len_labels:
+            raise ValueError("Dimensions of Z and labels must be consistent.")
+
+    _is_valid_linkage(Z, throw=True, name='Z', materialize=True, xp=xp)
+    Zs = Z.shape
+    n = Zs[0] + 1
+    if isinstance(p, int | float):
+        p = int(p)
+    else:
+        raise TypeError('The second argument must be a number')
+
+    if truncate_mode not in ('lastp', 'mtica', 'level', 'none', None):
+        # 'mtica' is kept working for backwards compat.
+        raise ValueError('Invalid truncation mode.')
+
+    if truncate_mode == 'lastp':
+        if p > n or p == 0:
+            p = n
+
+    if truncate_mode == 'mtica':
+        # 'mtica' is an alias
+        truncate_mode = 'level'
+
+    if truncate_mode == 'level':
+        if p <= 0:
+            p = np.inf
+
+    if get_leaves:
+        lvs = []
+    else:
+        lvs = None
+
+    icoord_list = []
+    dcoord_list = []
+    color_list = []
+    current_color = [0]
+    currently_below_threshold = [False]
+    ivl = []  # list of leaves
+
+    if color_threshold is None or (isinstance(color_threshold, str) and
+                                   color_threshold == 'default'):
+        color_threshold = xp.max(Z[:, 2]) * 0.7
+
+    R = {'icoord': icoord_list, 'dcoord': dcoord_list, 'ivl': ivl,
+         'leaves': lvs, 'color_list': color_list}
+
+    # Empty list will be filled in _dendrogram_calculate_info
+    contraction_marks = [] if show_contracted else None
+
+    _dendrogram_calculate_info(
+        Z=Z, p=p,
+        truncate_mode=truncate_mode,
+        color_threshold=color_threshold,
+        get_leaves=get_leaves,
+        orientation=orientation,
+        labels=labels,
+        count_sort=count_sort,
+        distance_sort=distance_sort,
+        show_leaf_counts=show_leaf_counts,
+        i=2*n - 2,
+        iv=0.0,
+        ivl=ivl,
+        n=n,
+        icoord_list=icoord_list,
+        dcoord_list=dcoord_list,
+        lvs=lvs,
+        current_color=current_color,
+        color_list=color_list,
+        currently_below_threshold=currently_below_threshold,
+        leaf_label_func=leaf_label_func,
+        contraction_marks=contraction_marks,
+        link_color_func=link_color_func,
+        above_threshold_color=above_threshold_color)
+
+    if not no_plot:
+        mh = xp.max(Z[:, 2])
+        _plot_dendrogram(icoord_list, dcoord_list, ivl, p, n, mh, orientation,
+                         no_labels, color_list,
+                         leaf_font_size=leaf_font_size,
+                         leaf_rotation=leaf_rotation,
+                         contraction_marks=contraction_marks,
+                         ax=ax,
+                         above_threshold_color=above_threshold_color)
+
+    R["leaves_color_list"] = _get_leaves_color_list(R)
+
+    return R
+
+
+def _get_leaves_color_list(R):
+    leaves_color_list = [None] * len(R['leaves'])
+    for link_x, link_y, link_color in zip(R['icoord'],
+                                          R['dcoord'],
+                                          R['color_list']):
+        for (xi, yi) in zip(link_x, link_y):
+            if yi == 0.0 and (xi % 5 == 0 and xi % 2 == 1):
+                # if yi is 0.0 and xi is divisible by 5 and odd,
+                # the point is a leaf
+                # xi of leaves are      5, 15, 25, 35, ... (see `iv_ticks`)
+                # index of leaves are   0,  1,  2,  3, ... as below
+                leaf_index = (int(xi) - 5) // 10
+                # each leaf has a same color of its link.
+                leaves_color_list[leaf_index] = link_color
+    return leaves_color_list
+
+
+def _append_singleton_leaf_node(Z, p, n, level, lvs, ivl, leaf_label_func,
+                                i, labels):
+    # If the leaf id structure is not None and is a list then the caller
+    # to dendrogram has indicated that cluster id's corresponding to the
+    # leaf nodes should be recorded.
+
+    if lvs is not None:
+        lvs.append(int(i))
+
+    # If leaf node labels are to be displayed...
+    if ivl is not None:
+        # If a leaf_label_func has been provided, the label comes from the
+        # string returned from the leaf_label_func, which is a function
+        # passed to dendrogram.
+        if leaf_label_func:
+            ivl.append(leaf_label_func(int(i)))
+        else:
+            # Otherwise, if the dendrogram caller has passed a labels list
+            # for the leaf nodes, use it.
+            if labels is not None:
+                ivl.append(labels[int(i - n)])
+            else:
+                # Otherwise, use the id as the label for the leaf.x
+                ivl.append(str(int(i)))
+
+
+def _append_nonsingleton_leaf_node(Z, p, n, level, lvs, ivl, leaf_label_func,
+                                   i, labels, show_leaf_counts):
+    # If the leaf id structure is not None and is a list then the caller
+    # to dendrogram has indicated that cluster id's corresponding to the
+    # leaf nodes should be recorded.
+
+    if lvs is not None:
+        lvs.append(int(i))
+    if ivl is not None:
+        if leaf_label_func:
+            ivl.append(leaf_label_func(int(i)))
+        else:
+            if show_leaf_counts:
+                ivl.append("(" + str(np.asarray(Z[i - n, 3], dtype=np.int64)) + ")")
+            else:
+                ivl.append("")
+
+
+def _append_contraction_marks(Z, iv, i, n, contraction_marks, xp):
+    _append_contraction_marks_sub(Z, iv, int_floor(Z[i - n, 0], xp),
+                                  n, contraction_marks, xp)
+    _append_contraction_marks_sub(Z, iv, int_floor(Z[i - n, 1], xp),
+                                  n, contraction_marks, xp)
+
+
+def _append_contraction_marks_sub(Z, iv, i, n, contraction_marks, xp):
+    if i >= n:
+        contraction_marks.append((iv, Z[i - n, 2]))
+        _append_contraction_marks_sub(Z, iv, int_floor(Z[i - n, 0], xp),
+                                      n, contraction_marks, xp)
+        _append_contraction_marks_sub(Z, iv, int_floor(Z[i - n, 1], xp),
+                                      n, contraction_marks, xp)
+
+
+def _dendrogram_calculate_info(Z, p, truncate_mode,
+                               color_threshold=np.inf, get_leaves=True,
+                               orientation='top', labels=None,
+                               count_sort=False, distance_sort=False,
+                               show_leaf_counts=False, i=-1, iv=0.0,
+                               ivl=None, n=0, icoord_list=None, dcoord_list=None,
+                               lvs=None, mhr=False,
+                               current_color=None, color_list=None,
+                               currently_below_threshold=None,
+                               leaf_label_func=None, level=0,
+                               contraction_marks=None,
+                               link_color_func=None,
+                               above_threshold_color='C0'):
+    """
+    Calculate the endpoints of the links as well as the labels for the
+    the dendrogram rooted at the node with index i. iv is the independent
+    variable value to plot the left-most leaf node below the root node i
+    (if orientation='top', this would be the left-most x value where the
+    plotting of this root node i and its descendents should begin).
+
+    ivl is a list to store the labels of the leaf nodes. The leaf_label_func
+    is called whenever ivl != None, labels == None, and
+    leaf_label_func != None. When ivl != None and labels != None, the
+    labels list is used only for labeling the leaf nodes. When
+    ivl == None, no labels are generated for leaf nodes.
+
+    When get_leaves==True, a list of leaves is built as they are visited
+    in the dendrogram.
+
+    Returns a tuple with l being the independent variable coordinate that
+    corresponds to the midpoint of cluster to the left of cluster i if
+    i is non-singleton, otherwise the independent coordinate of the leaf
+    node if i is a leaf node.
+
+    Returns
+    -------
+    A tuple (left, w, h, md), where:
+        * left is the independent variable coordinate of the center of the
+          the U of the subtree
+
+        * w is the amount of space used for the subtree (in independent
+          variable units)
+
+        * h is the height of the subtree in dependent variable units
+
+        * md is the ``max(Z[*,2]``) for all nodes ``*`` below and including
+          the target node.
+
+    """
+    xp = array_namespace(Z)
+    if n == 0:
+        raise ValueError("Invalid singleton cluster count n.")
+
+    if i == -1:
+        raise ValueError("Invalid root cluster index i.")
+
+    if truncate_mode == 'lastp':
+        # If the node is a leaf node but corresponds to a non-singleton
+        # cluster, its label is either the empty string or the number of
+        # original observations belonging to cluster i.
+        if 2*n - p > i >= n:
+            d = Z[i - n, 2]
+            _append_nonsingleton_leaf_node(Z, p, n, level, lvs, ivl,
+                                           leaf_label_func, i, labels,
+                                           show_leaf_counts)
+            if contraction_marks is not None:
+                _append_contraction_marks(Z, iv + 5.0, i, n, contraction_marks, xp)
+            return (iv + 5.0, 10.0, 0.0, d)
+        elif i < n:
+            _append_singleton_leaf_node(Z, p, n, level, lvs, ivl,
+                                        leaf_label_func, i, labels)
+            return (iv + 5.0, 10.0, 0.0, 0.0)
+    elif truncate_mode == 'level':
+        if i > n and level > p:
+            d = Z[i - n, 2]
+            _append_nonsingleton_leaf_node(Z, p, n, level, lvs, ivl,
+                                           leaf_label_func, i, labels,
+                                           show_leaf_counts)
+            if contraction_marks is not None:
+                _append_contraction_marks(Z, iv + 5.0, i, n, contraction_marks, xp)
+            return (iv + 5.0, 10.0, 0.0, d)
+        elif i < n:
+            _append_singleton_leaf_node(Z, p, n, level, lvs, ivl,
+                                        leaf_label_func, i, labels)
+            return (iv + 5.0, 10.0, 0.0, 0.0)
+
+    # Otherwise, only truncate if we have a leaf node.
+    #
+    # Only place leaves if they correspond to original observations.
+    if i < n:
+        _append_singleton_leaf_node(Z, p, n, level, lvs, ivl,
+                                    leaf_label_func, i, labels)
+        return (iv + 5.0, 10.0, 0.0, 0.0)
+
+    # !!! Otherwise, we don't have a leaf node, so work on plotting a
+    # non-leaf node.
+    # Actual indices of a and b
+    aa = int_floor(Z[i - n, 0], xp)
+    ab = int_floor(Z[i - n, 1], xp)
+    if aa >= n:
+        # The number of singletons below cluster a
+        na = Z[aa - n, 3]
+        # The distance between a's two direct children.
+        da = Z[aa - n, 2]
+    else:
+        na = 1
+        da = 0.0
+    if ab >= n:
+        nb = Z[ab - n, 3]
+        db = Z[ab - n, 2]
+    else:
+        nb = 1
+        db = 0.0
+
+    if count_sort == 'ascending' or count_sort is True:
+        # If a has a count greater than b, it and its descendents should
+        # be drawn to the right. Otherwise, to the left.
+        if na > nb:
+            # The cluster index to draw to the left (ua) will be ab
+            # and the one to draw to the right (ub) will be aa
+            ua = ab
+            ub = aa
+        else:
+            ua = aa
+            ub = ab
+    elif count_sort == 'descending':
+        # If a has a count less than or equal to b, it and its
+        # descendents should be drawn to the left. Otherwise, to
+        # the right.
+        if na > nb:
+            ua = aa
+            ub = ab
+        else:
+            ua = ab
+            ub = aa
+    elif distance_sort == 'ascending' or distance_sort is True:
+        # If a has a distance greater than b, it and its descendents should
+        # be drawn to the right. Otherwise, to the left.
+        if da > db:
+            ua = ab
+            ub = aa
+        else:
+            ua = aa
+            ub = ab
+    elif distance_sort == 'descending':
+        # If a has a distance less than or equal to b, it and its
+        # descendents should be drawn to the left. Otherwise, to
+        # the right.
+        if da > db:
+            ua = aa
+            ub = ab
+        else:
+            ua = ab
+            ub = aa
+    else:
+        ua = aa
+        ub = ab
+
+    # Updated iv variable and the amount of space used.
+    (uiva, uwa, uah, uamd) = \
+        _dendrogram_calculate_info(
+            Z=Z, p=p,
+            truncate_mode=truncate_mode,
+            color_threshold=color_threshold,
+            get_leaves=get_leaves,
+            orientation=orientation,
+            labels=labels,
+            count_sort=count_sort,
+            distance_sort=distance_sort,
+            show_leaf_counts=show_leaf_counts,
+            i=ua, iv=iv, ivl=ivl, n=n,
+            icoord_list=icoord_list,
+            dcoord_list=dcoord_list, lvs=lvs,
+            current_color=current_color,
+            color_list=color_list,
+            currently_below_threshold=currently_below_threshold,
+            leaf_label_func=leaf_label_func,
+            level=level + 1, contraction_marks=contraction_marks,
+            link_color_func=link_color_func,
+            above_threshold_color=above_threshold_color)
+
+    h = Z[i - n, 2]
+    if h >= color_threshold or color_threshold <= 0:
+        c = above_threshold_color
+
+        if currently_below_threshold[0]:
+            current_color[0] = (current_color[0] + 1) % len(_link_line_colors)
+        currently_below_threshold[0] = False
+    else:
+        currently_below_threshold[0] = True
+        c = _link_line_colors[current_color[0]]
+
+    (uivb, uwb, ubh, ubmd) = \
+        _dendrogram_calculate_info(
+            Z=Z, p=p,
+            truncate_mode=truncate_mode,
+            color_threshold=color_threshold,
+            get_leaves=get_leaves,
+            orientation=orientation,
+            labels=labels,
+            count_sort=count_sort,
+            distance_sort=distance_sort,
+            show_leaf_counts=show_leaf_counts,
+            i=ub, iv=iv + uwa, ivl=ivl, n=n,
+            icoord_list=icoord_list,
+            dcoord_list=dcoord_list, lvs=lvs,
+            current_color=current_color,
+            color_list=color_list,
+            currently_below_threshold=currently_below_threshold,
+            leaf_label_func=leaf_label_func,
+            level=level + 1, contraction_marks=contraction_marks,
+            link_color_func=link_color_func,
+            above_threshold_color=above_threshold_color)
+
+    max_dist = max(uamd, ubmd, h)
+
+    icoord_list.append([uiva, uiva, uivb, uivb])
+    dcoord_list.append([uah, h, h, ubh])
+    if link_color_func is not None:
+        v = link_color_func(int(i))
+        if not isinstance(v, str):
+            raise TypeError("link_color_func must return a matplotlib "
+                            "color string!")
+        color_list.append(v)
+    else:
+        color_list.append(c)
+
+    return (((uiva + uivb) / 2), uwa + uwb, h, max_dist)
+
+
+@xp_capabilities(cpu_only=True,
+                 warnings=[("dask.array", "see notes"), ("jax.numpy", "see notes")])
+def is_isomorphic(T1, T2):
+    """
+    Determine if two different cluster assignments are equivalent.
+
+    Parameters
+    ----------
+    T1 : array_like
+        An assignment of singleton cluster ids to flat cluster ids.
+    T2 : array_like
+        An assignment of singleton cluster ids to flat cluster ids.
+
+    Returns
+    -------
+    b : bool
+        Whether the flat cluster assignments `T1` and `T2` are
+        equivalent.
+
+    Notes
+    -----
+    *Array API support (experimental):* If the input is a lazy Array (e.g. Dask
+    or JAX), the return value will be a 0-dimensional bool Array.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    fcluster : for the creation of flat cluster assignments.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import fcluster, is_isomorphic
+    >>> from scipy.cluster.hierarchy import single, complete
+    >>> from scipy.spatial.distance import pdist
+
+    Two flat cluster assignments can be isomorphic if they represent the same
+    cluster assignment, with different labels.
+
+    For example, we can use the `scipy.cluster.hierarchy.single` method
+    and flatten the output to four clusters:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = single(pdist(X))
+    >>> T = fcluster(Z, 1, criterion='distance')
+    >>> T
+    array([3, 3, 3, 4, 4, 4, 2, 2, 2, 1, 1, 1], dtype=int32)
+
+    We can then do the same using the
+    `scipy.cluster.hierarchy.complete`: method:
+
+    >>> Z = complete(pdist(X))
+    >>> T_ = fcluster(Z, 1.5, criterion='distance')
+    >>> T_
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+
+    As we can see, in both cases we obtain four clusters and all the data
+    points are distributed in the same way - the only thing that changes
+    are the flat cluster labels (3 => 1, 4 =>2, 2 =>3 and 4 =>1), so both
+    cluster assignments are isomorphic:
+
+    >>> is_isomorphic(T, T_)
+    True
+
+    """
+    xp = array_namespace(T1, T2)
+    T1 = _asarray(T1, xp=xp)
+    T2 = _asarray(T2, xp=xp)
+
+    if T1.ndim != 1:
+        raise ValueError('T1 must be one-dimensional.')
+    if T2.ndim != 1:
+        raise ValueError('T2 must be one-dimensional.')
+    if T1.shape != T2.shape:
+        raise ValueError('T1 and T2 must have the same number of elements.')
+
+    def py_is_isomorphic(T1, T2):
+        d1 = {}
+        d2 = {}
+        for t1, t2 in zip(T1, T2):
+            if t1 in d1:
+                if t2 not in d2:
+                    return False
+                if d1[t1] != t2 or d2[t2] != t1:
+                    return False
+            elif t2 in d2:
+                return False
+            else:
+                d1[t1] = t2
+                d2[t2] = t1
+        return True
+
+    res = xpx.lazy_apply(py_is_isomorphic, T1, T2,
+                         shape=(), dtype=xp.bool,
+                         as_numpy=True, xp=xp)
+    return res if is_lazy_array(res) else bool(res)
+
+
+@lazy_cython
+def maxdists(Z):
+    """
+    Return the maximum distance between any non-singleton cluster.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as a matrix. See
+        ``linkage`` for more information.
+
+    Returns
+    -------
+    maxdists : ndarray
+        A ``(n-1)`` sized numpy array of doubles; ``MD[i]`` represents
+        the maximum distance between any cluster (including
+        singletons) below and including the node with index i. More
+        specifically, ``MD[i] = Z[Q(i)-n, 2].max()`` where ``Q(i)`` is the
+        set of all node indices below and including node i.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    is_monotonic : for testing for monotonicity of a linkage matrix.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import median, maxdists
+    >>> from scipy.spatial.distance import pdist
+
+    Given a linkage matrix ``Z``, `scipy.cluster.hierarchy.maxdists`
+    computes for each new cluster generated (i.e., for each row of the linkage
+    matrix) what is the maximum distance between any two child clusters.
+
+    Due to the nature of hierarchical clustering, in many cases this is going
+    to be just the distance between the two child clusters that were merged
+    to form the current one - that is, Z[:,2].
+
+    However, for non-monotonic cluster assignments such as
+    `scipy.cluster.hierarchy.median` clustering this is not always the
+    case: There may be cluster formations were the distance between the two
+    clusters merged is smaller than the distance between their children.
+
+    We can see this in an example:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = median(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.11803399,  3.        ],
+           [ 5.        , 13.        ,  1.11803399,  3.        ],
+           [ 8.        , 15.        ,  1.11803399,  3.        ],
+           [11.        , 14.        ,  1.11803399,  3.        ],
+           [18.        , 19.        ,  3.        ,  6.        ],
+           [16.        , 17.        ,  3.5       ,  6.        ],
+           [20.        , 21.        ,  3.25      , 12.        ]])
+    >>> maxdists(Z)
+    array([1.        , 1.        , 1.        , 1.        , 1.11803399,
+           1.11803399, 1.11803399, 1.11803399, 3.        , 3.5       ,
+           3.5       ])
+
+    Note that while the distance between the two clusters merged when creating the
+    last cluster is 3.25, there are two children (clusters 16 and 17) whose distance
+    is larger (3.5). Thus, `scipy.cluster.hierarchy.maxdists` returns 3.5 in
+    this case.
+
+    """
+    xp = array_namespace(Z)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    def cy_maxdists(Z, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+        MD = np.zeros((Z.shape[0],))
+        _hierarchy.get_max_dist_for_each_cluster(Z, MD, Z.shape[0] + 1)
+        return MD
+
+    return xpx.lazy_apply(cy_maxdists, Z, validate=is_lazy_array(Z),
+                          shape=(Z.shape[0], ), dtype=xp.float64,
+                          as_numpy=True, xp=xp)
+
+
+@lazy_cython
+def maxinconsts(Z, R):
+    """
+    Return the maximum inconsistency coefficient for each
+    non-singleton cluster and its children.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as a matrix. See
+        `linkage` for more information.
+    R : ndarray
+        The inconsistency matrix.
+
+    Returns
+    -------
+    MI : ndarray
+        A monotonic ``(n-1)``-sized numpy array of doubles.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    inconsistent : for the creation of a inconsistency matrix.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import median, inconsistent, maxinconsts
+    >>> from scipy.spatial.distance import pdist
+
+    Given a data set ``X``, we can apply a clustering method to obtain a
+    linkage matrix ``Z``. `scipy.cluster.hierarchy.inconsistent` can
+    be also used to obtain the inconsistency matrix ``R`` associated to
+    this clustering process:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = median(pdist(X))
+    >>> R = inconsistent(Z)
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.11803399,  3.        ],
+           [ 5.        , 13.        ,  1.11803399,  3.        ],
+           [ 8.        , 15.        ,  1.11803399,  3.        ],
+           [11.        , 14.        ,  1.11803399,  3.        ],
+           [18.        , 19.        ,  3.        ,  6.        ],
+           [16.        , 17.        ,  3.5       ,  6.        ],
+           [20.        , 21.        ,  3.25      , 12.        ]])
+    >>> R
+    array([[1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.74535599, 1.08655358, 3.        , 1.15470054],
+           [1.91202266, 1.37522872, 3.        , 1.15470054],
+           [3.25      , 0.25      , 3.        , 0.        ]])
+
+    Here, `scipy.cluster.hierarchy.maxinconsts` can be used to compute
+    the maximum value of the inconsistency statistic (the last column of
+    ``R``) for each non-singleton cluster and its children:
+
+    >>> maxinconsts(Z, R)
+    array([0.        , 0.        , 0.        , 0.        , 0.70710678,
+           0.70710678, 0.70710678, 0.70710678, 1.15470054, 1.15470054,
+           1.15470054])
+
+    """
+    xp = array_namespace(Z, R)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    R = _asarray(R, order='C', dtype=xp.float64, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+    _is_valid_im(R, throw=True, name='R', xp=xp)
+
+    if Z.shape[0] != R.shape[0]:
+        raise ValueError("The inconsistency matrix and linkage matrix each "
+                         "have a different number of rows.")
+    
+    def cy_maxinconsts(Z, R, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+            _is_valid_im(R, throw=True, name='R', xp=np)
+        n = Z.shape[0] + 1
+        MI = np.zeros((n - 1,))
+        _hierarchy.get_max_Rfield_for_each_cluster(Z, R, MI, n, 3)
+        return MI
+
+    return xpx.lazy_apply(cy_maxinconsts, Z, R, validate=is_lazy_array(Z),
+                          shape=(Z.shape[0], ), dtype=xp.float64,
+                          as_numpy=True, xp=xp)
+
+
+@lazy_cython
+def maxRstat(Z, R, i):
+    """
+    Return the maximum statistic for each non-singleton cluster and its
+    children.
+
+    Parameters
+    ----------
+    Z : array_like
+        The hierarchical clustering encoded as a matrix. See `linkage` for more
+        information.
+    R : array_like
+        The inconsistency matrix.
+    i : int
+        The column of `R` to use as the statistic.
+
+    Returns
+    -------
+    MR : ndarray
+        Calculates the maximum statistic for the i'th column of the
+        inconsistency matrix `R` for each non-singleton cluster
+        node. ``MR[j]`` is the maximum over ``R[Q(j)-n, i]``, where
+        ``Q(j)`` the set of all node ids corresponding to nodes below
+        and including ``j``.
+
+    See Also
+    --------
+    linkage : for a description of what a linkage matrix is.
+    inconsistent : for the creation of a inconsistency matrix.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import median, inconsistent, maxRstat
+    >>> from scipy.spatial.distance import pdist
+
+    Given a data set ``X``, we can apply a clustering method to obtain a
+    linkage matrix ``Z``. `scipy.cluster.hierarchy.inconsistent` can
+    be also used to obtain the inconsistency matrix ``R`` associated to
+    this clustering process:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = median(pdist(X))
+    >>> R = inconsistent(Z)
+    >>> R
+    array([[1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.        , 0.        , 1.        , 0.        ],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.05901699, 0.08346263, 2.        , 0.70710678],
+           [1.74535599, 1.08655358, 3.        , 1.15470054],
+           [1.91202266, 1.37522872, 3.        , 1.15470054],
+           [3.25      , 0.25      , 3.        , 0.        ]])
+
+    `scipy.cluster.hierarchy.maxRstat` can be used to compute
+    the maximum value of each column of ``R``, for each non-singleton
+    cluster and its children:
+
+    >>> maxRstat(Z, R, 0)
+    array([1.        , 1.        , 1.        , 1.        , 1.05901699,
+           1.05901699, 1.05901699, 1.05901699, 1.74535599, 1.91202266,
+           3.25      ])
+    >>> maxRstat(Z, R, 1)
+    array([0.        , 0.        , 0.        , 0.        , 0.08346263,
+           0.08346263, 0.08346263, 0.08346263, 1.08655358, 1.37522872,
+           1.37522872])
+    >>> maxRstat(Z, R, 3)
+    array([0.        , 0.        , 0.        , 0.        , 0.70710678,
+           0.70710678, 0.70710678, 0.70710678, 1.15470054, 1.15470054,
+           1.15470054])
+
+    """
+    xp = array_namespace(Z, R)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    R = _asarray(R, order='C', dtype=xp.float64, xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+    _is_valid_im(R, throw=True, name='R', xp=xp)
+
+    if not isinstance(i, int):
+        raise TypeError('The third argument must be an integer.')
+
+    if i < 0 or i > 3:
+        raise ValueError('i must be an integer between 0 and 3 inclusive.')
+
+    if Z.shape[0] != R.shape[0]:
+        raise ValueError("The inconsistency matrix and linkage matrix each "
+                         "have a different number of rows.")
+
+    def cy_maxRstat(Z, R, i, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+            _is_valid_im(R, throw=True, name='R', xp=np)
+        MR = np.zeros((Z.shape[0],))
+        n = Z.shape[0] + 1
+        _hierarchy.get_max_Rfield_for_each_cluster(Z, R, MR, n, i)
+        return MR
+
+    return xpx.lazy_apply(cy_maxRstat, Z, R, i=i, validate=is_lazy_array(Z),
+                          shape=(Z.shape[0], ), dtype=xp.float64,
+                          as_numpy=True, xp=xp)
+
+
+# Data-dependent output shape makes it impossible to use jax.jit
+@xp_capabilities(cpu_only=True, reason="Cython code", jax_jit=False,
+                 warnings=[("dask.array", "merges chunks")])
+def leaders(Z, T):
+    """
+    Return the root nodes in a hierarchical clustering.
+
+    Returns the root nodes in a hierarchical clustering corresponding
+    to a cut defined by a flat cluster assignment vector ``T``. See
+    the ``fcluster`` function for more information on the format of ``T``.
+
+    For each flat cluster :math:`j` of the :math:`k` flat clusters
+    represented in the n-sized flat cluster assignment vector ``T``,
+    this function finds the lowest cluster node :math:`i` in the linkage
+    tree Z, such that:
+
+      * leaf descendants belong only to flat cluster j
+        (i.e., ``T[p]==j`` for all :math:`p` in :math:`S(i)`, where
+        :math:`S(i)` is the set of leaf ids of descendant leaf nodes
+        with cluster node :math:`i`)
+
+      * there does not exist a leaf that is not a descendant with
+        :math:`i` that also belongs to cluster :math:`j`
+        (i.e., ``T[q]!=j`` for all :math:`q` not in :math:`S(i)`). If
+        this condition is violated, ``T`` is not a valid cluster
+        assignment vector, and an exception will be thrown.
+
+    Parameters
+    ----------
+    Z : ndarray
+        The hierarchical clustering encoded as a matrix. See
+        `linkage` for more information.
+    T : ndarray
+        The flat cluster assignment vector.
+
+    Returns
+    -------
+    L : ndarray
+        The leader linkage node id's stored as a k-element 1-D array,
+        where ``k`` is the number of flat clusters found in ``T``.
+
+        ``L[j]=i`` is the linkage cluster node id that is the
+        leader of flat cluster with id M[j]. If ``i < n``, ``i``
+        corresponds to an original observation, otherwise it
+        corresponds to a non-singleton cluster.
+    M : ndarray
+        The leader linkage node id's stored as a k-element 1-D array, where
+        ``k`` is the number of flat clusters found in ``T``. This allows the
+        set of flat cluster ids to be any arbitrary set of ``k`` integers.
+
+        For example: if ``L[3]=2`` and ``M[3]=8``, the flat cluster with
+        id 8's leader is linkage node 2.
+
+    See Also
+    --------
+    fcluster : for the creation of flat cluster assignments.
+
+    Examples
+    --------
+    >>> from scipy.cluster.hierarchy import ward, fcluster, leaders
+    >>> from scipy.spatial.distance import pdist
+
+    Given a linkage matrix ``Z`` - obtained after apply a clustering method
+    to a dataset ``X`` - and a flat cluster assignment array ``T``:
+
+    >>> X = [[0, 0], [0, 1], [1, 0],
+    ...      [0, 4], [0, 3], [1, 4],
+    ...      [4, 0], [3, 0], [4, 1],
+    ...      [4, 4], [3, 4], [4, 3]]
+
+    >>> Z = ward(pdist(X))
+    >>> Z
+    array([[ 0.        ,  1.        ,  1.        ,  2.        ],
+           [ 3.        ,  4.        ,  1.        ,  2.        ],
+           [ 6.        ,  7.        ,  1.        ,  2.        ],
+           [ 9.        , 10.        ,  1.        ,  2.        ],
+           [ 2.        , 12.        ,  1.29099445,  3.        ],
+           [ 5.        , 13.        ,  1.29099445,  3.        ],
+           [ 8.        , 14.        ,  1.29099445,  3.        ],
+           [11.        , 15.        ,  1.29099445,  3.        ],
+           [16.        , 17.        ,  5.77350269,  6.        ],
+           [18.        , 19.        ,  5.77350269,  6.        ],
+           [20.        , 21.        ,  8.16496581, 12.        ]])
+
+    >>> T = fcluster(Z, 3, criterion='distance')
+    >>> T
+    array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32)
+
+    `scipy.cluster.hierarchy.leaders` returns the indices of the nodes
+    in the dendrogram that are the leaders of each flat cluster:
+
+    >>> L, M = leaders(Z, T)
+    >>> L
+    array([16, 17, 18, 19], dtype=int32)
+
+    (remember that indices 0-11 point to the 12 data points in ``X``,
+    whereas indices 12-22 point to the 11 rows of ``Z``)
+
+    `scipy.cluster.hierarchy.leaders` also returns the indices of
+    the flat clusters in ``T``:
+
+    >>> M
+    array([1, 2, 3, 4], dtype=int32)
+
+    Notes
+    -----
+    *Array API support (experimental):* This function returns arrays
+    with data-dependent shape. In JAX, at the moment of writing this makes it
+    impossible to execute it inside `@jax.jit`.
+    """
+    xp = array_namespace(Z, T)
+    Z = _asarray(Z, order='C', dtype=xp.float64, xp=xp)
+    T = _asarray(T, order='C', xp=xp)
+    _is_valid_linkage(Z, throw=True, name='Z', xp=xp)
+
+    if T.dtype != xp.int32:
+        raise TypeError('T must be a 1-D array of dtype int32.')
+
+    if T.shape[0] != Z.shape[0] + 1:
+        raise ValueError('Mismatch: len(T)!=Z.shape[0] + 1.')
+
+    n_obs = Z.shape[0] + 1
+
+    def cy_leaders(Z, T, validate):
+        if validate:
+            _is_valid_linkage(Z, throw=True, name='Z', xp=np)
+        n_clusters = int(xpx.nunique(T))
+        L = np.zeros(n_clusters, dtype=np.int32)
+        M = np.zeros(n_clusters, dtype=np.int32)
+        s = _hierarchy.leaders(Z, T, L, M, n_clusters, n_obs)
+        if s >= 0:
+            raise ValueError('T is not a valid assignment vector. Error found '
+                             f'when examining linkage node {s} (< 2n-1).')
+        return L, M
+
+    return xpx.lazy_apply(cy_leaders, Z, T, validate=is_lazy_array(Z),
+                          shape=((None,), (None, )), dtype=(xp.int32, xp.int32),
+                          as_numpy=True, xp=xp)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/vq.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/vq.py
new file mode 100644
index 0000000000000000000000000000000000000000..65debbbde3ab3913be052cf56e3ffbae98dbe378
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/cluster/vq.py
@@ -0,0 +1,832 @@
+"""
+K-means clustering and vector quantization (:mod:`scipy.cluster.vq`)
+====================================================================
+
+Provides routines for k-means clustering, generating code books
+from k-means models and quantizing vectors by comparing them with
+centroids in a code book.
+
+.. autosummary::
+   :toctree: generated/
+
+   whiten -- Normalize a group of observations so each feature has unit variance
+   vq -- Calculate code book membership of a set of observation vectors
+   kmeans -- Perform k-means on a set of observation vectors forming k clusters
+   kmeans2 -- A different implementation of k-means with more methods
+           -- for initializing centroids
+
+Background information
+----------------------
+The k-means algorithm takes as input the number of clusters to
+generate, k, and a set of observation vectors to cluster. It
+returns a set of centroids, one for each of the k clusters. An
+observation vector is classified with the cluster number or
+centroid index of the centroid closest to it.
+
+A vector v belongs to cluster i if it is closer to centroid i than
+any other centroid. If v belongs to i, we say centroid i is the
+dominating centroid of v. The k-means algorithm tries to
+minimize distortion, which is defined as the sum of the squared distances
+between each observation vector and its dominating centroid.
+The minimization is achieved by iteratively reclassifying
+the observations into clusters and recalculating the centroids until
+a configuration is reached in which the centroids are stable. One can
+also define a maximum number of iterations.
+
+Since vector quantization is a natural application for k-means,
+information theory terminology is often used. The centroid index
+or cluster index is also referred to as a "code" and the table
+mapping codes to centroids and, vice versa, is often referred to as a
+"code book". The result of k-means, a set of centroids, can be
+used to quantize vectors. Quantization aims to find an encoding of
+vectors that reduces the expected distortion.
+
+All routines expect obs to be an M by N array, where the rows are
+the observation vectors. The codebook is a k by N array, where the
+ith row is the centroid of code word i. The observation vectors
+and centroids have the same feature dimension.
+
+As an example, suppose we wish to compress a 24-bit color image
+(each pixel is represented by one byte for red, one for blue, and
+one for green) before sending it over the web. By using a smaller
+8-bit encoding, we can reduce the amount of data by two
+thirds. Ideally, the colors for each of the 256 possible 8-bit
+encoding values should be chosen to minimize distortion of the
+color. Running k-means with k=256 generates a code book of 256
+codes, which fills up all possible 8-bit sequences. Instead of
+sending a 3-byte value for each pixel, the 8-bit centroid index
+(or code word) of the dominating centroid is transmitted. The code
+book is also sent over the wire so each 8-bit code can be
+translated back to a 24-bit pixel value representation. If the
+image of interest was of an ocean, we would expect many 24-bit
+blues to be represented by 8-bit codes. If it was an image of a
+human face, more flesh-tone colors would be represented in the
+code book.
+
+"""
+import warnings
+import numpy as np
+from collections import deque
+from scipy._lib._array_api import (_asarray, array_namespace, is_lazy_array,
+                                   xp_capabilities, xp_copy, xp_size)
+from scipy._lib._util import (check_random_state, rng_integers,
+                              _transition_to_rng)
+from scipy._lib import array_api_extra as xpx
+from scipy.spatial.distance import cdist
+
+from . import _vq
+
+__docformat__ = 'restructuredtext'
+
+__all__ = ['whiten', 'vq', 'kmeans', 'kmeans2']
+
+
+class ClusterError(Exception):
+    pass
+
+
+@xp_capabilities()
+def whiten(obs, check_finite=None):
+    """
+    Normalize a group of observations on a per feature basis.
+
+    Before running k-means, it is beneficial to rescale each feature
+    dimension of the observation set by its standard deviation (i.e. "whiten"
+    it - as in "white noise" where each frequency has equal power).
+    Each feature is divided by its standard deviation across all observations
+    to give it unit variance.
+
+    Parameters
+    ----------
+    obs : ndarray
+        Each row of the array is an observation.  The
+        columns are the features seen during each observation::
+
+            #        f0  f1  f2
+            obs = [[ 1., 1., 1.],  #o0
+                   [ 2., 2., 2.],  #o1
+                   [ 3., 3., 3.],  #o2
+                   [ 4., 4., 4.]]  #o3
+
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True for eager backends and False for lazy ones.
+
+    Returns
+    -------
+    result : ndarray
+        Contains the values in `obs` scaled by the standard deviation
+        of each column.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster.vq import whiten
+    >>> features  = np.array([[1.9, 2.3, 1.7],
+    ...                       [1.5, 2.5, 2.2],
+    ...                       [0.8, 0.6, 1.7,]])
+    >>> whiten(features)
+    array([[ 4.17944278,  2.69811351,  7.21248917],
+           [ 3.29956009,  2.93273208,  9.33380951],
+           [ 1.75976538,  0.7038557 ,  7.21248917]])
+
+    """
+    xp = array_namespace(obs)
+    if check_finite is None:
+        check_finite = not is_lazy_array(obs)
+    obs = _asarray(obs, check_finite=check_finite, xp=xp)
+    std_dev = xp.std(obs, axis=0)
+    zero_std_mask = std_dev == 0
+    std_dev = xpx.at(std_dev, zero_std_mask).set(1.0)
+    if check_finite and xp.any(zero_std_mask):
+        warnings.warn("Some columns have standard deviation zero. "
+                      "The values of these columns will not change.",
+                      RuntimeWarning, stacklevel=2)
+    return obs / std_dev
+
+
+@xp_capabilities(cpu_only=True, reason="uses spatial.distance.cdist",
+                 jax_jit=False, allow_dask_compute=True)
+def vq(obs, code_book, check_finite=True):
+    """
+    Assign codes from a code book to observations.
+
+    Assigns a code from a code book to each observation. Each
+    observation vector in the 'M' by 'N' `obs` array is compared with the
+    centroids in the code book and assigned the code of the closest
+    centroid.
+
+    The features in `obs` should have unit variance, which can be
+    achieved by passing them through the whiten function. The code
+    book can be created with the k-means algorithm or a different
+    encoding algorithm.
+
+    Parameters
+    ----------
+    obs : ndarray
+        Each row of the 'M' x 'N' array is an observation. The columns are
+        the "features" seen during each observation. The features must be
+        whitened first using the whiten function or something equivalent.
+    code_book : ndarray
+        The code book is usually generated using the k-means algorithm.
+        Each row of the array holds a different code, and the columns are
+        the features of the code::
+
+            #              f0  f1  f2  f3
+            code_book = [[ 1., 2., 3., 4.],  #c0
+                         [ 1., 2., 3., 4.],  #c1
+                         [ 1., 2., 3., 4.]]  #c2
+
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+
+    Returns
+    -------
+    code : ndarray
+        A length M array holding the code book index for each observation.
+    dist : ndarray
+        The distortion (distance) between the observation and its nearest
+        code.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster.vq import vq
+    >>> code_book = np.array([[1., 1., 1.],
+    ...                       [2., 2., 2.]])
+    >>> features  = np.array([[1.9, 2.3, 1.7],
+    ...                       [1.5, 2.5, 2.2],
+    ...                       [0.8, 0.6, 1.7]])
+    >>> vq(features, code_book)
+    (array([1, 1, 0], dtype=int32), array([0.43588989, 0.73484692, 0.83066239]))
+
+    """
+    xp = array_namespace(obs, code_book)
+    obs = _asarray(obs, xp=xp, check_finite=check_finite)
+    code_book = _asarray(code_book, xp=xp, check_finite=check_finite)
+    ct = xp.result_type(obs, code_book)
+
+    if xp.isdtype(ct, kind='real floating'):
+        c_obs = xp.astype(obs, ct, copy=False)
+        c_code_book = xp.astype(code_book, ct, copy=False)
+        c_obs = np.asarray(c_obs)
+        c_code_book = np.asarray(c_code_book)
+        result = _vq.vq(c_obs, c_code_book)
+        return xp.asarray(result[0]), xp.asarray(result[1])
+    return py_vq(obs, code_book, check_finite=False)
+
+
+def py_vq(obs, code_book, check_finite=True):
+    """ Python version of vq algorithm.
+
+    The algorithm computes the Euclidean distance between each
+    observation and every frame in the code_book.
+
+    Parameters
+    ----------
+    obs : ndarray
+        Expects a rank 2 array. Each row is one observation.
+    code_book : ndarray
+        Code book to use. Same format than obs. Should have same number of
+        features (e.g., columns) than obs.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+
+    Returns
+    -------
+    code : ndarray
+        code[i] gives the label of the ith obversation; its code is
+        code_book[code[i]].
+    mind_dist : ndarray
+        min_dist[i] gives the distance between the ith observation and its
+        corresponding code.
+
+    Notes
+    -----
+    This function is slower than the C version but works for
+    all input types. If the inputs have the wrong types for the
+    C versions of the function, this one is called as a last resort.
+
+    It is about 20 times slower than the C version.
+
+    """
+    xp = array_namespace(obs, code_book)
+    obs = _asarray(obs, xp=xp, check_finite=check_finite)
+    code_book = _asarray(code_book, xp=xp, check_finite=check_finite)
+
+    if obs.ndim != code_book.ndim:
+        raise ValueError("Observation and code_book should have the same rank")
+
+    if obs.ndim == 1:
+        obs = obs[:, xp.newaxis]
+        code_book = code_book[:, xp.newaxis]
+
+    # Once `cdist` has array API support, this `xp.asarray` call can be removed
+    dist = xp.asarray(cdist(obs, code_book))
+    code = xp.argmin(dist, axis=1)
+    min_dist = xp.min(dist, axis=1)
+    return code, min_dist
+
+
+def _kmeans(obs, guess, thresh=1e-5, xp=None):
+    """ "raw" version of k-means.
+
+    Returns
+    -------
+    code_book
+        The lowest distortion codebook found.
+    avg_dist
+        The average distance a observation is from a code in the book.
+        Lower means the code_book matches the data better.
+
+    See Also
+    --------
+    kmeans : wrapper around k-means
+
+    Examples
+    --------
+    Note: not whitened in this example.
+
+    >>> import numpy as np
+    >>> from scipy.cluster.vq import _kmeans
+    >>> features  = np.array([[ 1.9,2.3],
+    ...                       [ 1.5,2.5],
+    ...                       [ 0.8,0.6],
+    ...                       [ 0.4,1.8],
+    ...                       [ 1.0,1.0]])
+    >>> book = np.array((features[0],features[2]))
+    >>> _kmeans(features,book)
+    (array([[ 1.7       ,  2.4       ],
+           [ 0.73333333,  1.13333333]]), 0.40563916697728591)
+
+    """
+    xp = np if xp is None else xp
+    code_book = guess
+    diff = xp.inf
+    prev_avg_dists = deque([diff], maxlen=2)
+
+    np_obs = np.asarray(obs)
+    while diff > thresh:
+        # compute membership and distances between obs and code_book
+        obs_code, distort = vq(obs, code_book, check_finite=False)
+        prev_avg_dists.append(xp.mean(distort, axis=-1))
+        # recalc code_book as centroids of associated obs
+        obs_code = np.asarray(obs_code)
+        code_book, has_members = _vq.update_cluster_means(np_obs, obs_code,
+                                                          code_book.shape[0])
+        code_book = code_book[has_members]
+        code_book = xp.asarray(code_book)
+        diff = xp.abs(prev_avg_dists[0] - prev_avg_dists[1])
+
+    return code_book, prev_avg_dists[1]
+
+
+@xp_capabilities(cpu_only=True, jax_jit=False, allow_dask_compute=True)
+@_transition_to_rng("seed")
+def kmeans(obs, k_or_guess, iter=20, thresh=1e-5, check_finite=True,
+           *, rng=None):
+    """
+    Performs k-means on a set of observation vectors forming k clusters.
+
+    The k-means algorithm adjusts the classification of the observations
+    into clusters and updates the cluster centroids until the position of
+    the centroids is stable over successive iterations. In this
+    implementation of the algorithm, the stability of the centroids is
+    determined by comparing the absolute value of the change in the average
+    Euclidean distance between the observations and their corresponding
+    centroids against a threshold. This yields
+    a code book mapping centroids to codes and vice versa.
+
+    Parameters
+    ----------
+    obs : ndarray
+       Each row of the M by N array is an observation vector. The
+       columns are the features seen during each observation.
+       The features must be whitened first with the `whiten` function.
+
+    k_or_guess : int or ndarray
+       The number of centroids to generate. A code is assigned to
+       each centroid, which is also the row index of the centroid
+       in the code_book matrix generated.
+
+       The initial k centroids are chosen by randomly selecting
+       observations from the observation matrix. Alternatively,
+       passing a k by N array specifies the initial k centroids.
+
+    iter : int, optional
+       The number of times to run k-means, returning the codebook
+       with the lowest distortion. This argument is ignored if
+       initial centroids are specified with an array for the
+       ``k_or_guess`` parameter. This parameter does not represent the
+       number of iterations of the k-means algorithm.
+
+    thresh : float, optional
+       Terminates the k-means algorithm if the change in
+       distortion since the last k-means iteration is less than
+       or equal to threshold.
+
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+    Returns
+    -------
+    codebook : ndarray
+       A k by N array of k centroids. The ith centroid
+       codebook[i] is represented with the code i. The centroids
+       and codes generated represent the lowest distortion seen,
+       not necessarily the globally minimal distortion.
+       Note that the number of centroids is not necessarily the same as the
+       ``k_or_guess`` parameter, because centroids assigned to no observations
+       are removed during iterations.
+
+    distortion : float
+       The mean (non-squared) Euclidean distance between the observations
+       passed and the centroids generated. Note the difference to the standard
+       definition of distortion in the context of the k-means algorithm, which
+       is the sum of the squared distances.
+
+    See Also
+    --------
+    kmeans2 : a different implementation of k-means clustering
+       with more methods for generating initial centroids but without
+       using a distortion change threshold as a stopping criterion.
+
+    whiten : must be called prior to passing an observation matrix
+       to kmeans.
+
+    Notes
+    -----
+    For more functionalities or optimal performance, you can use
+    `sklearn.cluster.KMeans `_.
+    `This `_
+    is a benchmark result of several implementations.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.cluster.vq import vq, kmeans, whiten
+    >>> import matplotlib.pyplot as plt
+    >>> features  = np.array([[ 1.9,2.3],
+    ...                       [ 1.5,2.5],
+    ...                       [ 0.8,0.6],
+    ...                       [ 0.4,1.8],
+    ...                       [ 0.1,0.1],
+    ...                       [ 0.2,1.8],
+    ...                       [ 2.0,0.5],
+    ...                       [ 0.3,1.5],
+    ...                       [ 1.0,1.0]])
+    >>> whitened = whiten(features)
+    >>> book = np.array((whitened[0],whitened[2]))
+    >>> kmeans(whitened,book)
+    (array([[ 2.3110306 ,  2.86287398],    # random
+           [ 0.93218041,  1.24398691]]), 0.85684700941625547)
+
+    >>> codes = 3
+    >>> kmeans(whitened,codes)
+    (array([[ 2.3110306 ,  2.86287398],    # random
+           [ 1.32544402,  0.65607529],
+           [ 0.40782893,  2.02786907]]), 0.5196582527686241)
+
+    >>> # Create 50 datapoints in two clusters a and b
+    >>> pts = 50
+    >>> rng = np.random.default_rng()
+    >>> a = rng.multivariate_normal([0, 0], [[4, 1], [1, 4]], size=pts)
+    >>> b = rng.multivariate_normal([30, 10],
+    ...                             [[10, 2], [2, 1]],
+    ...                             size=pts)
+    >>> features = np.concatenate((a, b))
+    >>> # Whiten data
+    >>> whitened = whiten(features)
+    >>> # Find 2 clusters in the data
+    >>> codebook, distortion = kmeans(whitened, 2)
+    >>> # Plot whitened data and cluster centers in red
+    >>> plt.scatter(whitened[:, 0], whitened[:, 1])
+    >>> plt.scatter(codebook[:, 0], codebook[:, 1], c='r')
+    >>> plt.show()
+
+    """
+    if isinstance(k_or_guess, int):
+        xp = array_namespace(obs)
+    else:
+        xp = array_namespace(obs, k_or_guess)
+    obs = _asarray(obs, xp=xp, check_finite=check_finite)
+    guess = _asarray(k_or_guess, xp=xp, check_finite=check_finite)
+    if iter < 1:
+        raise ValueError(f"iter must be at least 1, got {iter}")
+
+    # Determine whether a count (scalar) or an initial guess (array) was passed.
+    if xp_size(guess) != 1:
+        if xp_size(guess) < 1:
+            raise ValueError(f"Asked for 0 clusters. Initial book was {guess}")
+        return _kmeans(obs, guess, thresh=thresh, xp=xp)
+
+    # k_or_guess is a scalar, now verify that it's an integer
+    k = int(guess)
+    if k != guess:
+        raise ValueError("If k_or_guess is a scalar, it must be an integer.")
+    if k < 1:
+        raise ValueError(f"Asked for {k} clusters.")
+
+    rng = check_random_state(rng)
+
+    # initialize best distance value to a large value
+    best_dist = xp.inf
+    for i in range(iter):
+        # the initial code book is randomly selected from observations
+        guess = _kpoints(obs, k, rng, xp)
+        book, dist = _kmeans(obs, guess, thresh=thresh, xp=xp)
+        if dist < best_dist:
+            best_book = book
+            best_dist = dist
+    return best_book, best_dist
+
+
+def _kpoints(data, k, rng, xp):
+    """Pick k points at random in data (one row = one observation).
+
+    Parameters
+    ----------
+    data : ndarray
+        Expect a rank 1 or 2 array. Rank 1 are assumed to describe one
+        dimensional data, rank 2 multidimensional data, in which case one
+        row is one observation.
+    k : int
+        Number of samples to generate.
+    rng : `numpy.random.Generator` or `numpy.random.RandomState`
+        Random number generator.
+
+    Returns
+    -------
+    x : ndarray
+        A 'k' by 'N' containing the initial centroids
+
+    """
+    idx = rng.choice(data.shape[0], size=int(k), replace=False)
+    # convert to array with default integer dtype (avoids numpy#25607)
+    idx = xp.asarray(idx, dtype=xp.asarray([1]).dtype)
+    return xp.take(data, idx, axis=0)
+
+
+def _krandinit(data, k, rng, xp):
+    """Returns k samples of a random variable whose parameters depend on data.
+
+    More precisely, it returns k observations sampled from a Gaussian random
+    variable whose mean and covariances are the ones estimated from the data.
+
+    Parameters
+    ----------
+    data : ndarray
+        Expect a rank 1 or 2 array. Rank 1 is assumed to describe 1-D
+        data, rank 2 multidimensional data, in which case one
+        row is one observation.
+    k : int
+        Number of samples to generate.
+    rng : `numpy.random.Generator` or `numpy.random.RandomState`
+        Random number generator.
+
+    Returns
+    -------
+    x : ndarray
+        A 'k' by 'N' containing the initial centroids
+
+    """
+    mu = xp.mean(data, axis=0)
+    k = np.asarray(k)
+
+    if data.ndim == 1:
+        _cov = xpx.cov(data, xp=xp)
+        x = rng.standard_normal(size=k)
+        x = xp.asarray(x)
+        x *= xp.sqrt(_cov)
+    elif data.shape[1] > data.shape[0]:
+        # initialize when the covariance matrix is rank deficient
+        _, s, vh = xp.linalg.svd(data - mu, full_matrices=False)
+        x = rng.standard_normal(size=(k, xp_size(s)))
+        x = xp.asarray(x)
+        sVh = s[:, None] * vh / xp.sqrt(data.shape[0] - xp.asarray(1.))
+        x = x @ sVh
+    else:
+        _cov = xpx.atleast_nd(xpx.cov(data.T, xp=xp), ndim=2, xp=xp)
+
+        # k rows, d cols (one row = one obs)
+        # Generate k sample of a random variable ~ Gaussian(mu, cov)
+        x = rng.standard_normal(size=(k, xp_size(mu)))
+        x = xp.asarray(x)
+        x = x @ xp.linalg.cholesky(_cov).T
+
+    x += mu
+    return x
+
+
+def _kpp(data, k, rng, xp):
+    """ Picks k points in the data based on the kmeans++ method.
+
+    Parameters
+    ----------
+    data : ndarray
+        Expect a rank 1 or 2 array. Rank 1 is assumed to describe 1-D
+        data, rank 2 multidimensional data, in which case one
+        row is one observation.
+    k : int
+        Number of samples to generate.
+    rng : `numpy.random.Generator` or `numpy.random.RandomState`
+        Random number generator.
+
+    Returns
+    -------
+    init : ndarray
+        A 'k' by 'N' containing the initial centroids.
+
+    References
+    ----------
+    .. [1] D. Arthur and S. Vassilvitskii, "k-means++: the advantages of
+       careful seeding", Proceedings of the Eighteenth Annual ACM-SIAM Symposium
+       on Discrete Algorithms, 2007.
+    """
+
+    ndim = len(data.shape)
+    if ndim == 1:
+        data = data[:, None]
+
+    dims = data.shape[1]
+
+    init = xp.empty((int(k), dims))
+
+    for i in range(k):
+        if i == 0:
+            data_idx = rng_integers(rng, data.shape[0])
+        else:
+            D2 = cdist(init[:i,:], data, metric='sqeuclidean').min(axis=0)
+            probs = D2/D2.sum()
+            cumprobs = probs.cumsum()
+            r = rng.uniform()
+            cumprobs = np.asarray(cumprobs)
+            data_idx = int(np.searchsorted(cumprobs, r))
+
+        init = xpx.at(init)[i, :].set(data[data_idx, :])
+
+    if ndim == 1:
+        init = init[:, 0]
+    return init
+
+
+_valid_init_meth = {'random': _krandinit, 'points': _kpoints, '++': _kpp}
+
+
+def _missing_warn():
+    """Print a warning when called."""
+    warnings.warn("One of the clusters is empty. "
+                  "Re-run kmeans with a different initialization.",
+                  stacklevel=3)
+
+
+def _missing_raise():
+    """Raise a ClusterError when called."""
+    raise ClusterError("One of the clusters is empty. "
+                       "Re-run kmeans with a different initialization.")
+
+
+_valid_miss_meth = {'warn': _missing_warn, 'raise': _missing_raise}
+
+
+@xp_capabilities(cpu_only=True, jax_jit=False, allow_dask_compute=True)
+@_transition_to_rng("seed")
+def kmeans2(data, k, iter=10, thresh=1e-5, minit='random',
+            missing='warn', check_finite=True, *, rng=None):
+    """
+    Classify a set of observations into k clusters using the k-means algorithm.
+
+    The algorithm attempts to minimize the Euclidean distance between
+    observations and centroids. Several initialization methods are
+    included.
+
+    Parameters
+    ----------
+    data : ndarray
+        A 'M' by 'N' array of 'M' observations in 'N' dimensions or a length
+        'M' array of 'M' 1-D observations.
+    k : int or ndarray
+        The number of clusters to form as well as the number of
+        centroids to generate. If `minit` initialization string is
+        'matrix', or if a ndarray is given instead, it is
+        interpreted as initial cluster to use instead.
+    iter : int, optional
+        Number of iterations of the k-means algorithm to run. Note
+        that this differs in meaning from the iters parameter to
+        the kmeans function.
+    thresh : float, optional
+        (not used yet)
+    minit : str, optional
+        Method for initialization. Available methods are 'random',
+        'points', '++' and 'matrix':
+
+        'random': generate k centroids from a Gaussian with mean and
+        variance estimated from the data.
+
+        'points': choose k observations (rows) at random from data for
+        the initial centroids.
+
+        '++': choose k observations accordingly to the kmeans++ method
+        (careful seeding)
+
+        'matrix': interpret the k parameter as a k by M (or length k
+        array for 1-D data) array of initial centroids.
+    missing : str, optional
+        Method to deal with empty clusters. Available methods are
+        'warn' and 'raise':
+
+        'warn': give a warning and continue.
+
+        'raise': raise an ClusterError and terminate the algorithm.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+    Returns
+    -------
+    centroid : ndarray
+        A 'k' by 'N' array of centroids found at the last iteration of
+        k-means.
+    label : ndarray
+        label[i] is the code or index of the centroid the
+        ith observation is closest to.
+
+    See Also
+    --------
+    kmeans
+
+    References
+    ----------
+    .. [1] D. Arthur and S. Vassilvitskii, "k-means++: the advantages of
+       careful seeding", Proceedings of the Eighteenth Annual ACM-SIAM Symposium
+       on Discrete Algorithms, 2007.
+
+    Examples
+    --------
+    >>> from scipy.cluster.vq import kmeans2
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy as np
+
+    Create z, an array with shape (100, 2) containing a mixture of samples
+    from three multivariate normal distributions.
+
+    >>> rng = np.random.default_rng()
+    >>> a = rng.multivariate_normal([0, 6], [[2, 1], [1, 1.5]], size=45)
+    >>> b = rng.multivariate_normal([2, 0], [[1, -1], [-1, 3]], size=30)
+    >>> c = rng.multivariate_normal([6, 4], [[5, 0], [0, 1.2]], size=25)
+    >>> z = np.concatenate((a, b, c))
+    >>> rng.shuffle(z)
+
+    Compute three clusters.
+
+    >>> centroid, label = kmeans2(z, 3, minit='points')
+    >>> centroid
+    array([[ 2.22274463, -0.61666946],  # may vary
+           [ 0.54069047,  5.86541444],
+           [ 6.73846769,  4.01991898]])
+
+    How many points are in each cluster?
+
+    >>> counts = np.bincount(label)
+    >>> counts
+    array([29, 51, 20])  # may vary
+
+    Plot the clusters.
+
+    >>> w0 = z[label == 0]
+    >>> w1 = z[label == 1]
+    >>> w2 = z[label == 2]
+    >>> plt.plot(w0[:, 0], w0[:, 1], 'o', alpha=0.5, label='cluster 0')
+    >>> plt.plot(w1[:, 0], w1[:, 1], 'd', alpha=0.5, label='cluster 1')
+    >>> plt.plot(w2[:, 0], w2[:, 1], 's', alpha=0.5, label='cluster 2')
+    >>> plt.plot(centroid[:, 0], centroid[:, 1], 'k*', label='centroids')
+    >>> plt.axis('equal')
+    >>> plt.legend(shadow=True)
+    >>> plt.show()
+
+    """
+    if int(iter) < 1:
+        raise ValueError(f"Invalid iter ({iter}), must be a positive integer.")
+    try:
+        miss_meth = _valid_miss_meth[missing]
+    except KeyError as e:
+        raise ValueError(f"Unknown missing method {missing!r}") from e
+
+    if isinstance(k, int):
+        xp = array_namespace(data)
+    else:
+        xp = array_namespace(data, k)
+    data = _asarray(data, xp=xp, check_finite=check_finite)
+    code_book = xp_copy(k, xp=xp)
+    if data.ndim == 1:
+        d = 1
+    elif data.ndim == 2:
+        d = data.shape[1]
+    else:
+        raise ValueError("Input of rank > 2 is not supported.")
+
+    if xp_size(data) < 1 or xp_size(code_book) < 1:
+        raise ValueError("Empty input is not supported.")
+
+    # If k is not a single value, it should be compatible with data's shape
+    if minit == 'matrix' or xp_size(code_book) > 1:
+        if data.ndim != code_book.ndim:
+            raise ValueError("k array doesn't match data rank")
+        nc = code_book.shape[0]
+        if data.ndim > 1 and code_book.shape[1] != d:
+            raise ValueError("k array doesn't match data dimension")
+    else:
+        nc = int(code_book)
+
+        if nc < 1:
+            raise ValueError(
+                f"Cannot ask kmeans2 for {nc} clusters (k was {code_book})"
+            )
+        elif nc != code_book:
+            warnings.warn("k was not an integer, was converted.", stacklevel=2)
+
+        try:
+            init_meth = _valid_init_meth[minit]
+        except KeyError as e:
+            raise ValueError(f"Unknown init method {minit!r}") from e
+        else:
+            rng = check_random_state(rng)
+            code_book = init_meth(data, code_book, rng, xp)
+
+    data = np.asarray(data)
+    code_book = np.asarray(code_book)
+    for _ in range(iter):
+        # Compute the nearest neighbor for each obs using the current code book
+        label = vq(data, code_book, check_finite=check_finite)[0]
+        # Update the code book by computing centroids
+        new_code_book, has_members = _vq.update_cluster_means(data, label, nc)
+        if not has_members.all():
+            miss_meth()
+            # Set the empty clusters to their previous positions
+            new_code_book[~has_members] = code_book[~has_members]
+        code_book = new_code_book
+
+    return xp.asarray(code_book), xp.asarray(label)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/constants/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/constants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdf939b249c17256b622c2f2756a5f34c4a128cc
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/constants/__init__.py
@@ -0,0 +1,358 @@
+r"""
+==================================
+Constants (:mod:`scipy.constants`)
+==================================
+
+.. currentmodule:: scipy.constants
+
+Physical and mathematical constants and units.
+
+
+Mathematical constants
+======================
+
+================  =================================================================
+``pi``            Pi
+``golden``        Golden ratio
+``golden_ratio``  Golden ratio
+================  =================================================================
+
+
+Physical constants
+==================
+The following physical constants are available as attributes of `scipy.constants`.
+All units are `SI `_.
+
+===========================  ================================================================  ===============
+Attribute                    Quantity                                                          Units
+===========================  ================================================================  ===============
+``c``                        speed of light in vacuum                                          m s^-1
+``speed_of_light``           speed of light in vacuum                                          m s^-1
+``mu_0``                     the magnetic constant :math:`\mu_0`                               N A^-2
+``epsilon_0``                the electric constant (vacuum permittivity), :math:`\epsilon_0`   F m^-1
+``h``                        the Planck constant :math:`h`                                     J Hz^-1
+``Planck``                   the Planck constant :math:`h`                                     J Hz^-1
+``hbar``                     the reduced Planck constant, :math:`\hbar = h/(2\pi)`             J s
+``G``                        Newtonian constant of gravitation                                 m^3 kg^-1 s^-2
+``gravitational_constant``   Newtonian constant of gravitation                                 m^3 kg^-1 s^-2
+``g``                        standard acceleration of gravity                                  m s^-2
+``e``                        elementary charge                                                 C
+``elementary_charge``        elementary charge                                                 C
+``R``                        molar gas constant                                                J mol^-1 K^-1
+``gas_constant``             molar gas constant                                                J mol^-1 K^-1
+``alpha``                    fine-structure constant                                           (unitless)
+``fine_structure``           fine-structure constant                                           (unitless)
+``N_A``                      Avogadro constant                                                 mol^-1
+``Avogadro``                 Avogadro constant                                                 mol^-1
+``k``                        Boltzmann constant                                                J K^-1
+``Boltzmann``                Boltzmann constant                                                J K^-1
+``sigma``                    Stefan-Boltzmann constant :math:`\sigma`                          W m^-2 K^-4
+``Stefan_Boltzmann``         Stefan-Boltzmann constant :math:`\sigma`                          W m^-2 K^-4
+``Wien``                     Wien wavelength displacement law constant                         m K
+``Rydberg``                  Rydberg constant                                                  m^-1
+``m_e``                      electron mass                                                     kg
+``electron_mass``            electron mass                                                     kg
+``m_p``                      proton mass                                                       kg
+``proton_mass``              proton mass                                                       kg
+``m_n``                      neutron mass                                                      kg
+``neutron_mass``             neutron mass                                                      kg
+===========================  ================================================================  ===============
+
+
+Constants database
+------------------
+
+In addition to the above variables, :mod:`scipy.constants` also contains the
+2022 CODATA recommended values [CODATA2022]_ database containing more physical
+constants.
+
+.. autosummary::
+   :toctree: generated/
+
+   value      -- Value in physical_constants indexed by key
+   unit       -- Unit in physical_constants indexed by key
+   precision  -- Relative precision in physical_constants indexed by key
+   find       -- Return list of physical_constant keys with a given string
+   ConstantWarning -- Constant sought not in newest CODATA data set
+
+.. data:: physical_constants
+
+   Dictionary of physical constants, of the format
+   ``physical_constants[name] = (value, unit, uncertainty)``.
+   The CODATA database uses ellipses to indicate that a value is defined
+   (exactly) in terms of others but cannot be represented exactly with the
+   allocated number of digits. In these cases, SciPy calculates the derived
+   value and reports it to the full precision of a Python ``float``. Although 
+   ``physical_constants`` lists the uncertainty as ``0.0`` to indicate that
+   the CODATA value is exact, the value in ``physical_constants`` is still
+   subject to the truncation error inherent in double-precision representation.
+
+Available constants:
+
+======================================================================  ====
+%(constant_names)s
+======================================================================  ====
+
+
+Units
+=====
+
+SI prefixes
+-----------
+
+============  =================================================================
+``quetta``    :math:`10^{30}`
+``ronna``     :math:`10^{27}`
+``yotta``     :math:`10^{24}`
+``zetta``     :math:`10^{21}`
+``exa``       :math:`10^{18}`
+``peta``      :math:`10^{15}`
+``tera``      :math:`10^{12}`
+``giga``      :math:`10^{9}`
+``mega``      :math:`10^{6}`
+``kilo``      :math:`10^{3}`
+``hecto``     :math:`10^{2}`
+``deka``      :math:`10^{1}`
+``deci``      :math:`10^{-1}`
+``centi``     :math:`10^{-2}`
+``milli``     :math:`10^{-3}`
+``micro``     :math:`10^{-6}`
+``nano``      :math:`10^{-9}`
+``pico``      :math:`10^{-12}`
+``femto``     :math:`10^{-15}`
+``atto``      :math:`10^{-18}`
+``zepto``     :math:`10^{-21}`
+``yocto``     :math:`10^{-24}`
+``ronto``     :math:`10^{-27}`
+``quecto``    :math:`10^{-30}`
+============  =================================================================
+
+Binary prefixes
+---------------
+
+============  =================================================================
+``kibi``      :math:`2^{10}`
+``mebi``      :math:`2^{20}`
+``gibi``      :math:`2^{30}`
+``tebi``      :math:`2^{40}`
+``pebi``      :math:`2^{50}`
+``exbi``      :math:`2^{60}`
+``zebi``      :math:`2^{70}`
+``yobi``      :math:`2^{80}`
+============  =================================================================
+
+Mass
+----
+
+=================  ============================================================
+``gram``           :math:`10^{-3}` kg
+``metric_ton``     :math:`10^{3}` kg
+``grain``          one grain in kg
+``lb``             one pound (avoirdupous) in kg
+``pound``          one pound (avoirdupous) in kg
+``blob``           one inch version of a slug in kg (added in 1.0.0)
+``slinch``         one inch version of a slug in kg (added in 1.0.0)
+``slug``           one slug in kg (added in 1.0.0)
+``oz``             one ounce in kg
+``ounce``          one ounce in kg
+``stone``          one stone in kg
+``grain``          one grain in kg
+``long_ton``       one long ton in kg
+``short_ton``      one short ton in kg
+``troy_ounce``     one Troy ounce in kg
+``troy_pound``     one Troy pound in kg
+``carat``          one carat in kg
+``m_u``            atomic mass constant (in kg)
+``u``              atomic mass constant (in kg)
+``atomic_mass``    atomic mass constant (in kg)
+=================  ============================================================
+
+Angle
+-----
+
+=================  ============================================================
+``degree``         degree in radians
+``arcmin``         arc minute in radians
+``arcminute``      arc minute in radians
+``arcsec``         arc second in radians
+``arcsecond``      arc second in radians
+=================  ============================================================
+
+
+Time
+----
+
+=================  ============================================================
+``minute``         one minute in seconds
+``hour``           one hour in seconds
+``day``            one day in seconds
+``week``           one week in seconds
+``year``           one year (365 days) in seconds
+``Julian_year``    one Julian year (365.25 days) in seconds
+=================  ============================================================
+
+
+Length
+------
+
+=====================  ============================================================
+``inch``               one inch in meters
+``foot``               one foot in meters
+``yard``               one yard in meters
+``mile``               one mile in meters
+``mil``                one mil in meters
+``pt``                 one point in meters
+``point``              one point in meters
+``survey_foot``        one survey foot in meters
+``survey_mile``        one survey mile in meters
+``nautical_mile``      one nautical mile in meters
+``fermi``              one Fermi in meters
+``angstrom``           one Angstrom in meters
+``micron``             one micron in meters
+``au``                 one astronomical unit in meters
+``astronomical_unit``  one astronomical unit in meters
+``light_year``         one light year in meters
+``parsec``             one parsec in meters
+=====================  ============================================================
+
+Pressure
+--------
+
+=================  ============================================================
+``atm``            standard atmosphere in pascals
+``atmosphere``     standard atmosphere in pascals
+``bar``            one bar in pascals
+``torr``           one torr (mmHg) in pascals
+``mmHg``           one torr (mmHg) in pascals
+``psi``            one psi in pascals
+=================  ============================================================
+
+Area
+----
+
+=================  ============================================================
+``hectare``        one hectare in square meters
+``acre``           one acre in square meters
+=================  ============================================================
+
+
+Volume
+------
+
+===================    ========================================================
+``liter``              one liter in cubic meters
+``litre``              one liter in cubic meters
+``gallon``             one gallon (US) in cubic meters
+``gallon_US``          one gallon (US) in cubic meters
+``gallon_imp``         one gallon (UK) in cubic meters
+``fluid_ounce``        one fluid ounce (US) in cubic meters
+``fluid_ounce_US``     one fluid ounce (US) in cubic meters
+``fluid_ounce_imp``    one fluid ounce (UK) in cubic meters
+``bbl``                one barrel in cubic meters
+``barrel``             one barrel in cubic meters
+===================    ========================================================
+
+Speed
+-----
+
+==================    ==========================================================
+``kmh``               kilometers per hour in meters per second
+``mph``               miles per hour in meters per second
+``mach``              one Mach (approx., at 15 C, 1 atm) in meters per second
+``speed_of_sound``    one Mach (approx., at 15 C, 1 atm) in meters per second
+``knot``              one knot in meters per second
+==================    ==========================================================
+
+
+Temperature
+-----------
+
+=====================  =======================================================
+``zero_Celsius``       zero of Celsius scale in Kelvin
+``degree_Fahrenheit``  one Fahrenheit (only differences) in Kelvins
+=====================  =======================================================
+
+.. autosummary::
+   :toctree: generated/
+
+   convert_temperature
+
+Energy
+------
+
+====================  =======================================================
+``eV``                one electron volt in Joules
+``electron_volt``     one electron volt in Joules
+``calorie``           one calorie (thermochemical) in Joules
+``calorie_th``        one calorie (thermochemical) in Joules
+``calorie_IT``        one calorie (International Steam Table calorie, 1956) in Joules
+``erg``               one erg in Joules
+``Btu``               one British thermal unit (International Steam Table) in Joules
+``Btu_IT``            one British thermal unit (International Steam Table) in Joules
+``Btu_th``            one British thermal unit (thermochemical) in Joules
+``ton_TNT``           one ton of TNT in Joules
+====================  =======================================================
+
+Power
+-----
+
+====================  =======================================================
+``hp``                one horsepower in watts
+``horsepower``        one horsepower in watts
+====================  =======================================================
+
+Force
+-----
+
+====================  =======================================================
+``dyn``               one dyne in newtons
+``dyne``              one dyne in newtons
+``lbf``               one pound force in newtons
+``pound_force``       one pound force in newtons
+``kgf``               one kilogram force in newtons
+``kilogram_force``    one kilogram force in newtons
+====================  =======================================================
+
+Optics
+------
+
+.. autosummary::
+   :toctree: generated/
+
+   lambda2nu
+   nu2lambda
+
+References
+==========
+
+.. [CODATA2022] CODATA Recommended Values of the Fundamental
+   Physical Constants 2022.
+
+   https://physics.nist.gov/cuu/Constants/
+
+"""  # noqa: E501
+# Modules contributed by BasSw (wegwerp@gmail.com)
+from ._codata import *
+from ._constants import *
+from ._codata import _obsolete_constants, physical_constants
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import codata, constants
+
+_constant_names_list = [(_k.lower(), _k, _v)
+                        for _k, _v in physical_constants.items()
+                        if _k not in _obsolete_constants]
+_constant_names = "\n".join(["``{}``{}  {} {}".format(_x[1], " "*(66-len(_x[1])),
+                                                  _x[2][0], _x[2][1])
+                             for _x in sorted(_constant_names_list)])
+if __doc__:
+    __doc__ = __doc__ % dict(constant_names=_constant_names)
+
+del _constant_names
+del _constant_names_list
+
+__all__ = [s for s in dir() if not s.startswith('_')]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/constants/_codata.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/constants/_codata.py
new file mode 100644
index 0000000000000000000000000000000000000000..4457a8089d9c4b7ba159519e6ec1606fb7b74070
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/constants/_codata.py
@@ -0,0 +1,2266 @@
+"""
+Fundamental Physical Constants
+------------------------------
+
+These constants are taken from CODATA Recommended Values of the Fundamental
+Physical Constants 2022.
+
+Object
+------
+physical_constants : dict
+    A dictionary containing physical constants. Keys are the names of physical
+    constants, values are tuples (value, units, precision).
+
+Functions
+---------
+value(key):
+    Returns the value of the physical constant(key).
+unit(key):
+    Returns the units of the physical constant(key).
+precision(key):
+    Returns the relative precision of the physical constant(key).
+find(sub):
+    Prints or returns list of keys containing the string sub, default is all.
+
+Source
+------
+The values of the constants provided at this site are recommended for
+international use by CODATA and are the latest available. Termed the "2018
+CODATA recommended values," they are generally recognized worldwide for use in
+all fields of science and technology. The values became available on 20 May
+2019 and replaced the 2014 CODATA set. Also available is an introduction to the
+constants for non-experts at
+
+https://physics.nist.gov/cuu/Constants/introduction.html
+
+References
+----------
+Theoretical and experimental publications relevant to the fundamental constants
+and closely related precision measurements published since the mid 1980s, but
+also including many older papers of particular interest, some of which date
+back to the 1800s. To search the bibliography, visit
+
+https://physics.nist.gov/cuu/Constants/
+
+"""
+
+# Compiled by Charles Harris, dated October 3, 2002
+# updated to 2002 values by BasSw, 2006
+# Updated to 2006 values by Vincent Davis June 2010
+# Updated to 2014 values by Joseph Booker, 2015
+# Updated to 2018 values by Jakob Jakobson, 2019
+# Updated to 2022 values by Jakob Jakobson, 2024
+
+import warnings
+import math
+
+from typing import Any
+from collections.abc import Callable
+
+__all__ = ['physical_constants', 'value', 'unit', 'precision', 'find',
+           'ConstantWarning']
+
+"""
+Source:  https://physics.nist.gov/cuu/Constants/
+
+The values of the constants provided at this site are recommended for
+international use by CODATA and are the latest available. Termed the "2018
+CODATA recommended values," they are generally recognized worldwide for use in
+all fields of science and technology. The values became available on 20 May
+2019 and replaced the 2014 CODATA set.
+"""
+
+#
+# Source:  https://physics.nist.gov/cuu/Constants/
+#
+
+# Quantity                                             Value                 Uncertainty          Unit
+# ---------------------------------------------------- --------------------- -------------------- -------------
+txt2002 = """\
+Wien displacement law constant                         2.897 7685e-3         0.000 0051e-3         m K
+atomic unit of 1st hyperpolarizablity                  3.206 361 51e-53      0.000 000 28e-53      C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizablity                  6.235 3808e-65        0.000 0011e-65        C^4 m^4 J^-3
+atomic unit of electric dipole moment                  8.478 353 09e-30      0.000 000 73e-30      C m
+atomic unit of electric polarizablity                  1.648 777 274e-41     0.000 000 016e-41     C^2 m^2 J^-1
+atomic unit of electric quadrupole moment              4.486 551 24e-40      0.000 000 39e-40      C m^2
+atomic unit of magn. dipole moment                     1.854 801 90e-23      0.000 000 16e-23      J T^-1
+atomic unit of magn. flux density                      2.350 517 42e5        0.000 000 20e5        T
+deuteron magn. moment                                  0.433 073 482e-26     0.000 000 038e-26     J T^-1
+deuteron magn. moment to Bohr magneton ratio           0.466 975 4567e-3     0.000 000 0050e-3
+deuteron magn. moment to nuclear magneton ratio        0.857 438 2329        0.000 000 0092
+deuteron-electron magn. moment ratio                   -4.664 345 548e-4     0.000 000 050e-4
+deuteron-proton magn. moment ratio                     0.307 012 2084        0.000 000 0045
+deuteron-neutron magn. moment ratio                    -0.448 206 52         0.000 000 11
+electron gyromagn. ratio                               1.760 859 74e11       0.000 000 15e11       s^-1 T^-1
+electron gyromagn. ratio over 2 pi                     28 024.9532           0.0024                MHz T^-1
+electron magn. moment                                  -928.476 412e-26      0.000 080e-26         J T^-1
+electron magn. moment to Bohr magneton ratio           -1.001 159 652 1859   0.000 000 000 0038
+electron magn. moment to nuclear magneton ratio        -1838.281 971 07      0.000 000 85
+electron magn. moment anomaly                          1.159 652 1859e-3     0.000 000 0038e-3
+electron to shielded proton magn. moment ratio         -658.227 5956         0.000 0071
+electron to shielded helion magn. moment ratio         864.058 255           0.000 010
+electron-deuteron magn. moment ratio                   -2143.923 493         0.000 023
+electron-muon magn. moment ratio                       206.766 9894          0.000 0054
+electron-neutron magn. moment ratio                    960.920 50            0.000 23
+electron-proton magn. moment ratio                     -658.210 6862         0.000 0066
+magn. constant                                         12.566 370 614...e-7  (exact)               N A^-2
+magn. flux quantum                                     2.067 833 72e-15      0.000 000 18e-15      Wb
+muon magn. moment                                      -4.490 447 99e-26     0.000 000 40e-26      J T^-1
+muon magn. moment to Bohr magneton ratio               -4.841 970 45e-3      0.000 000 13e-3
+muon magn. moment to nuclear magneton ratio            -8.890 596 98         0.000 000 23
+muon-proton magn. moment ratio                         -3.183 345 118        0.000 000 089
+neutron gyromagn. ratio                                1.832 471 83e8        0.000 000 46e8        s^-1 T^-1
+neutron gyromagn. ratio over 2 pi                      29.164 6950           0.000 0073            MHz T^-1
+neutron magn. moment                                   -0.966 236 45e-26     0.000 000 24e-26      J T^-1
+neutron magn. moment to Bohr magneton ratio            -1.041 875 63e-3      0.000 000 25e-3
+neutron magn. moment to nuclear magneton ratio         -1.913 042 73         0.000 000 45
+neutron to shielded proton magn. moment ratio          -0.684 996 94         0.000 000 16
+neutron-electron magn. moment ratio                    1.040 668 82e-3       0.000 000 25e-3
+neutron-proton magn. moment ratio                      -0.684 979 34         0.000 000 16
+proton gyromagn. ratio                                 2.675 222 05e8        0.000 000 23e8        s^-1 T^-1
+proton gyromagn. ratio over 2 pi                       42.577 4813           0.000 0037            MHz T^-1
+proton magn. moment                                    1.410 606 71e-26      0.000 000 12e-26      J T^-1
+proton magn. moment to Bohr magneton ratio             1.521 032 206e-3      0.000 000 015e-3
+proton magn. moment to nuclear magneton ratio          2.792 847 351         0.000 000 028
+proton magn. shielding correction                      25.689e-6             0.015e-6
+proton-neutron magn. moment ratio                      -1.459 898 05         0.000 000 34
+shielded helion gyromagn. ratio                        2.037 894 70e8        0.000 000 18e8        s^-1 T^-1
+shielded helion gyromagn. ratio over 2 pi              32.434 1015           0.000 0028            MHz T^-1
+shielded helion magn. moment                           -1.074 553 024e-26    0.000 000 093e-26     J T^-1
+shielded helion magn. moment to Bohr magneton ratio    -1.158 671 474e-3     0.000 000 014e-3
+shielded helion magn. moment to nuclear magneton ratio -2.127 497 723        0.000 000 025
+shielded helion to proton magn. moment ratio           -0.761 766 562        0.000 000 012
+shielded helion to shielded proton magn. moment ratio  -0.761 786 1313       0.000 000 0033
+shielded helion gyromagn. ratio                        2.037 894 70e8        0.000 000 18e8        s^-1 T^-1
+shielded helion gyromagn. ratio over 2 pi              32.434 1015           0.000 0028            MHz T^-1
+shielded proton magn. moment                           1.410 570 47e-26      0.000 000 12e-26      J T^-1
+shielded proton magn. moment to Bohr magneton ratio    1.520 993 132e-3      0.000 000 016e-3
+shielded proton magn. moment to nuclear magneton ratio 2.792 775 604         0.000 000 030
+{220} lattice spacing of silicon                       192.015 5965e-12      0.000 0070e-12        m"""
+
+
+def exact2002(exact):
+    replace = {
+        'magn. constant': 4e-7 * math.pi,
+    }
+    return replace
+
+
+txt2006 = """\
+lattice spacing of silicon                             192.015 5762 e-12     0.000 0050 e-12       m
+alpha particle-electron mass ratio                     7294.299 5365         0.000 0031
+alpha particle mass                                    6.644 656 20 e-27     0.000 000 33 e-27     kg
+alpha particle mass energy equivalent                  5.971 919 17 e-10     0.000 000 30 e-10     J
+alpha particle mass energy equivalent in MeV           3727.379 109          0.000 093             MeV
+alpha particle mass in u                               4.001 506 179 127     0.000 000 000 062     u
+alpha particle molar mass                              4.001 506 179 127 e-3 0.000 000 000 062 e-3 kg mol^-1
+alpha particle-proton mass ratio                       3.972 599 689 51      0.000 000 000 41
+Angstrom star                                          1.000 014 98 e-10     0.000 000 90 e-10     m
+atomic mass constant                                   1.660 538 782 e-27    0.000 000 083 e-27    kg
+atomic mass constant energy equivalent                 1.492 417 830 e-10    0.000 000 074 e-10    J
+atomic mass constant energy equivalent in MeV          931.494 028           0.000 023             MeV
+atomic mass unit-electron volt relationship            931.494 028 e6        0.000 023 e6          eV
+atomic mass unit-hartree relationship                  3.423 177 7149 e7     0.000 000 0049 e7     E_h
+atomic mass unit-hertz relationship                    2.252 342 7369 e23    0.000 000 0032 e23    Hz
+atomic mass unit-inverse meter relationship            7.513 006 671 e14     0.000 000 011 e14     m^-1
+atomic mass unit-joule relationship                    1.492 417 830 e-10    0.000 000 074 e-10    J
+atomic mass unit-kelvin relationship                   1.080 9527 e13        0.000 0019 e13        K
+atomic mass unit-kilogram relationship                 1.660 538 782 e-27    0.000 000 083 e-27    kg
+atomic unit of 1st hyperpolarizability                 3.206 361 533 e-53    0.000 000 081 e-53    C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                 6.235 380 95 e-65     0.000 000 31 e-65     C^4 m^4 J^-3
+atomic unit of action                                  1.054 571 628 e-34    0.000 000 053 e-34    J s
+atomic unit of charge                                  1.602 176 487 e-19    0.000 000 040 e-19    C
+atomic unit of charge density                          1.081 202 300 e12     0.000 000 027 e12     C m^-3
+atomic unit of current                                 6.623 617 63 e-3      0.000 000 17 e-3      A
+atomic unit of electric dipole mom.                    8.478 352 81 e-30     0.000 000 21 e-30     C m
+atomic unit of electric field                          5.142 206 32 e11      0.000 000 13 e11      V m^-1
+atomic unit of electric field gradient                 9.717 361 66 e21      0.000 000 24 e21      V m^-2
+atomic unit of electric polarizability                 1.648 777 2536 e-41   0.000 000 0034 e-41   C^2 m^2 J^-1
+atomic unit of electric potential                      27.211 383 86         0.000 000 68          V
+atomic unit of electric quadrupole mom.                4.486 551 07 e-40     0.000 000 11 e-40     C m^2
+atomic unit of energy                                  4.359 743 94 e-18     0.000 000 22 e-18     J
+atomic unit of force                                   8.238 722 06 e-8      0.000 000 41 e-8      N
+atomic unit of length                                  0.529 177 208 59 e-10 0.000 000 000 36 e-10 m
+atomic unit of mag. dipole mom.                        1.854 801 830 e-23    0.000 000 046 e-23    J T^-1
+atomic unit of mag. flux density                       2.350 517 382 e5      0.000 000 059 e5      T
+atomic unit of magnetizability                         7.891 036 433 e-29    0.000 000 027 e-29    J T^-2
+atomic unit of mass                                    9.109 382 15 e-31     0.000 000 45 e-31     kg
+atomic unit of momentum                                1.992 851 565 e-24    0.000 000 099 e-24    kg m s^-1
+atomic unit of permittivity                            1.112 650 056... e-10 (exact)               F m^-1
+atomic unit of time                                    2.418 884 326 505 e-17 0.000 000 000 016 e-17 s
+atomic unit of velocity                                2.187 691 2541 e6     0.000 000 0015 e6     m s^-1
+Avogadro constant                                      6.022 141 79 e23      0.000 000 30 e23      mol^-1
+Bohr magneton                                          927.400 915 e-26      0.000 023 e-26        J T^-1
+Bohr magneton in eV/T                                  5.788 381 7555 e-5    0.000 000 0079 e-5    eV T^-1
+Bohr magneton in Hz/T                                  13.996 246 04 e9      0.000 000 35 e9       Hz T^-1
+Bohr magneton in inverse meters per tesla              46.686 4515           0.000 0012            m^-1 T^-1
+Bohr magneton in K/T                                   0.671 7131            0.000 0012            K T^-1
+Bohr radius                                            0.529 177 208 59 e-10 0.000 000 000 36 e-10 m
+Boltzmann constant                                     1.380 6504 e-23       0.000 0024 e-23       J K^-1
+Boltzmann constant in eV/K                             8.617 343 e-5         0.000 015 e-5         eV K^-1
+Boltzmann constant in Hz/K                             2.083 6644 e10        0.000 0036 e10        Hz K^-1
+Boltzmann constant in inverse meters per kelvin        69.503 56             0.000 12              m^-1 K^-1
+characteristic impedance of vacuum                     376.730 313 461...    (exact)               ohm
+classical electron radius                              2.817 940 2894 e-15   0.000 000 0058 e-15   m
+Compton wavelength                                     2.426 310 2175 e-12   0.000 000 0033 e-12   m
+Compton wavelength over 2 pi                           386.159 264 59 e-15   0.000 000 53 e-15     m
+conductance quantum                                    7.748 091 7004 e-5    0.000 000 0053 e-5    S
+conventional value of Josephson constant               483 597.9 e9          (exact)               Hz V^-1
+conventional value of von Klitzing constant            25 812.807            (exact)               ohm
+Cu x unit                                              1.002 076 99 e-13     0.000 000 28 e-13     m
+deuteron-electron mag. mom. ratio                      -4.664 345 537 e-4    0.000 000 039 e-4
+deuteron-electron mass ratio                           3670.482 9654         0.000 0016
+deuteron g factor                                      0.857 438 2308        0.000 000 0072
+deuteron mag. mom.                                     0.433 073 465 e-26    0.000 000 011 e-26    J T^-1
+deuteron mag. mom. to Bohr magneton ratio              0.466 975 4556 e-3    0.000 000 0039 e-3
+deuteron mag. mom. to nuclear magneton ratio           0.857 438 2308        0.000 000 0072
+deuteron mass                                          3.343 583 20 e-27     0.000 000 17 e-27     kg
+deuteron mass energy equivalent                        3.005 062 72 e-10     0.000 000 15 e-10     J
+deuteron mass energy equivalent in MeV                 1875.612 793          0.000 047             MeV
+deuteron mass in u                                     2.013 553 212 724     0.000 000 000 078     u
+deuteron molar mass                                    2.013 553 212 724 e-3 0.000 000 000 078 e-3 kg mol^-1
+deuteron-neutron mag. mom. ratio                       -0.448 206 52         0.000 000 11
+deuteron-proton mag. mom. ratio                        0.307 012 2070        0.000 000 0024
+deuteron-proton mass ratio                             1.999 007 501 08      0.000 000 000 22
+deuteron rms charge radius                             2.1402 e-15           0.0028 e-15           m
+electric constant                                      8.854 187 817... e-12 (exact)               F m^-1
+electron charge to mass quotient                       -1.758 820 150 e11    0.000 000 044 e11     C kg^-1
+electron-deuteron mag. mom. ratio                      -2143.923 498         0.000 018
+electron-deuteron mass ratio                           2.724 437 1093 e-4    0.000 000 0012 e-4
+electron g factor                                      -2.002 319 304 3622   0.000 000 000 0015
+electron gyromag. ratio                                1.760 859 770 e11     0.000 000 044 e11     s^-1 T^-1
+electron gyromag. ratio over 2 pi                      28 024.953 64         0.000 70              MHz T^-1
+electron mag. mom.                                     -928.476 377 e-26     0.000 023 e-26        J T^-1
+electron mag. mom. anomaly                             1.159 652 181 11 e-3  0.000 000 000 74 e-3
+electron mag. mom. to Bohr magneton ratio              -1.001 159 652 181 11 0.000 000 000 000 74
+electron mag. mom. to nuclear magneton ratio           -1838.281 970 92      0.000 000 80
+electron mass                                          9.109 382 15 e-31     0.000 000 45 e-31     kg
+electron mass energy equivalent                        8.187 104 38 e-14     0.000 000 41 e-14     J
+electron mass energy equivalent in MeV                 0.510 998 910         0.000 000 013         MeV
+electron mass in u                                     5.485 799 0943 e-4    0.000 000 0023 e-4    u
+electron molar mass                                    5.485 799 0943 e-7    0.000 000 0023 e-7    kg mol^-1
+electron-muon mag. mom. ratio                          206.766 9877          0.000 0052
+electron-muon mass ratio                               4.836 331 71 e-3      0.000 000 12 e-3
+electron-neutron mag. mom. ratio                       960.920 50            0.000 23
+electron-neutron mass ratio                            5.438 673 4459 e-4    0.000 000 0033 e-4
+electron-proton mag. mom. ratio                        -658.210 6848         0.000 0054
+electron-proton mass ratio                             5.446 170 2177 e-4    0.000 000 0024 e-4
+electron-tau mass ratio                                2.875 64 e-4          0.000 47 e-4
+electron to alpha particle mass ratio                  1.370 933 555 70 e-4  0.000 000 000 58 e-4
+electron to shielded helion mag. mom. ratio            864.058 257           0.000 010
+electron to shielded proton mag. mom. ratio            -658.227 5971         0.000 0072
+electron volt                                          1.602 176 487 e-19    0.000 000 040 e-19    J
+electron volt-atomic mass unit relationship            1.073 544 188 e-9     0.000 000 027 e-9     u
+electron volt-hartree relationship                     3.674 932 540 e-2     0.000 000 092 e-2     E_h
+electron volt-hertz relationship                       2.417 989 454 e14     0.000 000 060 e14     Hz
+electron volt-inverse meter relationship               8.065 544 65 e5       0.000 000 20 e5       m^-1
+electron volt-joule relationship                       1.602 176 487 e-19    0.000 000 040 e-19    J
+electron volt-kelvin relationship                      1.160 4505 e4         0.000 0020 e4         K
+electron volt-kilogram relationship                    1.782 661 758 e-36    0.000 000 044 e-36    kg
+elementary charge                                      1.602 176 487 e-19    0.000 000 040 e-19    C
+elementary charge over h                               2.417 989 454 e14     0.000 000 060 e14     A J^-1
+Faraday constant                                       96 485.3399           0.0024                C mol^-1
+Faraday constant for conventional electric current     96 485.3401           0.0048                C_90 mol^-1
+Fermi coupling constant                                1.166 37 e-5          0.000 01 e-5          GeV^-2
+fine-structure constant                                7.297 352 5376 e-3    0.000 000 0050 e-3
+first radiation constant                               3.741 771 18 e-16     0.000 000 19 e-16     W m^2
+first radiation constant for spectral radiance         1.191 042 759 e-16    0.000 000 059 e-16    W m^2 sr^-1
+hartree-atomic mass unit relationship                  2.921 262 2986 e-8    0.000 000 0042 e-8    u
+hartree-electron volt relationship                     27.211 383 86         0.000 000 68          eV
+Hartree energy                                         4.359 743 94 e-18     0.000 000 22 e-18     J
+Hartree energy in eV                                   27.211 383 86         0.000 000 68          eV
+hartree-hertz relationship                             6.579 683 920 722 e15 0.000 000 000 044 e15 Hz
+hartree-inverse meter relationship                     2.194 746 313 705 e7  0.000 000 000 015 e7  m^-1
+hartree-joule relationship                             4.359 743 94 e-18     0.000 000 22 e-18     J
+hartree-kelvin relationship                            3.157 7465 e5         0.000 0055 e5         K
+hartree-kilogram relationship                          4.850 869 34 e-35     0.000 000 24 e-35     kg
+helion-electron mass ratio                             5495.885 2765         0.000 0052
+helion mass                                            5.006 411 92 e-27     0.000 000 25 e-27     kg
+helion mass energy equivalent                          4.499 538 64 e-10     0.000 000 22 e-10     J
+helion mass energy equivalent in MeV                   2808.391 383          0.000 070             MeV
+helion mass in u                                       3.014 932 2473        0.000 000 0026        u
+helion molar mass                                      3.014 932 2473 e-3    0.000 000 0026 e-3    kg mol^-1
+helion-proton mass ratio                               2.993 152 6713        0.000 000 0026
+hertz-atomic mass unit relationship                    4.439 821 6294 e-24   0.000 000 0064 e-24   u
+hertz-electron volt relationship                       4.135 667 33 e-15     0.000 000 10 e-15     eV
+hertz-hartree relationship                             1.519 829 846 006 e-16 0.000 000 000010e-16 E_h
+hertz-inverse meter relationship                       3.335 640 951... e-9  (exact)               m^-1
+hertz-joule relationship                               6.626 068 96 e-34     0.000 000 33 e-34     J
+hertz-kelvin relationship                              4.799 2374 e-11       0.000 0084 e-11       K
+hertz-kilogram relationship                            7.372 496 00 e-51     0.000 000 37 e-51     kg
+inverse fine-structure constant                        137.035 999 679       0.000 000 094
+inverse meter-atomic mass unit relationship            1.331 025 0394 e-15   0.000 000 0019 e-15   u
+inverse meter-electron volt relationship               1.239 841 875 e-6     0.000 000 031 e-6     eV
+inverse meter-hartree relationship                     4.556 335 252 760 e-8 0.000 000 000 030 e-8 E_h
+inverse meter-hertz relationship                       299 792 458           (exact)               Hz
+inverse meter-joule relationship                       1.986 445 501 e-25    0.000 000 099 e-25    J
+inverse meter-kelvin relationship                      1.438 7752 e-2        0.000 0025 e-2        K
+inverse meter-kilogram relationship                    2.210 218 70 e-42     0.000 000 11 e-42     kg
+inverse of conductance quantum                         12 906.403 7787       0.000 0088            ohm
+Josephson constant                                     483 597.891 e9        0.012 e9              Hz V^-1
+joule-atomic mass unit relationship                    6.700 536 41 e9       0.000 000 33 e9       u
+joule-electron volt relationship                       6.241 509 65 e18      0.000 000 16 e18      eV
+joule-hartree relationship                             2.293 712 69 e17      0.000 000 11 e17      E_h
+joule-hertz relationship                               1.509 190 450 e33     0.000 000 075 e33     Hz
+joule-inverse meter relationship                       5.034 117 47 e24      0.000 000 25 e24      m^-1
+joule-kelvin relationship                              7.242 963 e22         0.000 013 e22         K
+joule-kilogram relationship                            1.112 650 056... e-17 (exact)               kg
+kelvin-atomic mass unit relationship                   9.251 098 e-14        0.000 016 e-14        u
+kelvin-electron volt relationship                      8.617 343 e-5         0.000 015 e-5         eV
+kelvin-hartree relationship                            3.166 8153 e-6        0.000 0055 e-6        E_h
+kelvin-hertz relationship                              2.083 6644 e10        0.000 0036 e10        Hz
+kelvin-inverse meter relationship                      69.503 56             0.000 12              m^-1
+kelvin-joule relationship                              1.380 6504 e-23       0.000 0024 e-23       J
+kelvin-kilogram relationship                           1.536 1807 e-40       0.000 0027 e-40       kg
+kilogram-atomic mass unit relationship                 6.022 141 79 e26      0.000 000 30 e26      u
+kilogram-electron volt relationship                    5.609 589 12 e35      0.000 000 14 e35      eV
+kilogram-hartree relationship                          2.061 486 16 e34      0.000 000 10 e34      E_h
+kilogram-hertz relationship                            1.356 392 733 e50     0.000 000 068 e50     Hz
+kilogram-inverse meter relationship                    4.524 439 15 e41      0.000 000 23 e41      m^-1
+kilogram-joule relationship                            8.987 551 787... e16  (exact)               J
+kilogram-kelvin relationship                           6.509 651 e39         0.000 011 e39         K
+lattice parameter of silicon                           543.102 064 e-12      0.000 014 e-12        m
+Loschmidt constant (273.15 K, 101.325 kPa)             2.686 7774 e25        0.000 0047 e25        m^-3
+mag. constant                                          12.566 370 614... e-7 (exact)               N A^-2
+mag. flux quantum                                      2.067 833 667 e-15    0.000 000 052 e-15    Wb
+molar gas constant                                     8.314 472             0.000 015             J mol^-1 K^-1
+molar mass constant                                    1 e-3                 (exact)               kg mol^-1
+molar mass of carbon-12                                12 e-3                (exact)               kg mol^-1
+molar Planck constant                                  3.990 312 6821 e-10   0.000 000 0057 e-10   J s mol^-1
+molar Planck constant times c                          0.119 626 564 72      0.000 000 000 17      J m mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)          22.710 981 e-3        0.000 040 e-3         m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)      22.413 996 e-3        0.000 039 e-3         m^3 mol^-1
+molar volume of silicon                                12.058 8349 e-6       0.000 0011 e-6        m^3 mol^-1
+Mo x unit                                              1.002 099 55 e-13     0.000 000 53 e-13     m
+muon Compton wavelength                                11.734 441 04 e-15    0.000 000 30 e-15     m
+muon Compton wavelength over 2 pi                      1.867 594 295 e-15    0.000 000 047 e-15    m
+muon-electron mass ratio                               206.768 2823          0.000 0052
+muon g factor                                          -2.002 331 8414       0.000 000 0012
+muon mag. mom.                                         -4.490 447 86 e-26    0.000 000 16 e-26     J T^-1
+muon mag. mom. anomaly                                 1.165 920 69 e-3      0.000 000 60 e-3
+muon mag. mom. to Bohr magneton ratio                  -4.841 970 49 e-3     0.000 000 12 e-3
+muon mag. mom. to nuclear magneton ratio               -8.890 597 05         0.000 000 23
+muon mass                                              1.883 531 30 e-28     0.000 000 11 e-28     kg
+muon mass energy equivalent                            1.692 833 510 e-11    0.000 000 095 e-11    J
+muon mass energy equivalent in MeV                     105.658 3668          0.000 0038            MeV
+muon mass in u                                         0.113 428 9256        0.000 000 0029        u
+muon molar mass                                        0.113 428 9256 e-3    0.000 000 0029 e-3    kg mol^-1
+muon-neutron mass ratio                                0.112 454 5167        0.000 000 0029
+muon-proton mag. mom. ratio                            -3.183 345 137        0.000 000 085
+muon-proton mass ratio                                 0.112 609 5261        0.000 000 0029
+muon-tau mass ratio                                    5.945 92 e-2          0.000 97 e-2
+natural unit of action                                 1.054 571 628 e-34    0.000 000 053 e-34    J s
+natural unit of action in eV s                         6.582 118 99 e-16     0.000 000 16 e-16     eV s
+natural unit of energy                                 8.187 104 38 e-14     0.000 000 41 e-14     J
+natural unit of energy in MeV                          0.510 998 910         0.000 000 013         MeV
+natural unit of length                                 386.159 264 59 e-15   0.000 000 53 e-15     m
+natural unit of mass                                   9.109 382 15 e-31     0.000 000 45 e-31     kg
+natural unit of momentum                               2.730 924 06 e-22     0.000 000 14 e-22     kg m s^-1
+natural unit of momentum in MeV/c                      0.510 998 910         0.000 000 013         MeV/c
+natural unit of time                                   1.288 088 6570 e-21   0.000 000 0018 e-21   s
+natural unit of velocity                               299 792 458           (exact)               m s^-1
+neutron Compton wavelength                             1.319 590 8951 e-15   0.000 000 0020 e-15   m
+neutron Compton wavelength over 2 pi                   0.210 019 413 82 e-15 0.000 000 000 31 e-15 m
+neutron-electron mag. mom. ratio                       1.040 668 82 e-3      0.000 000 25 e-3
+neutron-electron mass ratio                            1838.683 6605         0.000 0011
+neutron g factor                                       -3.826 085 45         0.000 000 90
+neutron gyromag. ratio                                 1.832 471 85 e8       0.000 000 43 e8       s^-1 T^-1
+neutron gyromag. ratio over 2 pi                       29.164 6954           0.000 0069            MHz T^-1
+neutron mag. mom.                                      -0.966 236 41 e-26    0.000 000 23 e-26     J T^-1
+neutron mag. mom. to Bohr magneton ratio               -1.041 875 63 e-3     0.000 000 25 e-3
+neutron mag. mom. to nuclear magneton ratio            -1.913 042 73         0.000 000 45
+neutron mass                                           1.674 927 211 e-27    0.000 000 084 e-27    kg
+neutron mass energy equivalent                         1.505 349 505 e-10    0.000 000 075 e-10    J
+neutron mass energy equivalent in MeV                  939.565 346           0.000 023             MeV
+neutron mass in u                                      1.008 664 915 97      0.000 000 000 43      u
+neutron molar mass                                     1.008 664 915 97 e-3  0.000 000 000 43 e-3  kg mol^-1
+neutron-muon mass ratio                                8.892 484 09          0.000 000 23
+neutron-proton mag. mom. ratio                         -0.684 979 34         0.000 000 16
+neutron-proton mass ratio                              1.001 378 419 18      0.000 000 000 46
+neutron-tau mass ratio                                 0.528 740             0.000 086
+neutron to shielded proton mag. mom. ratio             -0.684 996 94         0.000 000 16
+Newtonian constant of gravitation                      6.674 28 e-11         0.000 67 e-11         m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c         6.708 81 e-39         0.000 67 e-39         (GeV/c^2)^-2
+nuclear magneton                                       5.050 783 24 e-27     0.000 000 13 e-27     J T^-1
+nuclear magneton in eV/T                               3.152 451 2326 e-8    0.000 000 0045 e-8    eV T^-1
+nuclear magneton in inverse meters per tesla           2.542 623 616 e-2     0.000 000 064 e-2     m^-1 T^-1
+nuclear magneton in K/T                                3.658 2637 e-4        0.000 0064 e-4        K T^-1
+nuclear magneton in MHz/T                              7.622 593 84          0.000 000 19          MHz T^-1
+Planck constant                                        6.626 068 96 e-34     0.000 000 33 e-34     J s
+Planck constant in eV s                                4.135 667 33 e-15     0.000 000 10 e-15     eV s
+Planck constant over 2 pi                              1.054 571 628 e-34    0.000 000 053 e-34    J s
+Planck constant over 2 pi in eV s                      6.582 118 99 e-16     0.000 000 16 e-16     eV s
+Planck constant over 2 pi times c in MeV fm            197.326 9631          0.000 0049            MeV fm
+Planck length                                          1.616 252 e-35        0.000 081 e-35        m
+Planck mass                                            2.176 44 e-8          0.000 11 e-8          kg
+Planck mass energy equivalent in GeV                   1.220 892 e19         0.000 061 e19         GeV
+Planck temperature                                     1.416 785 e32         0.000 071 e32         K
+Planck time                                            5.391 24 e-44         0.000 27 e-44         s
+proton charge to mass quotient                         9.578 833 92 e7       0.000 000 24 e7       C kg^-1
+proton Compton wavelength                              1.321 409 8446 e-15   0.000 000 0019 e-15   m
+proton Compton wavelength over 2 pi                    0.210 308 908 61 e-15 0.000 000 000 30 e-15 m
+proton-electron mass ratio                             1836.152 672 47       0.000 000 80
+proton g factor                                        5.585 694 713         0.000 000 046
+proton gyromag. ratio                                  2.675 222 099 e8      0.000 000 070 e8      s^-1 T^-1
+proton gyromag. ratio over 2 pi                        42.577 4821           0.000 0011            MHz T^-1
+proton mag. mom.                                       1.410 606 662 e-26    0.000 000 037 e-26    J T^-1
+proton mag. mom. to Bohr magneton ratio                1.521 032 209 e-3     0.000 000 012 e-3
+proton mag. mom. to nuclear magneton ratio             2.792 847 356         0.000 000 023
+proton mag. shielding correction                       25.694 e-6            0.014 e-6
+proton mass                                            1.672 621 637 e-27    0.000 000 083 e-27    kg
+proton mass energy equivalent                          1.503 277 359 e-10    0.000 000 075 e-10    J
+proton mass energy equivalent in MeV                   938.272 013           0.000 023             MeV
+proton mass in u                                       1.007 276 466 77      0.000 000 000 10      u
+proton molar mass                                      1.007 276 466 77 e-3  0.000 000 000 10 e-3  kg mol^-1
+proton-muon mass ratio                                 8.880 243 39          0.000 000 23
+proton-neutron mag. mom. ratio                         -1.459 898 06         0.000 000 34
+proton-neutron mass ratio                              0.998 623 478 24      0.000 000 000 46
+proton rms charge radius                               0.8768 e-15           0.0069 e-15           m
+proton-tau mass ratio                                  0.528 012             0.000 086
+quantum of circulation                                 3.636 947 5199 e-4    0.000 000 0050 e-4    m^2 s^-1
+quantum of circulation times 2                         7.273 895 040 e-4     0.000 000 010 e-4     m^2 s^-1
+Rydberg constant                                       10 973 731.568 527    0.000 073             m^-1
+Rydberg constant times c in Hz                         3.289 841 960 361 e15 0.000 000 000 022 e15 Hz
+Rydberg constant times hc in eV                        13.605 691 93         0.000 000 34          eV
+Rydberg constant times hc in J                         2.179 871 97 e-18     0.000 000 11 e-18     J
+Sackur-Tetrode constant (1 K, 100 kPa)                 -1.151 7047           0.000 0044
+Sackur-Tetrode constant (1 K, 101.325 kPa)             -1.164 8677           0.000 0044
+second radiation constant                              1.438 7752 e-2        0.000 0025 e-2        m K
+shielded helion gyromag. ratio                         2.037 894 730 e8      0.000 000 056 e8      s^-1 T^-1
+shielded helion gyromag. ratio over 2 pi               32.434 101 98         0.000 000 90          MHz T^-1
+shielded helion mag. mom.                              -1.074 552 982 e-26   0.000 000 030 e-26    J T^-1
+shielded helion mag. mom. to Bohr magneton ratio       -1.158 671 471 e-3    0.000 000 014 e-3
+shielded helion mag. mom. to nuclear magneton ratio    -2.127 497 718        0.000 000 025
+shielded helion to proton mag. mom. ratio              -0.761 766 558        0.000 000 011
+shielded helion to shielded proton mag. mom. ratio     -0.761 786 1313       0.000 000 0033
+shielded proton gyromag. ratio                         2.675 153 362 e8      0.000 000 073 e8      s^-1 T^-1
+shielded proton gyromag. ratio over 2 pi               42.576 3881           0.000 0012            MHz T^-1
+shielded proton mag. mom.                              1.410 570 419 e-26    0.000 000 038 e-26    J T^-1
+shielded proton mag. mom. to Bohr magneton ratio       1.520 993 128 e-3     0.000 000 017 e-3
+shielded proton mag. mom. to nuclear magneton ratio    2.792 775 598         0.000 000 030
+speed of light in vacuum                               299 792 458           (exact)               m s^-1
+standard acceleration of gravity                       9.806 65              (exact)               m s^-2
+standard atmosphere                                    101 325               (exact)               Pa
+Stefan-Boltzmann constant                              5.670 400 e-8         0.000 040 e-8         W m^-2 K^-4
+tau Compton wavelength                                 0.697 72 e-15         0.000 11 e-15         m
+tau Compton wavelength over 2 pi                       0.111 046 e-15        0.000 018 e-15        m
+tau-electron mass ratio                                3477.48               0.57
+tau mass                                               3.167 77 e-27         0.000 52 e-27         kg
+tau mass energy equivalent                             2.847 05 e-10         0.000 46 e-10         J
+tau mass energy equivalent in MeV                      1776.99               0.29                  MeV
+tau mass in u                                          1.907 68              0.000 31              u
+tau molar mass                                         1.907 68 e-3          0.000 31 e-3          kg mol^-1
+tau-muon mass ratio                                    16.8183               0.0027
+tau-neutron mass ratio                                 1.891 29              0.000 31
+tau-proton mass ratio                                  1.893 90              0.000 31
+Thomson cross section                                  0.665 245 8558 e-28   0.000 000 0027 e-28   m^2
+triton-electron mag. mom. ratio                        -1.620 514 423 e-3    0.000 000 021 e-3
+triton-electron mass ratio                             5496.921 5269         0.000 0051
+triton g factor                                        5.957 924 896         0.000 000 076
+triton mag. mom.                                       1.504 609 361 e-26    0.000 000 042 e-26    J T^-1
+triton mag. mom. to Bohr magneton ratio                1.622 393 657 e-3     0.000 000 021 e-3
+triton mag. mom. to nuclear magneton ratio             2.978 962 448         0.000 000 038
+triton mass                                            5.007 355 88 e-27     0.000 000 25 e-27     kg
+triton mass energy equivalent                          4.500 387 03 e-10     0.000 000 22 e-10     J
+triton mass energy equivalent in MeV                   2808.920 906          0.000 070             MeV
+triton mass in u                                       3.015 500 7134        0.000 000 0025        u
+triton molar mass                                      3.015 500 7134 e-3    0.000 000 0025 e-3    kg mol^-1
+triton-neutron mag. mom. ratio                         -1.557 185 53         0.000 000 37
+triton-proton mag. mom. ratio                          1.066 639 908         0.000 000 010
+triton-proton mass ratio                               2.993 717 0309        0.000 000 0025
+unified atomic mass unit                               1.660 538 782 e-27    0.000 000 083 e-27    kg
+von Klitzing constant                                  25 812.807 557        0.000 018             ohm
+weak mixing angle                                      0.222 55              0.000 56
+Wien frequency displacement law constant               5.878 933 e10         0.000 010 e10         Hz K^-1
+Wien wavelength displacement law constant              2.897 7685 e-3        0.000 0051 e-3        m K"""
+
+
+def exact2006(exact):
+    mu0 = 4e-7 * math.pi
+    c = exact['speed of light in vacuum']
+    epsilon0 = 1 / (mu0 * c**2)
+    replace = {
+        'mag. constant': mu0,
+        'electric constant': epsilon0,
+        'atomic unit of permittivity': 4*math.pi*epsilon0,
+        'characteristic impedance of vacuum': math.sqrt(mu0 / epsilon0),
+        'hertz-inverse meter relationship': 1/c,
+        'joule-kilogram relationship': 1/c**2,
+        'kilogram-joule relationship': c**2,
+    }
+    return replace
+
+
+txt2010 = """\
+{220} lattice spacing of silicon                       192.015 5714 e-12     0.000 0032 e-12       m
+alpha particle-electron mass ratio                     7294.299 5361         0.000 0029
+alpha particle mass                                    6.644 656 75 e-27     0.000 000 29 e-27     kg
+alpha particle mass energy equivalent                  5.971 919 67 e-10     0.000 000 26 e-10     J
+alpha particle mass energy equivalent in MeV           3727.379 240          0.000 082             MeV
+alpha particle mass in u                               4.001 506 179 125     0.000 000 000 062     u
+alpha particle molar mass                              4.001 506 179 125 e-3 0.000 000 000 062 e-3 kg mol^-1
+alpha particle-proton mass ratio                       3.972 599 689 33      0.000 000 000 36
+Angstrom star                                          1.000 014 95 e-10     0.000 000 90 e-10     m
+atomic mass constant                                   1.660 538 921 e-27    0.000 000 073 e-27    kg
+atomic mass constant energy equivalent                 1.492 417 954 e-10    0.000 000 066 e-10    J
+atomic mass constant energy equivalent in MeV          931.494 061           0.000 021             MeV
+atomic mass unit-electron volt relationship            931.494 061 e6        0.000 021 e6          eV
+atomic mass unit-hartree relationship                  3.423 177 6845 e7     0.000 000 0024 e7     E_h
+atomic mass unit-hertz relationship                    2.252 342 7168 e23    0.000 000 0016 e23    Hz
+atomic mass unit-inverse meter relationship            7.513 006 6042 e14    0.000 000 0053 e14    m^-1
+atomic mass unit-joule relationship                    1.492 417 954 e-10    0.000 000 066 e-10    J
+atomic mass unit-kelvin relationship                   1.080 954 08 e13      0.000 000 98 e13      K
+atomic mass unit-kilogram relationship                 1.660 538 921 e-27    0.000 000 073 e-27    kg
+atomic unit of 1st hyperpolarizability                 3.206 361 449 e-53    0.000 000 071 e-53    C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                 6.235 380 54 e-65     0.000 000 28 e-65     C^4 m^4 J^-3
+atomic unit of action                                  1.054 571 726 e-34    0.000 000 047 e-34    J s
+atomic unit of charge                                  1.602 176 565 e-19    0.000 000 035 e-19    C
+atomic unit of charge density                          1.081 202 338 e12     0.000 000 024 e12     C m^-3
+atomic unit of current                                 6.623 617 95 e-3      0.000 000 15 e-3      A
+atomic unit of electric dipole mom.                    8.478 353 26 e-30     0.000 000 19 e-30     C m
+atomic unit of electric field                          5.142 206 52 e11      0.000 000 11 e11      V m^-1
+atomic unit of electric field gradient                 9.717 362 00 e21      0.000 000 21 e21      V m^-2
+atomic unit of electric polarizability                 1.648 777 2754 e-41   0.000 000 0016 e-41   C^2 m^2 J^-1
+atomic unit of electric potential                      27.211 385 05         0.000 000 60          V
+atomic unit of electric quadrupole mom.                4.486 551 331 e-40    0.000 000 099 e-40    C m^2
+atomic unit of energy                                  4.359 744 34 e-18     0.000 000 19 e-18     J
+atomic unit of force                                   8.238 722 78 e-8      0.000 000 36 e-8      N
+atomic unit of length                                  0.529 177 210 92 e-10 0.000 000 000 17 e-10 m
+atomic unit of mag. dipole mom.                        1.854 801 936 e-23    0.000 000 041 e-23    J T^-1
+atomic unit of mag. flux density                       2.350 517 464 e5      0.000 000 052 e5      T
+atomic unit of magnetizability                         7.891 036 607 e-29    0.000 000 013 e-29    J T^-2
+atomic unit of mass                                    9.109 382 91 e-31     0.000 000 40 e-31     kg
+atomic unit of mom.um                                  1.992 851 740 e-24    0.000 000 088 e-24    kg m s^-1
+atomic unit of permittivity                            1.112 650 056... e-10 (exact)               F m^-1
+atomic unit of time                                    2.418 884 326 502e-17 0.000 000 000 012e-17 s
+atomic unit of velocity                                2.187 691 263 79 e6   0.000 000 000 71 e6   m s^-1
+Avogadro constant                                      6.022 141 29 e23      0.000 000 27 e23      mol^-1
+Bohr magneton                                          927.400 968 e-26      0.000 020 e-26        J T^-1
+Bohr magneton in eV/T                                  5.788 381 8066 e-5    0.000 000 0038 e-5    eV T^-1
+Bohr magneton in Hz/T                                  13.996 245 55 e9      0.000 000 31 e9       Hz T^-1
+Bohr magneton in inverse meters per tesla              46.686 4498           0.000 0010            m^-1 T^-1
+Bohr magneton in K/T                                   0.671 713 88          0.000 000 61          K T^-1
+Bohr radius                                            0.529 177 210 92 e-10 0.000 000 000 17 e-10 m
+Boltzmann constant                                     1.380 6488 e-23       0.000 0013 e-23       J K^-1
+Boltzmann constant in eV/K                             8.617 3324 e-5        0.000 0078 e-5        eV K^-1
+Boltzmann constant in Hz/K                             2.083 6618 e10        0.000 0019 e10        Hz K^-1
+Boltzmann constant in inverse meters per kelvin        69.503 476            0.000 063             m^-1 K^-1
+characteristic impedance of vacuum                     376.730 313 461...    (exact)               ohm
+classical electron radius                              2.817 940 3267 e-15   0.000 000 0027 e-15   m
+Compton wavelength                                     2.426 310 2389 e-12   0.000 000 0016 e-12   m
+Compton wavelength over 2 pi                           386.159 268 00 e-15   0.000 000 25 e-15     m
+conductance quantum                                    7.748 091 7346 e-5    0.000 000 0025 e-5    S
+conventional value of Josephson constant               483 597.9 e9          (exact)               Hz V^-1
+conventional value of von Klitzing constant            25 812.807            (exact)               ohm
+Cu x unit                                              1.002 076 97 e-13     0.000 000 28 e-13     m
+deuteron-electron mag. mom. ratio                      -4.664 345 537 e-4    0.000 000 039 e-4
+deuteron-electron mass ratio                           3670.482 9652         0.000 0015
+deuteron g factor                                      0.857 438 2308        0.000 000 0072
+deuteron mag. mom.                                     0.433 073 489 e-26    0.000 000 010 e-26    J T^-1
+deuteron mag. mom. to Bohr magneton ratio              0.466 975 4556 e-3    0.000 000 0039 e-3
+deuteron mag. mom. to nuclear magneton ratio           0.857 438 2308        0.000 000 0072
+deuteron mass                                          3.343 583 48 e-27     0.000 000 15 e-27     kg
+deuteron mass energy equivalent                        3.005 062 97 e-10     0.000 000 13 e-10     J
+deuteron mass energy equivalent in MeV                 1875.612 859          0.000 041             MeV
+deuteron mass in u                                     2.013 553 212 712     0.000 000 000 077     u
+deuteron molar mass                                    2.013 553 212 712 e-3 0.000 000 000 077 e-3 kg mol^-1
+deuteron-neutron mag. mom. ratio                       -0.448 206 52         0.000 000 11
+deuteron-proton mag. mom. ratio                        0.307 012 2070        0.000 000 0024
+deuteron-proton mass ratio                             1.999 007 500 97      0.000 000 000 18
+deuteron rms charge radius                             2.1424 e-15           0.0021 e-15           m
+electric constant                                      8.854 187 817... e-12 (exact)               F m^-1
+electron charge to mass quotient                       -1.758 820 088 e11    0.000 000 039 e11     C kg^-1
+electron-deuteron mag. mom. ratio                      -2143.923 498         0.000 018
+electron-deuteron mass ratio                           2.724 437 1095 e-4    0.000 000 0011 e-4
+electron g factor                                      -2.002 319 304 361 53 0.000 000 000 000 53
+electron gyromag. ratio                                1.760 859 708 e11     0.000 000 039 e11     s^-1 T^-1
+electron gyromag. ratio over 2 pi                      28 024.952 66         0.000 62              MHz T^-1
+electron-helion mass ratio                             1.819 543 0761 e-4    0.000 000 0017 e-4
+electron mag. mom.                                     -928.476 430 e-26     0.000 021 e-26        J T^-1
+electron mag. mom. anomaly                             1.159 652 180 76 e-3  0.000 000 000 27 e-3
+electron mag. mom. to Bohr magneton ratio              -1.001 159 652 180 76 0.000 000 000 000 27
+electron mag. mom. to nuclear magneton ratio           -1838.281 970 90      0.000 000 75
+electron mass                                          9.109 382 91 e-31     0.000 000 40 e-31     kg
+electron mass energy equivalent                        8.187 105 06 e-14     0.000 000 36 e-14     J
+electron mass energy equivalent in MeV                 0.510 998 928         0.000 000 011         MeV
+electron mass in u                                     5.485 799 0946 e-4    0.000 000 0022 e-4    u
+electron molar mass                                    5.485 799 0946 e-7    0.000 000 0022 e-7    kg mol^-1
+electron-muon mag. mom. ratio                          206.766 9896          0.000 0052
+electron-muon mass ratio                               4.836 331 66 e-3      0.000 000 12 e-3
+electron-neutron mag. mom. ratio                       960.920 50            0.000 23
+electron-neutron mass ratio                            5.438 673 4461 e-4    0.000 000 0032 e-4
+electron-proton mag. mom. ratio                        -658.210 6848         0.000 0054
+electron-proton mass ratio                             5.446 170 2178 e-4    0.000 000 0022 e-4
+electron-tau mass ratio                                2.875 92 e-4          0.000 26 e-4
+electron to alpha particle mass ratio                  1.370 933 555 78 e-4  0.000 000 000 55 e-4
+electron to shielded helion mag. mom. ratio            864.058 257           0.000 010
+electron to shielded proton mag. mom. ratio            -658.227 5971         0.000 0072
+electron-triton mass ratio                             1.819 200 0653 e-4    0.000 000 0017 e-4
+electron volt                                          1.602 176 565 e-19    0.000 000 035 e-19    J
+electron volt-atomic mass unit relationship            1.073 544 150 e-9     0.000 000 024 e-9     u
+electron volt-hartree relationship                     3.674 932 379 e-2     0.000 000 081 e-2     E_h
+electron volt-hertz relationship                       2.417 989 348 e14     0.000 000 053 e14     Hz
+electron volt-inverse meter relationship               8.065 544 29 e5       0.000 000 18 e5       m^-1
+electron volt-joule relationship                       1.602 176 565 e-19    0.000 000 035 e-19    J
+electron volt-kelvin relationship                      1.160 4519 e4         0.000 0011 e4         K
+electron volt-kilogram relationship                    1.782 661 845 e-36    0.000 000 039 e-36    kg
+elementary charge                                      1.602 176 565 e-19    0.000 000 035 e-19    C
+elementary charge over h                               2.417 989 348 e14     0.000 000 053 e14     A J^-1
+Faraday constant                                       96 485.3365           0.0021                C mol^-1
+Faraday constant for conventional electric current     96 485.3321           0.0043                C_90 mol^-1
+Fermi coupling constant                                1.166 364 e-5         0.000 005 e-5         GeV^-2
+fine-structure constant                                7.297 352 5698 e-3    0.000 000 0024 e-3
+first radiation constant                               3.741 771 53 e-16     0.000 000 17 e-16     W m^2
+first radiation constant for spectral radiance         1.191 042 869 e-16    0.000 000 053 e-16    W m^2 sr^-1
+hartree-atomic mass unit relationship                  2.921 262 3246 e-8    0.000 000 0021 e-8    u
+hartree-electron volt relationship                     27.211 385 05         0.000 000 60          eV
+Hartree energy                                         4.359 744 34 e-18     0.000 000 19 e-18     J
+Hartree energy in eV                                   27.211 385 05         0.000 000 60          eV
+hartree-hertz relationship                             6.579 683 920 729 e15 0.000 000 000 033 e15 Hz
+hartree-inverse meter relationship                     2.194 746 313 708 e7  0.000 000 000 011 e7  m^-1
+hartree-joule relationship                             4.359 744 34 e-18     0.000 000 19 e-18     J
+hartree-kelvin relationship                            3.157 7504 e5         0.000 0029 e5         K
+hartree-kilogram relationship                          4.850 869 79 e-35     0.000 000 21 e-35     kg
+helion-electron mass ratio                             5495.885 2754         0.000 0050
+helion g factor                                        -4.255 250 613        0.000 000 050
+helion mag. mom.                                       -1.074 617 486 e-26   0.000 000 027 e-26    J T^-1
+helion mag. mom. to Bohr magneton ratio                -1.158 740 958 e-3    0.000 000 014 e-3
+helion mag. mom. to nuclear magneton ratio             -2.127 625 306        0.000 000 025
+helion mass                                            5.006 412 34 e-27     0.000 000 22 e-27     kg
+helion mass energy equivalent                          4.499 539 02 e-10     0.000 000 20 e-10     J
+helion mass energy equivalent in MeV                   2808.391 482          0.000 062             MeV
+helion mass in u                                       3.014 932 2468        0.000 000 0025        u
+helion molar mass                                      3.014 932 2468 e-3    0.000 000 0025 e-3    kg mol^-1
+helion-proton mass ratio                               2.993 152 6707        0.000 000 0025
+hertz-atomic mass unit relationship                    4.439 821 6689 e-24   0.000 000 0031 e-24   u
+hertz-electron volt relationship                       4.135 667 516 e-15    0.000 000 091 e-15    eV
+hertz-hartree relationship                             1.519 829 8460045e-16 0.000 000 0000076e-16 E_h
+hertz-inverse meter relationship                       3.335 640 951... e-9  (exact)               m^-1
+hertz-joule relationship                               6.626 069 57 e-34     0.000 000 29 e-34     J
+hertz-kelvin relationship                              4.799 2434 e-11       0.000 0044 e-11       K
+hertz-kilogram relationship                            7.372 496 68 e-51     0.000 000 33 e-51     kg
+inverse fine-structure constant                        137.035 999 074       0.000 000 044
+inverse meter-atomic mass unit relationship            1.331 025 051 20 e-15 0.000 000 000 94 e-15 u
+inverse meter-electron volt relationship               1.239 841 930 e-6     0.000 000 027 e-6     eV
+inverse meter-hartree relationship                     4.556 335 252 755 e-8 0.000 000 000 023 e-8 E_h
+inverse meter-hertz relationship                       299 792 458           (exact)               Hz
+inverse meter-joule relationship                       1.986 445 684 e-25    0.000 000 088 e-25    J
+inverse meter-kelvin relationship                      1.438 7770 e-2        0.000 0013 e-2        K
+inverse meter-kilogram relationship                    2.210 218 902 e-42    0.000 000 098 e-42    kg
+inverse of conductance quantum                         12 906.403 7217       0.000 0042            ohm
+Josephson constant                                     483 597.870 e9        0.011 e9              Hz V^-1
+joule-atomic mass unit relationship                    6.700 535 85 e9       0.000 000 30 e9       u
+joule-electron volt relationship                       6.241 509 34 e18      0.000 000 14 e18      eV
+joule-hartree relationship                             2.293 712 48 e17      0.000 000 10 e17      E_h
+joule-hertz relationship                               1.509 190 311 e33     0.000 000 067 e33     Hz
+joule-inverse meter relationship                       5.034 117 01 e24      0.000 000 22 e24      m^-1
+joule-kelvin relationship                              7.242 9716 e22        0.000 0066 e22        K
+joule-kilogram relationship                            1.112 650 056... e-17 (exact)               kg
+kelvin-atomic mass unit relationship                   9.251 0868 e-14       0.000 0084 e-14       u
+kelvin-electron volt relationship                      8.617 3324 e-5        0.000 0078 e-5        eV
+kelvin-hartree relationship                            3.166 8114 e-6        0.000 0029 e-6        E_h
+kelvin-hertz relationship                              2.083 6618 e10        0.000 0019 e10        Hz
+kelvin-inverse meter relationship                      69.503 476            0.000 063             m^-1
+kelvin-joule relationship                              1.380 6488 e-23       0.000 0013 e-23       J
+kelvin-kilogram relationship                           1.536 1790 e-40       0.000 0014 e-40       kg
+kilogram-atomic mass unit relationship                 6.022 141 29 e26      0.000 000 27 e26      u
+kilogram-electron volt relationship                    5.609 588 85 e35      0.000 000 12 e35      eV
+kilogram-hartree relationship                          2.061 485 968 e34     0.000 000 091 e34     E_h
+kilogram-hertz relationship                            1.356 392 608 e50     0.000 000 060 e50     Hz
+kilogram-inverse meter relationship                    4.524 438 73 e41      0.000 000 20 e41      m^-1
+kilogram-joule relationship                            8.987 551 787... e16  (exact)               J
+kilogram-kelvin relationship                           6.509 6582 e39        0.000 0059 e39        K
+lattice parameter of silicon                           543.102 0504 e-12     0.000 0089 e-12       m
+Loschmidt constant (273.15 K, 100 kPa)                 2.651 6462 e25        0.000 0024 e25        m^-3
+Loschmidt constant (273.15 K, 101.325 kPa)             2.686 7805 e25        0.000 0024 e25        m^-3
+mag. constant                                          12.566 370 614... e-7 (exact)               N A^-2
+mag. flux quantum                                      2.067 833 758 e-15    0.000 000 046 e-15    Wb
+molar gas constant                                     8.314 4621            0.000 0075            J mol^-1 K^-1
+molar mass constant                                    1 e-3                 (exact)               kg mol^-1
+molar mass of carbon-12                                12 e-3                (exact)               kg mol^-1
+molar Planck constant                                  3.990 312 7176 e-10   0.000 000 0028 e-10   J s mol^-1
+molar Planck constant times c                          0.119 626 565 779     0.000 000 000 084     J m mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)          22.710 953 e-3        0.000 021 e-3         m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)      22.413 968 e-3        0.000 020 e-3         m^3 mol^-1
+molar volume of silicon                                12.058 833 01 e-6     0.000 000 80 e-6      m^3 mol^-1
+Mo x unit                                              1.002 099 52 e-13     0.000 000 53 e-13     m
+muon Compton wavelength                                11.734 441 03 e-15    0.000 000 30 e-15     m
+muon Compton wavelength over 2 pi                      1.867 594 294 e-15    0.000 000 047 e-15    m
+muon-electron mass ratio                               206.768 2843          0.000 0052
+muon g factor                                          -2.002 331 8418       0.000 000 0013
+muon mag. mom.                                         -4.490 448 07 e-26    0.000 000 15 e-26     J T^-1
+muon mag. mom. anomaly                                 1.165 920 91 e-3      0.000 000 63 e-3
+muon mag. mom. to Bohr magneton ratio                  -4.841 970 44 e-3     0.000 000 12 e-3
+muon mag. mom. to nuclear magneton ratio               -8.890 596 97         0.000 000 22
+muon mass                                              1.883 531 475 e-28    0.000 000 096 e-28    kg
+muon mass energy equivalent                            1.692 833 667 e-11    0.000 000 086 e-11    J
+muon mass energy equivalent in MeV                     105.658 3715          0.000 0035            MeV
+muon mass in u                                         0.113 428 9267        0.000 000 0029        u
+muon molar mass                                        0.113 428 9267 e-3    0.000 000 0029 e-3    kg mol^-1
+muon-neutron mass ratio                                0.112 454 5177        0.000 000 0028
+muon-proton mag. mom. ratio                            -3.183 345 107        0.000 000 084
+muon-proton mass ratio                                 0.112 609 5272        0.000 000 0028
+muon-tau mass ratio                                    5.946 49 e-2          0.000 54 e-2
+natural unit of action                                 1.054 571 726 e-34    0.000 000 047 e-34    J s
+natural unit of action in eV s                         6.582 119 28 e-16     0.000 000 15 e-16     eV s
+natural unit of energy                                 8.187 105 06 e-14     0.000 000 36 e-14     J
+natural unit of energy in MeV                          0.510 998 928         0.000 000 011         MeV
+natural unit of length                                 386.159 268 00 e-15   0.000 000 25 e-15     m
+natural unit of mass                                   9.109 382 91 e-31     0.000 000 40 e-31     kg
+natural unit of mom.um                                 2.730 924 29 e-22     0.000 000 12 e-22     kg m s^-1
+natural unit of mom.um in MeV/c                        0.510 998 928         0.000 000 011         MeV/c
+natural unit of time                                   1.288 088 668 33 e-21 0.000 000 000 83 e-21 s
+natural unit of velocity                               299 792 458           (exact)               m s^-1
+neutron Compton wavelength                             1.319 590 9068 e-15   0.000 000 0011 e-15   m
+neutron Compton wavelength over 2 pi                   0.210 019 415 68 e-15 0.000 000 000 17 e-15 m
+neutron-electron mag. mom. ratio                       1.040 668 82 e-3      0.000 000 25 e-3
+neutron-electron mass ratio                            1838.683 6605         0.000 0011
+neutron g factor                                       -3.826 085 45         0.000 000 90
+neutron gyromag. ratio                                 1.832 471 79 e8       0.000 000 43 e8       s^-1 T^-1
+neutron gyromag. ratio over 2 pi                       29.164 6943           0.000 0069            MHz T^-1
+neutron mag. mom.                                      -0.966 236 47 e-26    0.000 000 23 e-26     J T^-1
+neutron mag. mom. to Bohr magneton ratio               -1.041 875 63 e-3     0.000 000 25 e-3
+neutron mag. mom. to nuclear magneton ratio            -1.913 042 72         0.000 000 45
+neutron mass                                           1.674 927 351 e-27    0.000 000 074 e-27    kg
+neutron mass energy equivalent                         1.505 349 631 e-10    0.000 000 066 e-10    J
+neutron mass energy equivalent in MeV                  939.565 379           0.000 021             MeV
+neutron mass in u                                      1.008 664 916 00      0.000 000 000 43      u
+neutron molar mass                                     1.008 664 916 00 e-3  0.000 000 000 43 e-3  kg mol^-1
+neutron-muon mass ratio                                8.892 484 00          0.000 000 22
+neutron-proton mag. mom. ratio                         -0.684 979 34         0.000 000 16
+neutron-proton mass difference                         2.305 573 92 e-30     0.000 000 76 e-30
+neutron-proton mass difference energy equivalent       2.072 146 50 e-13     0.000 000 68 e-13
+neutron-proton mass difference energy equivalent in MeV 1.293 332 17          0.000 000 42
+neutron-proton mass difference in u                    0.001 388 449 19      0.000 000 000 45
+neutron-proton mass ratio                              1.001 378 419 17      0.000 000 000 45
+neutron-tau mass ratio                                 0.528 790             0.000 048
+neutron to shielded proton mag. mom. ratio             -0.684 996 94         0.000 000 16
+Newtonian constant of gravitation                      6.673 84 e-11         0.000 80 e-11         m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c         6.708 37 e-39         0.000 80 e-39         (GeV/c^2)^-2
+nuclear magneton                                       5.050 783 53 e-27     0.000 000 11 e-27     J T^-1
+nuclear magneton in eV/T                               3.152 451 2605 e-8    0.000 000 0022 e-8    eV T^-1
+nuclear magneton in inverse meters per tesla           2.542 623 527 e-2     0.000 000 056 e-2     m^-1 T^-1
+nuclear magneton in K/T                                3.658 2682 e-4        0.000 0033 e-4        K T^-1
+nuclear magneton in MHz/T                              7.622 593 57          0.000 000 17          MHz T^-1
+Planck constant                                        6.626 069 57 e-34     0.000 000 29 e-34     J s
+Planck constant in eV s                                4.135 667 516 e-15    0.000 000 091 e-15    eV s
+Planck constant over 2 pi                              1.054 571 726 e-34    0.000 000 047 e-34    J s
+Planck constant over 2 pi in eV s                      6.582 119 28 e-16     0.000 000 15 e-16     eV s
+Planck constant over 2 pi times c in MeV fm            197.326 9718          0.000 0044            MeV fm
+Planck length                                          1.616 199 e-35        0.000 097 e-35        m
+Planck mass                                            2.176 51 e-8          0.000 13 e-8          kg
+Planck mass energy equivalent in GeV                   1.220 932 e19         0.000 073 e19         GeV
+Planck temperature                                     1.416 833 e32         0.000 085 e32         K
+Planck time                                            5.391 06 e-44         0.000 32 e-44         s
+proton charge to mass quotient                         9.578 833 58 e7       0.000 000 21 e7       C kg^-1
+proton Compton wavelength                              1.321 409 856 23 e-15 0.000 000 000 94 e-15 m
+proton Compton wavelength over 2 pi                    0.210 308 910 47 e-15 0.000 000 000 15 e-15 m
+proton-electron mass ratio                             1836.152 672 45       0.000 000 75
+proton g factor                                        5.585 694 713         0.000 000 046
+proton gyromag. ratio                                  2.675 222 005 e8      0.000 000 063 e8      s^-1 T^-1
+proton gyromag. ratio over 2 pi                        42.577 4806           0.000 0010            MHz T^-1
+proton mag. mom.                                       1.410 606 743 e-26    0.000 000 033 e-26    J T^-1
+proton mag. mom. to Bohr magneton ratio                1.521 032 210 e-3     0.000 000 012 e-3
+proton mag. mom. to nuclear magneton ratio             2.792 847 356         0.000 000 023
+proton mag. shielding correction                       25.694 e-6            0.014 e-6
+proton mass                                            1.672 621 777 e-27    0.000 000 074 e-27    kg
+proton mass energy equivalent                          1.503 277 484 e-10    0.000 000 066 e-10    J
+proton mass energy equivalent in MeV                   938.272 046           0.000 021             MeV
+proton mass in u                                       1.007 276 466 812     0.000 000 000 090     u
+proton molar mass                                      1.007 276 466 812 e-3 0.000 000 000 090 e-3 kg mol^-1
+proton-muon mass ratio                                 8.880 243 31          0.000 000 22
+proton-neutron mag. mom. ratio                         -1.459 898 06         0.000 000 34
+proton-neutron mass ratio                              0.998 623 478 26      0.000 000 000 45
+proton rms charge radius                               0.8775 e-15           0.0051 e-15           m
+proton-tau mass ratio                                  0.528 063             0.000 048
+quantum of circulation                                 3.636 947 5520 e-4    0.000 000 0024 e-4    m^2 s^-1
+quantum of circulation times 2                         7.273 895 1040 e-4    0.000 000 0047 e-4    m^2 s^-1
+Rydberg constant                                       10 973 731.568 539    0.000 055             m^-1
+Rydberg constant times c in Hz                         3.289 841 960 364 e15 0.000 000 000 017 e15 Hz
+Rydberg constant times hc in eV                        13.605 692 53         0.000 000 30          eV
+Rydberg constant times hc in J                         2.179 872 171 e-18    0.000 000 096 e-18    J
+Sackur-Tetrode constant (1 K, 100 kPa)                 -1.151 7078           0.000 0023
+Sackur-Tetrode constant (1 K, 101.325 kPa)             -1.164 8708           0.000 0023
+second radiation constant                              1.438 7770 e-2        0.000 0013 e-2        m K
+shielded helion gyromag. ratio                         2.037 894 659 e8      0.000 000 051 e8      s^-1 T^-1
+shielded helion gyromag. ratio over 2 pi               32.434 100 84         0.000 000 81          MHz T^-1
+shielded helion mag. mom.                              -1.074 553 044 e-26   0.000 000 027 e-26    J T^-1
+shielded helion mag. mom. to Bohr magneton ratio       -1.158 671 471 e-3    0.000 000 014 e-3
+shielded helion mag. mom. to nuclear magneton ratio    -2.127 497 718        0.000 000 025
+shielded helion to proton mag. mom. ratio              -0.761 766 558        0.000 000 011
+shielded helion to shielded proton mag. mom. ratio     -0.761 786 1313       0.000 000 0033
+shielded proton gyromag. ratio                         2.675 153 268 e8      0.000 000 066 e8      s^-1 T^-1
+shielded proton gyromag. ratio over 2 pi               42.576 3866           0.000 0010            MHz T^-1
+shielded proton mag. mom.                              1.410 570 499 e-26    0.000 000 035 e-26    J T^-1
+shielded proton mag. mom. to Bohr magneton ratio       1.520 993 128 e-3     0.000 000 017 e-3
+shielded proton mag. mom. to nuclear magneton ratio    2.792 775 598         0.000 000 030
+speed of light in vacuum                               299 792 458           (exact)               m s^-1
+standard acceleration of gravity                       9.806 65              (exact)               m s^-2
+standard atmosphere                                    101 325               (exact)               Pa
+standard-state pressure                                100 000               (exact)               Pa
+Stefan-Boltzmann constant                              5.670 373 e-8         0.000 021 e-8         W m^-2 K^-4
+tau Compton wavelength                                 0.697 787 e-15        0.000 063 e-15        m
+tau Compton wavelength over 2 pi                       0.111 056 e-15        0.000 010 e-15        m
+tau-electron mass ratio                                3477.15               0.31
+tau mass                                               3.167 47 e-27         0.000 29 e-27         kg
+tau mass energy equivalent                             2.846 78 e-10         0.000 26 e-10         J
+tau mass energy equivalent in MeV                      1776.82               0.16                  MeV
+tau mass in u                                          1.907 49              0.000 17              u
+tau molar mass                                         1.907 49 e-3          0.000 17 e-3          kg mol^-1
+tau-muon mass ratio                                    16.8167               0.0015
+tau-neutron mass ratio                                 1.891 11              0.000 17
+tau-proton mass ratio                                  1.893 72              0.000 17
+Thomson cross section                                  0.665 245 8734 e-28   0.000 000 0013 e-28   m^2
+triton-electron mass ratio                             5496.921 5267         0.000 0050
+triton g factor                                        5.957 924 896         0.000 000 076
+triton mag. mom.                                       1.504 609 447 e-26    0.000 000 038 e-26    J T^-1
+triton mag. mom. to Bohr magneton ratio                1.622 393 657 e-3     0.000 000 021 e-3
+triton mag. mom. to nuclear magneton ratio             2.978 962 448         0.000 000 038
+triton mass                                            5.007 356 30 e-27     0.000 000 22 e-27     kg
+triton mass energy equivalent                          4.500 387 41 e-10     0.000 000 20 e-10     J
+triton mass energy equivalent in MeV                   2808.921 005          0.000 062             MeV
+triton mass in u                                       3.015 500 7134        0.000 000 0025        u
+triton molar mass                                      3.015 500 7134 e-3    0.000 000 0025 e-3    kg mol^-1
+triton-proton mass ratio                               2.993 717 0308        0.000 000 0025
+unified atomic mass unit                               1.660 538 921 e-27    0.000 000 073 e-27    kg
+von Klitzing constant                                  25 812.807 4434       0.000 0084            ohm
+weak mixing angle                                      0.2223                0.0021
+Wien frequency displacement law constant               5.878 9254 e10        0.000 0053 e10        Hz K^-1
+Wien wavelength displacement law constant              2.897 7721 e-3        0.000 0026 e-3        m K"""
+
+
+exact2010 = exact2006
+
+
+txt2014 = """\
+{220} lattice spacing of silicon                       192.015 5714 e-12     0.000 0032 e-12       m
+alpha particle-electron mass ratio                     7294.299 541 36       0.000 000 24
+alpha particle mass                                    6.644 657 230 e-27    0.000 000 082 e-27    kg
+alpha particle mass energy equivalent                  5.971 920 097 e-10    0.000 000 073 e-10    J
+alpha particle mass energy equivalent in MeV           3727.379 378          0.000 023             MeV
+alpha particle mass in u                               4.001 506 179 127     0.000 000 000 063     u
+alpha particle molar mass                              4.001 506 179 127 e-3 0.000 000 000 063 e-3 kg mol^-1
+alpha particle-proton mass ratio                       3.972 599 689 07      0.000 000 000 36
+Angstrom star                                          1.000 014 95 e-10     0.000 000 90 e-10     m
+atomic mass constant                                   1.660 539 040 e-27    0.000 000 020 e-27    kg
+atomic mass constant energy equivalent                 1.492 418 062 e-10    0.000 000 018 e-10    J
+atomic mass constant energy equivalent in MeV          931.494 0954          0.000 0057            MeV
+atomic mass unit-electron volt relationship            931.494 0954 e6       0.000 0057 e6         eV
+atomic mass unit-hartree relationship                  3.423 177 6902 e7     0.000 000 0016 e7     E_h
+atomic mass unit-hertz relationship                    2.252 342 7206 e23    0.000 000 0010 e23    Hz
+atomic mass unit-inverse meter relationship            7.513 006 6166 e14    0.000 000 0034 e14    m^-1
+atomic mass unit-joule relationship                    1.492 418 062 e-10    0.000 000 018 e-10    J
+atomic mass unit-kelvin relationship                   1.080 954 38 e13      0.000 000 62 e13      K
+atomic mass unit-kilogram relationship                 1.660 539 040 e-27    0.000 000 020 e-27    kg
+atomic unit of 1st hyperpolarizability                 3.206 361 329 e-53    0.000 000 020 e-53    C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                 6.235 380 085 e-65    0.000 000 077 e-65    C^4 m^4 J^-3
+atomic unit of action                                  1.054 571 800 e-34    0.000 000 013 e-34    J s
+atomic unit of charge                                  1.602 176 6208 e-19   0.000 000 0098 e-19   C
+atomic unit of charge density                          1.081 202 3770 e12    0.000 000 0067 e12    C m^-3
+atomic unit of current                                 6.623 618 183 e-3     0.000 000 041 e-3     A
+atomic unit of electric dipole mom.                    8.478 353 552 e-30    0.000 000 052 e-30    C m
+atomic unit of electric field                          5.142 206 707 e11     0.000 000 032 e11     V m^-1
+atomic unit of electric field gradient                 9.717 362 356 e21     0.000 000 060 e21     V m^-2
+atomic unit of electric polarizability                 1.648 777 2731 e-41   0.000 000 0011 e-41   C^2 m^2 J^-1
+atomic unit of electric potential                      27.211 386 02         0.000 000 17          V
+atomic unit of electric quadrupole mom.                4.486 551 484 e-40    0.000 000 028 e-40    C m^2
+atomic unit of energy                                  4.359 744 650 e-18    0.000 000 054 e-18    J
+atomic unit of force                                   8.238 723 36 e-8      0.000 000 10 e-8      N
+atomic unit of length                                  0.529 177 210 67 e-10 0.000 000 000 12 e-10 m
+atomic unit of mag. dipole mom.                        1.854 801 999 e-23    0.000 000 011 e-23    J T^-1
+atomic unit of mag. flux density                       2.350 517 550 e5      0.000 000 014 e5      T
+atomic unit of magnetizability                         7.891 036 5886 e-29   0.000 000 0090 e-29   J T^-2
+atomic unit of mass                                    9.109 383 56 e-31     0.000 000 11 e-31     kg
+atomic unit of mom.um                                  1.992 851 882 e-24    0.000 000 024 e-24    kg m s^-1
+atomic unit of permittivity                            1.112 650 056... e-10 (exact)               F m^-1
+atomic unit of time                                    2.418 884 326509e-17  0.000 000 000014e-17  s
+atomic unit of velocity                                2.187 691 262 77 e6   0.000 000 000 50 e6   m s^-1
+Avogadro constant                                      6.022 140 857 e23     0.000 000 074 e23     mol^-1
+Bohr magneton                                          927.400 9994 e-26     0.000 0057 e-26       J T^-1
+Bohr magneton in eV/T                                  5.788 381 8012 e-5    0.000 000 0026 e-5    eV T^-1
+Bohr magneton in Hz/T                                  13.996 245 042 e9     0.000 000 086 e9      Hz T^-1
+Bohr magneton in inverse meters per tesla              46.686 448 14         0.000 000 29          m^-1 T^-1
+Bohr magneton in K/T                                   0.671 714 05          0.000 000 39          K T^-1
+Bohr radius                                            0.529 177 210 67 e-10 0.000 000 000 12 e-10 m
+Boltzmann constant                                     1.380 648 52 e-23     0.000 000 79 e-23     J K^-1
+Boltzmann constant in eV/K                             8.617 3303 e-5        0.000 0050 e-5        eV K^-1
+Boltzmann constant in Hz/K                             2.083 6612 e10        0.000 0012 e10        Hz K^-1
+Boltzmann constant in inverse meters per kelvin        69.503 457            0.000 040             m^-1 K^-1
+characteristic impedance of vacuum                     376.730 313 461...    (exact)               ohm
+classical electron radius                              2.817 940 3227 e-15   0.000 000 0019 e-15   m
+Compton wavelength                                     2.426 310 2367 e-12   0.000 000 0011 e-12   m
+Compton wavelength over 2 pi                           386.159 267 64 e-15   0.000 000 18 e-15     m
+conductance quantum                                    7.748 091 7310 e-5    0.000 000 0018 e-5    S
+conventional value of Josephson constant               483 597.9 e9          (exact)               Hz V^-1
+conventional value of von Klitzing constant            25 812.807            (exact)               ohm
+Cu x unit                                              1.002 076 97 e-13     0.000 000 28 e-13     m
+deuteron-electron mag. mom. ratio                      -4.664 345 535 e-4    0.000 000 026 e-4
+deuteron-electron mass ratio                           3670.482 967 85       0.000 000 13
+deuteron g factor                                      0.857 438 2311        0.000 000 0048
+deuteron mag. mom.                                     0.433 073 5040 e-26   0.000 000 0036 e-26   J T^-1
+deuteron mag. mom. to Bohr magneton ratio              0.466 975 4554 e-3    0.000 000 0026 e-3
+deuteron mag. mom. to nuclear magneton ratio           0.857 438 2311        0.000 000 0048
+deuteron mass                                          3.343 583 719 e-27    0.000 000 041 e-27    kg
+deuteron mass energy equivalent                        3.005 063 183 e-10    0.000 000 037 e-10    J
+deuteron mass energy equivalent in MeV                 1875.612 928          0.000 012             MeV
+deuteron mass in u                                     2.013 553 212 745     0.000 000 000 040     u
+deuteron molar mass                                    2.013 553 212 745 e-3 0.000 000 000 040 e-3 kg mol^-1
+deuteron-neutron mag. mom. ratio                       -0.448 206 52         0.000 000 11
+deuteron-proton mag. mom. ratio                        0.307 012 2077        0.000 000 0015
+deuteron-proton mass ratio                             1.999 007 500 87      0.000 000 000 19
+deuteron rms charge radius                             2.1413 e-15           0.0025 e-15           m
+electric constant                                      8.854 187 817... e-12 (exact)               F m^-1
+electron charge to mass quotient                       -1.758 820 024 e11    0.000 000 011 e11     C kg^-1
+electron-deuteron mag. mom. ratio                      -2143.923 499         0.000 012
+electron-deuteron mass ratio                           2.724 437 107 484 e-4 0.000 000 000 096 e-4
+electron g factor                                      -2.002 319 304 361 82 0.000 000 000 000 52
+electron gyromag. ratio                                1.760 859 644 e11     0.000 000 011 e11     s^-1 T^-1
+electron gyromag. ratio over 2 pi                      28 024.951 64         0.000 17              MHz T^-1
+electron-helion mass ratio                             1.819 543 074 854 e-4 0.000 000 000 088 e-4
+electron mag. mom.                                     -928.476 4620 e-26    0.000 0057 e-26       J T^-1
+electron mag. mom. anomaly                             1.159 652 180 91 e-3  0.000 000 000 26 e-3
+electron mag. mom. to Bohr magneton ratio              -1.001 159 652 180 91 0.000 000 000 000 26
+electron mag. mom. to nuclear magneton ratio           -1838.281 972 34      0.000 000 17
+electron mass                                          9.109 383 56 e-31     0.000 000 11 e-31     kg
+electron mass energy equivalent                        8.187 105 65 e-14     0.000 000 10 e-14     J
+electron mass energy equivalent in MeV                 0.510 998 9461        0.000 000 0031        MeV
+electron mass in u                                     5.485 799 090 70 e-4  0.000 000 000 16 e-4  u
+electron molar mass                                    5.485 799 090 70 e-7  0.000 000 000 16 e-7  kg mol^-1
+electron-muon mag. mom. ratio                          206.766 9880          0.000 0046
+electron-muon mass ratio                               4.836 331 70 e-3      0.000 000 11 e-3
+electron-neutron mag. mom. ratio                       960.920 50            0.000 23
+electron-neutron mass ratio                            5.438 673 4428 e-4    0.000 000 0027 e-4
+electron-proton mag. mom. ratio                        -658.210 6866         0.000 0020
+electron-proton mass ratio                             5.446 170 213 52 e-4  0.000 000 000 52 e-4
+electron-tau mass ratio                                2.875 92 e-4          0.000 26 e-4
+electron to alpha particle mass ratio                  1.370 933 554 798 e-4 0.000 000 000 045 e-4
+electron to shielded helion mag. mom. ratio            864.058 257           0.000 010
+electron to shielded proton mag. mom. ratio            -658.227 5971         0.000 0072
+electron-triton mass ratio                             1.819 200 062 203 e-4 0.000 000 000 084 e-4
+electron volt                                          1.602 176 6208 e-19   0.000 000 0098 e-19   J
+electron volt-atomic mass unit relationship            1.073 544 1105 e-9    0.000 000 0066 e-9    u
+electron volt-hartree relationship                     3.674 932 248 e-2     0.000 000 023 e-2     E_h
+electron volt-hertz relationship                       2.417 989 262 e14     0.000 000 015 e14     Hz
+electron volt-inverse meter relationship               8.065 544 005 e5      0.000 000 050 e5      m^-1
+electron volt-joule relationship                       1.602 176 6208 e-19   0.000 000 0098 e-19   J
+electron volt-kelvin relationship                      1.160 452 21 e4       0.000 000 67 e4       K
+electron volt-kilogram relationship                    1.782 661 907 e-36    0.000 000 011 e-36    kg
+elementary charge                                      1.602 176 6208 e-19   0.000 000 0098 e-19   C
+elementary charge over h                               2.417 989 262 e14     0.000 000 015 e14     A J^-1
+Faraday constant                                       96 485.332 89         0.000 59              C mol^-1
+Faraday constant for conventional electric current     96 485.3251           0.0012                C_90 mol^-1
+Fermi coupling constant                                1.166 3787 e-5        0.000 0006 e-5        GeV^-2
+fine-structure constant                                7.297 352 5664 e-3    0.000 000 0017 e-3
+first radiation constant                               3.741 771 790 e-16    0.000 000 046 e-16    W m^2
+first radiation constant for spectral radiance         1.191 042 953 e-16    0.000 000 015 e-16    W m^2 sr^-1
+hartree-atomic mass unit relationship                  2.921 262 3197 e-8    0.000 000 0013 e-8    u
+hartree-electron volt relationship                     27.211 386 02         0.000 000 17          eV
+Hartree energy                                         4.359 744 650 e-18    0.000 000 054 e-18    J
+Hartree energy in eV                                   27.211 386 02         0.000 000 17          eV
+hartree-hertz relationship                             6.579 683 920 711 e15 0.000 000 000 039 e15 Hz
+hartree-inverse meter relationship                     2.194 746 313 702 e7  0.000 000 000 013 e7  m^-1
+hartree-joule relationship                             4.359 744 650 e-18    0.000 000 054 e-18    J
+hartree-kelvin relationship                            3.157 7513 e5         0.000 0018 e5         K
+hartree-kilogram relationship                          4.850 870 129 e-35    0.000 000 060 e-35    kg
+helion-electron mass ratio                             5495.885 279 22       0.000 000 27
+helion g factor                                        -4.255 250 616        0.000 000 050
+helion mag. mom.                                       -1.074 617 522 e-26   0.000 000 014 e-26    J T^-1
+helion mag. mom. to Bohr magneton ratio                -1.158 740 958 e-3    0.000 000 014 e-3
+helion mag. mom. to nuclear magneton ratio             -2.127 625 308        0.000 000 025
+helion mass                                            5.006 412 700 e-27    0.000 000 062 e-27    kg
+helion mass energy equivalent                          4.499 539 341 e-10    0.000 000 055 e-10    J
+helion mass energy equivalent in MeV                   2808.391 586          0.000 017             MeV
+helion mass in u                                       3.014 932 246 73      0.000 000 000 12      u
+helion molar mass                                      3.014 932 246 73 e-3  0.000 000 000 12 e-3  kg mol^-1
+helion-proton mass ratio                               2.993 152 670 46      0.000 000 000 29
+hertz-atomic mass unit relationship                    4.439 821 6616 e-24   0.000 000 0020 e-24   u
+hertz-electron volt relationship                       4.135 667 662 e-15    0.000 000 025 e-15    eV
+hertz-hartree relationship                             1.5198298460088 e-16  0.0000000000090e-16   E_h
+hertz-inverse meter relationship                       3.335 640 951... e-9  (exact)               m^-1
+hertz-joule relationship                               6.626 070 040 e-34    0.000 000 081 e-34    J
+hertz-kelvin relationship                              4.799 2447 e-11       0.000 0028 e-11       K
+hertz-kilogram relationship                            7.372 497 201 e-51    0.000 000 091 e-51    kg
+inverse fine-structure constant                        137.035 999 139       0.000 000 031
+inverse meter-atomic mass unit relationship            1.331 025 049 00 e-15 0.000 000 000 61 e-15 u
+inverse meter-electron volt relationship               1.239 841 9739 e-6    0.000 000 0076 e-6    eV
+inverse meter-hartree relationship                     4.556 335 252 767 e-8 0.000 000 000 027 e-8 E_h
+inverse meter-hertz relationship                       299 792 458           (exact)               Hz
+inverse meter-joule relationship                       1.986 445 824 e-25    0.000 000 024 e-25    J
+inverse meter-kelvin relationship                      1.438 777 36 e-2      0.000 000 83 e-2      K
+inverse meter-kilogram relationship                    2.210 219 057 e-42    0.000 000 027 e-42    kg
+inverse of conductance quantum                         12 906.403 7278       0.000 0029            ohm
+Josephson constant                                     483 597.8525 e9       0.0030 e9             Hz V^-1
+joule-atomic mass unit relationship                    6.700 535 363 e9      0.000 000 082 e9      u
+joule-electron volt relationship                       6.241 509 126 e18     0.000 000 038 e18     eV
+joule-hartree relationship                             2.293 712 317 e17     0.000 000 028 e17     E_h
+joule-hertz relationship                               1.509 190 205 e33     0.000 000 019 e33     Hz
+joule-inverse meter relationship                       5.034 116 651 e24     0.000 000 062 e24     m^-1
+joule-kelvin relationship                              7.242 9731 e22        0.000 0042 e22        K
+joule-kilogram relationship                            1.112 650 056... e-17 (exact)               kg
+kelvin-atomic mass unit relationship                   9.251 0842 e-14       0.000 0053 e-14       u
+kelvin-electron volt relationship                      8.617 3303 e-5        0.000 0050 e-5        eV
+kelvin-hartree relationship                            3.166 8105 e-6        0.000 0018 e-6        E_h
+kelvin-hertz relationship                              2.083 6612 e10        0.000 0012 e10        Hz
+kelvin-inverse meter relationship                      69.503 457            0.000 040             m^-1
+kelvin-joule relationship                              1.380 648 52 e-23     0.000 000 79 e-23     J
+kelvin-kilogram relationship                           1.536 178 65 e-40     0.000 000 88 e-40     kg
+kilogram-atomic mass unit relationship                 6.022 140 857 e26     0.000 000 074 e26     u
+kilogram-electron volt relationship                    5.609 588 650 e35     0.000 000 034 e35     eV
+kilogram-hartree relationship                          2.061 485 823 e34     0.000 000 025 e34     E_h
+kilogram-hertz relationship                            1.356 392 512 e50     0.000 000 017 e50     Hz
+kilogram-inverse meter relationship                    4.524 438 411 e41     0.000 000 056 e41     m^-1
+kilogram-joule relationship                            8.987 551 787... e16  (exact)               J
+kilogram-kelvin relationship                           6.509 6595 e39        0.000 0037 e39        K
+lattice parameter of silicon                           543.102 0504 e-12     0.000 0089 e-12       m
+Loschmidt constant (273.15 K, 100 kPa)                 2.651 6467 e25        0.000 0015 e25        m^-3
+Loschmidt constant (273.15 K, 101.325 kPa)             2.686 7811 e25        0.000 0015 e25        m^-3
+mag. constant                                          12.566 370 614... e-7 (exact)               N A^-2
+mag. flux quantum                                      2.067 833 831 e-15    0.000 000 013 e-15    Wb
+molar gas constant                                     8.314 4598            0.000 0048            J mol^-1 K^-1
+molar mass constant                                    1 e-3                 (exact)               kg mol^-1
+molar mass of carbon-12                                12 e-3                (exact)               kg mol^-1
+molar Planck constant                                  3.990 312 7110 e-10   0.000 000 0018 e-10   J s mol^-1
+molar Planck constant times c                          0.119 626 565 582     0.000 000 000 054     J m mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)          22.710 947 e-3        0.000 013 e-3         m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)      22.413 962 e-3        0.000 013 e-3         m^3 mol^-1
+molar volume of silicon                                12.058 832 14 e-6     0.000 000 61 e-6      m^3 mol^-1
+Mo x unit                                              1.002 099 52 e-13     0.000 000 53 e-13     m
+muon Compton wavelength                                11.734 441 11 e-15    0.000 000 26 e-15     m
+muon Compton wavelength over 2 pi                      1.867 594 308 e-15    0.000 000 042 e-15    m
+muon-electron mass ratio                               206.768 2826          0.000 0046
+muon g factor                                          -2.002 331 8418       0.000 000 0013
+muon mag. mom.                                         -4.490 448 26 e-26    0.000 000 10 e-26     J T^-1
+muon mag. mom. anomaly                                 1.165 920 89 e-3      0.000 000 63 e-3
+muon mag. mom. to Bohr magneton ratio                  -4.841 970 48 e-3     0.000 000 11 e-3
+muon mag. mom. to nuclear magneton ratio               -8.890 597 05         0.000 000 20
+muon mass                                              1.883 531 594 e-28    0.000 000 048 e-28    kg
+muon mass energy equivalent                            1.692 833 774 e-11    0.000 000 043 e-11    J
+muon mass energy equivalent in MeV                     105.658 3745          0.000 0024            MeV
+muon mass in u                                         0.113 428 9257        0.000 000 0025        u
+muon molar mass                                        0.113 428 9257 e-3    0.000 000 0025 e-3    kg mol^-1
+muon-neutron mass ratio                                0.112 454 5167        0.000 000 0025
+muon-proton mag. mom. ratio                            -3.183 345 142        0.000 000 071
+muon-proton mass ratio                                 0.112 609 5262        0.000 000 0025
+muon-tau mass ratio                                    5.946 49 e-2          0.000 54 e-2
+natural unit of action                                 1.054 571 800 e-34    0.000 000 013 e-34    J s
+natural unit of action in eV s                         6.582 119 514 e-16    0.000 000 040 e-16    eV s
+natural unit of energy                                 8.187 105 65 e-14     0.000 000 10 e-14     J
+natural unit of energy in MeV                          0.510 998 9461        0.000 000 0031        MeV
+natural unit of length                                 386.159 267 64 e-15   0.000 000 18 e-15     m
+natural unit of mass                                   9.109 383 56 e-31     0.000 000 11 e-31     kg
+natural unit of mom.um                                 2.730 924 488 e-22    0.000 000 034 e-22    kg m s^-1
+natural unit of mom.um in MeV/c                        0.510 998 9461        0.000 000 0031        MeV/c
+natural unit of time                                   1.288 088 667 12 e-21 0.000 000 000 58 e-21 s
+natural unit of velocity                               299 792 458           (exact)               m s^-1
+neutron Compton wavelength                             1.319 590 904 81 e-15 0.000 000 000 88 e-15 m
+neutron Compton wavelength over 2 pi                   0.210 019 415 36 e-15 0.000 000 000 14 e-15 m
+neutron-electron mag. mom. ratio                       1.040 668 82 e-3      0.000 000 25 e-3
+neutron-electron mass ratio                            1838.683 661 58       0.000 000 90
+neutron g factor                                       -3.826 085 45         0.000 000 90
+neutron gyromag. ratio                                 1.832 471 72 e8       0.000 000 43 e8       s^-1 T^-1
+neutron gyromag. ratio over 2 pi                       29.164 6933           0.000 0069            MHz T^-1
+neutron mag. mom.                                      -0.966 236 50 e-26    0.000 000 23 e-26     J T^-1
+neutron mag. mom. to Bohr magneton ratio               -1.041 875 63 e-3     0.000 000 25 e-3
+neutron mag. mom. to nuclear magneton ratio            -1.913 042 73         0.000 000 45
+neutron mass                                           1.674 927 471 e-27    0.000 000 021 e-27    kg
+neutron mass energy equivalent                         1.505 349 739 e-10    0.000 000 019 e-10    J
+neutron mass energy equivalent in MeV                  939.565 4133          0.000 0058            MeV
+neutron mass in u                                      1.008 664 915 88      0.000 000 000 49      u
+neutron molar mass                                     1.008 664 915 88 e-3  0.000 000 000 49 e-3  kg mol^-1
+neutron-muon mass ratio                                8.892 484 08          0.000 000 20
+neutron-proton mag. mom. ratio                         -0.684 979 34         0.000 000 16
+neutron-proton mass difference                         2.305 573 77 e-30     0.000 000 85 e-30
+neutron-proton mass difference energy equivalent       2.072 146 37 e-13     0.000 000 76 e-13
+neutron-proton mass difference energy equivalent in MeV 1.293 332 05         0.000 000 48
+neutron-proton mass difference in u                    0.001 388 449 00      0.000 000 000 51
+neutron-proton mass ratio                              1.001 378 418 98      0.000 000 000 51
+neutron-tau mass ratio                                 0.528 790             0.000 048
+neutron to shielded proton mag. mom. ratio             -0.684 996 94         0.000 000 16
+Newtonian constant of gravitation                      6.674 08 e-11         0.000 31 e-11         m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c         6.708 61 e-39         0.000 31 e-39         (GeV/c^2)^-2
+nuclear magneton                                       5.050 783 699 e-27    0.000 000 031 e-27    J T^-1
+nuclear magneton in eV/T                               3.152 451 2550 e-8    0.000 000 0015 e-8    eV T^-1
+nuclear magneton in inverse meters per tesla           2.542 623 432 e-2     0.000 000 016 e-2     m^-1 T^-1
+nuclear magneton in K/T                                3.658 2690 e-4        0.000 0021 e-4        K T^-1
+nuclear magneton in MHz/T                              7.622 593 285         0.000 000 047         MHz T^-1
+Planck constant                                        6.626 070 040 e-34    0.000 000 081 e-34    J s
+Planck constant in eV s                                4.135 667 662 e-15    0.000 000 025 e-15    eV s
+Planck constant over 2 pi                              1.054 571 800 e-34    0.000 000 013 e-34    J s
+Planck constant over 2 pi in eV s                      6.582 119 514 e-16    0.000 000 040 e-16    eV s
+Planck constant over 2 pi times c in MeV fm            197.326 9788          0.000 0012            MeV fm
+Planck length                                          1.616 229 e-35        0.000 038 e-35        m
+Planck mass                                            2.176 470 e-8         0.000 051 e-8         kg
+Planck mass energy equivalent in GeV                   1.220 910 e19         0.000 029 e19         GeV
+Planck temperature                                     1.416 808 e32         0.000 033 e32         K
+Planck time                                            5.391 16 e-44         0.000 13 e-44         s
+proton charge to mass quotient                         9.578 833 226 e7      0.000 000 059 e7      C kg^-1
+proton Compton wavelength                              1.321 409 853 96 e-15 0.000 000 000 61 e-15 m
+proton Compton wavelength over 2 pi                    0.210 308910109e-15   0.000 000 000097e-15  m
+proton-electron mass ratio                             1836.152 673 89       0.000 000 17
+proton g factor                                        5.585 694 702         0.000 000 017
+proton gyromag. ratio                                  2.675 221 900 e8      0.000 000 018 e8      s^-1 T^-1
+proton gyromag. ratio over 2 pi                        42.577 478 92         0.000 000 29          MHz T^-1
+proton mag. mom.                                       1.410 606 7873 e-26   0.000 000 0097 e-26   J T^-1
+proton mag. mom. to Bohr magneton ratio                1.521 032 2053 e-3    0.000 000 0046 e-3
+proton mag. mom. to nuclear magneton ratio             2.792 847 3508        0.000 000 0085
+proton mag. shielding correction                       25.691 e-6            0.011 e-6
+proton mass                                            1.672 621 898 e-27    0.000 000 021 e-27    kg
+proton mass energy equivalent                          1.503 277 593 e-10    0.000 000 018 e-10    J
+proton mass energy equivalent in MeV                   938.272 0813          0.000 0058            MeV
+proton mass in u                                       1.007 276 466 879     0.000 000 000 091     u
+proton molar mass                                      1.007 276 466 879 e-3 0.000 000 000 091 e-3 kg mol^-1
+proton-muon mass ratio                                 8.880 243 38          0.000 000 20
+proton-neutron mag. mom. ratio                         -1.459 898 05         0.000 000 34
+proton-neutron mass ratio                              0.998 623 478 44      0.000 000 000 51
+proton rms charge radius                               0.8751 e-15           0.0061 e-15           m
+proton-tau mass ratio                                  0.528 063             0.000 048
+quantum of circulation                                 3.636 947 5486 e-4    0.000 000 0017 e-4    m^2 s^-1
+quantum of circulation times 2                         7.273 895 0972 e-4    0.000 000 0033 e-4    m^2 s^-1
+Rydberg constant                                       10 973 731.568 508    0.000 065             m^-1
+Rydberg constant times c in Hz                         3.289 841 960 355 e15 0.000 000 000 019 e15 Hz
+Rydberg constant times hc in eV                        13.605 693 009        0.000 000 084         eV
+Rydberg constant times hc in J                         2.179 872 325 e-18    0.000 000 027 e-18    J
+Sackur-Tetrode constant (1 K, 100 kPa)                 -1.151 7084           0.000 0014
+Sackur-Tetrode constant (1 K, 101.325 kPa)             -1.164 8714           0.000 0014
+second radiation constant                              1.438 777 36 e-2      0.000 000 83 e-2      m K
+shielded helion gyromag. ratio                         2.037 894 585 e8      0.000 000 027 e8      s^-1 T^-1
+shielded helion gyromag. ratio over 2 pi               32.434 099 66         0.000 000 43          MHz T^-1
+shielded helion mag. mom.                              -1.074 553 080 e-26   0.000 000 014 e-26    J T^-1
+shielded helion mag. mom. to Bohr magneton ratio       -1.158 671 471 e-3    0.000 000 014 e-3
+shielded helion mag. mom. to nuclear magneton ratio    -2.127 497 720        0.000 000 025
+shielded helion to proton mag. mom. ratio              -0.761 766 5603       0.000 000 0092
+shielded helion to shielded proton mag. mom. ratio     -0.761 786 1313       0.000 000 0033
+shielded proton gyromag. ratio                         2.675 153 171 e8      0.000 000 033 e8      s^-1 T^-1
+shielded proton gyromag. ratio over 2 pi               42.576 385 07         0.000 000 53          MHz T^-1
+shielded proton mag. mom.                              1.410 570 547 e-26    0.000 000 018 e-26    J T^-1
+shielded proton mag. mom. to Bohr magneton ratio       1.520 993 128 e-3     0.000 000 017 e-3
+shielded proton mag. mom. to nuclear magneton ratio    2.792 775 600         0.000 000 030
+speed of light in vacuum                               299 792 458           (exact)               m s^-1
+standard acceleration of gravity                       9.806 65              (exact)               m s^-2
+standard atmosphere                                    101 325               (exact)               Pa
+standard-state pressure                                100 000               (exact)               Pa
+Stefan-Boltzmann constant                              5.670 367 e-8         0.000 013 e-8         W m^-2 K^-4
+tau Compton wavelength                                 0.697 787 e-15        0.000 063 e-15        m
+tau Compton wavelength over 2 pi                       0.111 056 e-15        0.000 010 e-15        m
+tau-electron mass ratio                                3477.15               0.31
+tau mass                                               3.167 47 e-27         0.000 29 e-27         kg
+tau mass energy equivalent                             2.846 78 e-10         0.000 26 e-10         J
+tau mass energy equivalent in MeV                      1776.82               0.16                  MeV
+tau mass in u                                          1.907 49              0.000 17              u
+tau molar mass                                         1.907 49 e-3          0.000 17 e-3          kg mol^-1
+tau-muon mass ratio                                    16.8167               0.0015
+tau-neutron mass ratio                                 1.891 11              0.000 17
+tau-proton mass ratio                                  1.893 72              0.000 17
+Thomson cross section                                  0.665 245 871 58 e-28 0.000 000 000 91 e-28 m^2
+triton-electron mass ratio                             5496.921 535 88       0.000 000 26
+triton g factor                                        5.957 924 920         0.000 000 028
+triton mag. mom.                                       1.504 609 503 e-26    0.000 000 012 e-26    J T^-1
+triton mag. mom. to Bohr magneton ratio                1.622 393 6616 e-3    0.000 000 0076 e-3
+triton mag. mom. to nuclear magneton ratio             2.978 962 460         0.000 000 014
+triton mass                                            5.007 356 665 e-27    0.000 000 062 e-27    kg
+triton mass energy equivalent                          4.500 387 735 e-10    0.000 000 055 e-10    J
+triton mass energy equivalent in MeV                   2808.921 112          0.000 017             MeV
+triton mass in u                                       3.015 500 716 32      0.000 000 000 11      u
+triton molar mass                                      3.015 500 716 32 e-3  0.000 000 000 11 e-3  kg mol^-1
+triton-proton mass ratio                               2.993 717 033 48      0.000 000 000 22
+unified atomic mass unit                               1.660 539 040 e-27    0.000 000 020 e-27    kg
+von Klitzing constant                                  25 812.807 4555       0.000 0059            ohm
+weak mixing angle                                      0.2223                0.0021
+Wien frequency displacement law constant               5.878 9238 e10        0.000 0034 e10        Hz K^-1
+Wien wavelength displacement law constant              2.897 7729 e-3        0.000 0017 e-3        m K"""
+
+
+exact2014 = exact2010
+
+
+txt2018 = """\
+alpha particle-electron mass ratio                          7294.299 541 42          0.000 000 24
+alpha particle mass                                         6.644 657 3357 e-27      0.000 000 0020 e-27      kg
+alpha particle mass energy equivalent                       5.971 920 1914 e-10      0.000 000 0018 e-10      J
+alpha particle mass energy equivalent in MeV                3727.379 4066            0.000 0011               MeV
+alpha particle mass in u                                    4.001 506 179 127        0.000 000 000 063        u
+alpha particle molar mass                                   4.001 506 1777 e-3       0.000 000 0012 e-3       kg mol^-1
+alpha particle-proton mass ratio                            3.972 599 690 09         0.000 000 000 22
+alpha particle relative atomic mass                         4.001 506 179 127        0.000 000 000 063
+Angstrom star                                               1.000 014 95 e-10        0.000 000 90 e-10        m
+atomic mass constant                                        1.660 539 066 60 e-27    0.000 000 000 50 e-27    kg
+atomic mass constant energy equivalent                      1.492 418 085 60 e-10    0.000 000 000 45 e-10    J
+atomic mass constant energy equivalent in MeV               931.494 102 42           0.000 000 28             MeV
+atomic mass unit-electron volt relationship                 9.314 941 0242 e8        0.000 000 0028 e8        eV
+atomic mass unit-hartree relationship                       3.423 177 6874 e7        0.000 000 0010 e7        E_h
+atomic mass unit-hertz relationship                         2.252 342 718 71 e23     0.000 000 000 68 e23     Hz
+atomic mass unit-inverse meter relationship                 7.513 006 6104 e14       0.000 000 0023 e14       m^-1
+atomic mass unit-joule relationship                         1.492 418 085 60 e-10    0.000 000 000 45 e-10    J
+atomic mass unit-kelvin relationship                        1.080 954 019 16 e13     0.000 000 000 33 e13     K
+atomic mass unit-kilogram relationship                      1.660 539 066 60 e-27    0.000 000 000 50 e-27    kg
+atomic unit of 1st hyperpolarizability                      3.206 361 3061 e-53      0.000 000 0015 e-53      C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                      6.235 379 9905 e-65      0.000 000 0038 e-65      C^4 m^4 J^-3
+atomic unit of action                                       1.054 571 817... e-34    (exact)                  J s
+atomic unit of charge                                       1.602 176 634 e-19       (exact)                  C
+atomic unit of charge density                               1.081 202 384 57 e12     0.000 000 000 49 e12     C m^-3
+atomic unit of current                                      6.623 618 237 510 e-3    0.000 000 000 013 e-3    A
+atomic unit of electric dipole mom.                         8.478 353 6255 e-30      0.000 000 0013 e-30      C m
+atomic unit of electric field                               5.142 206 747 63 e11     0.000 000 000 78 e11     V m^-1
+atomic unit of electric field gradient                      9.717 362 4292 e21       0.000 000 0029 e21       V m^-2
+atomic unit of electric polarizability                      1.648 777 274 36 e-41    0.000 000 000 50 e-41    C^2 m^2 J^-1
+atomic unit of electric potential                           27.211 386 245 988       0.000 000 000 053        V
+atomic unit of electric quadrupole mom.                     4.486 551 5246 e-40      0.000 000 0014 e-40      C m^2
+atomic unit of energy                                       4.359 744 722 2071 e-18  0.000 000 000 0085 e-18  J
+atomic unit of force                                        8.238 723 4983 e-8       0.000 000 0012 e-8       N
+atomic unit of length                                       5.291 772 109 03 e-11    0.000 000 000 80 e-11    m
+atomic unit of mag. dipole mom.                             1.854 802 015 66 e-23    0.000 000 000 56 e-23    J T^-1
+atomic unit of mag. flux density                            2.350 517 567 58 e5      0.000 000 000 71 e5      T
+atomic unit of magnetizability                              7.891 036 6008 e-29      0.000 000 0048 e-29      J T^-2
+atomic unit of mass                                         9.109 383 7015 e-31      0.000 000 0028 e-31      kg
+atomic unit of momentum                                     1.992 851 914 10 e-24    0.000 000 000 30 e-24    kg m s^-1
+atomic unit of permittivity                                 1.112 650 055 45 e-10    0.000 000 000 17 e-10    F m^-1
+atomic unit of time                                         2.418 884 326 5857 e-17  0.000 000 000 0047 e-17  s
+atomic unit of velocity                                     2.187 691 263 64 e6      0.000 000 000 33 e6      m s^-1
+Avogadro constant                                           6.022 140 76 e23         (exact)                  mol^-1
+Bohr magneton                                               9.274 010 0783 e-24      0.000 000 0028 e-24      J T^-1
+Bohr magneton in eV/T                                       5.788 381 8060 e-5       0.000 000 0017 e-5       eV T^-1
+Bohr magneton in Hz/T                                       1.399 624 493 61 e10     0.000 000 000 42 e10     Hz T^-1
+Bohr magneton in inverse meter per tesla                    46.686 447 783           0.000 000 014            m^-1 T^-1
+Bohr magneton in K/T                                        0.671 713 815 63         0.000 000 000 20         K T^-1
+Bohr radius                                                 5.291 772 109 03 e-11    0.000 000 000 80 e-11    m
+Boltzmann constant                                          1.380 649 e-23           (exact)                  J K^-1
+Boltzmann constant in eV/K                                  8.617 333 262... e-5     (exact)                  eV K^-1
+Boltzmann constant in Hz/K                                  2.083 661 912... e10     (exact)                  Hz K^-1
+Boltzmann constant in inverse meter per kelvin              69.503 480 04...         (exact)                  m^-1 K^-1
+characteristic impedance of vacuum                          376.730 313 668          0.000 000 057            ohm
+classical electron radius                                   2.817 940 3262 e-15      0.000 000 0013 e-15      m
+Compton wavelength                                          2.426 310 238 67 e-12    0.000 000 000 73 e-12    m
+conductance quantum                                         7.748 091 729... e-5     (exact)                  S
+conventional value of ampere-90                             1.000 000 088 87...      (exact)                  A
+conventional value of coulomb-90                            1.000 000 088 87...      (exact)                  C
+conventional value of farad-90                              0.999 999 982 20...      (exact)                  F
+conventional value of henry-90                              1.000 000 017 79...      (exact)                  H
+conventional value of Josephson constant                    483 597.9 e9             (exact)                  Hz V^-1
+conventional value of ohm-90                                1.000 000 017 79...      (exact)                  ohm
+conventional value of volt-90                               1.000 000 106 66...      (exact)                  V
+conventional value of von Klitzing constant                 25 812.807               (exact)                  ohm
+conventional value of watt-90                               1.000 000 195 53...      (exact)                  W
+Cu x unit                                                   1.002 076 97 e-13        0.000 000 28 e-13        m
+deuteron-electron mag. mom. ratio                           -4.664 345 551 e-4       0.000 000 012 e-4
+deuteron-electron mass ratio                                3670.482 967 88          0.000 000 13
+deuteron g factor                                           0.857 438 2338           0.000 000 0022
+deuteron mag. mom.                                          4.330 735 094 e-27       0.000 000 011 e-27       J T^-1
+deuteron mag. mom. to Bohr magneton ratio                   4.669 754 570 e-4        0.000 000 012 e-4
+deuteron mag. mom. to nuclear magneton ratio                0.857 438 2338           0.000 000 0022
+deuteron mass                                               3.343 583 7724 e-27      0.000 000 0010 e-27      kg
+deuteron mass energy equivalent                             3.005 063 231 02 e-10    0.000 000 000 91 e-10    J
+deuteron mass energy equivalent in MeV                      1875.612 942 57          0.000 000 57             MeV
+deuteron mass in u                                          2.013 553 212 745        0.000 000 000 040        u
+deuteron molar mass                                         2.013 553 212 05 e-3     0.000 000 000 61 e-3     kg mol^-1
+deuteron-neutron mag. mom. ratio                            -0.448 206 53            0.000 000 11
+deuteron-proton mag. mom. ratio                             0.307 012 209 39         0.000 000 000 79
+deuteron-proton mass ratio                                  1.999 007 501 39         0.000 000 000 11
+deuteron relative atomic mass                               2.013 553 212 745        0.000 000 000 040
+deuteron rms charge radius                                  2.127 99 e-15            0.000 74 e-15            m
+electron charge to mass quotient                            -1.758 820 010 76 e11    0.000 000 000 53 e11     C kg^-1
+electron-deuteron mag. mom. ratio                           -2143.923 4915           0.000 0056
+electron-deuteron mass ratio                                2.724 437 107 462 e-4    0.000 000 000 096 e-4
+electron g factor                                           -2.002 319 304 362 56    0.000 000 000 000 35
+electron gyromag. ratio                                     1.760 859 630 23 e11     0.000 000 000 53 e11     s^-1 T^-1
+electron gyromag. ratio in MHz/T                            28 024.951 4242          0.000 0085               MHz T^-1
+electron-helion mass ratio                                  1.819 543 074 573 e-4    0.000 000 000 079 e-4
+electron mag. mom.                                          -9.284 764 7043 e-24     0.000 000 0028 e-24      J T^-1
+electron mag. mom. anomaly                                  1.159 652 181 28 e-3     0.000 000 000 18 e-3
+electron mag. mom. to Bohr magneton ratio                   -1.001 159 652 181 28    0.000 000 000 000 18
+electron mag. mom. to nuclear magneton ratio                -1838.281 971 88         0.000 000 11
+electron mass                                               9.109 383 7015 e-31      0.000 000 0028 e-31      kg
+electron mass energy equivalent                             8.187 105 7769 e-14      0.000 000 0025 e-14      J
+electron mass energy equivalent in MeV                      0.510 998 950 00         0.000 000 000 15         MeV
+electron mass in u                                          5.485 799 090 65 e-4     0.000 000 000 16 e-4     u
+electron molar mass                                         5.485 799 0888 e-7       0.000 000 0017 e-7       kg mol^-1
+electron-muon mag. mom. ratio                               206.766 9883             0.000 0046
+electron-muon mass ratio                                    4.836 331 69 e-3         0.000 000 11 e-3
+electron-neutron mag. mom. ratio                            960.920 50               0.000 23
+electron-neutron mass ratio                                 5.438 673 4424 e-4       0.000 000 0026 e-4
+electron-proton mag. mom. ratio                             -658.210 687 89          0.000 000 20
+electron-proton mass ratio                                  5.446 170 214 87 e-4     0.000 000 000 33 e-4
+electron relative atomic mass                               5.485 799 090 65 e-4     0.000 000 000 16 e-4
+electron-tau mass ratio                                     2.875 85 e-4             0.000 19 e-4
+electron to alpha particle mass ratio                       1.370 933 554 787 e-4    0.000 000 000 045 e-4
+electron to shielded helion mag. mom. ratio                 864.058 257              0.000 010
+electron to shielded proton mag. mom. ratio                 -658.227 5971            0.000 0072
+electron-triton mass ratio                                  1.819 200 062 251 e-4    0.000 000 000 090 e-4
+electron volt                                               1.602 176 634 e-19       (exact)                  J
+electron volt-atomic mass unit relationship                 1.073 544 102 33 e-9     0.000 000 000 32 e-9     u
+electron volt-hartree relationship                          3.674 932 217 5655 e-2   0.000 000 000 0071 e-2   E_h
+electron volt-hertz relationship                            2.417 989 242... e14     (exact)                  Hz
+electron volt-inverse meter relationship                    8.065 543 937... e5      (exact)                  m^-1
+electron volt-joule relationship                            1.602 176 634 e-19       (exact)                  J
+electron volt-kelvin relationship                           1.160 451 812... e4      (exact)                  K
+electron volt-kilogram relationship                         1.782 661 921... e-36    (exact)                  kg
+elementary charge                                           1.602 176 634 e-19       (exact)                  C
+elementary charge over h-bar                                1.519 267 447... e15     (exact)                  A J^-1
+Faraday constant                                            96 485.332 12...         (exact)                  C mol^-1
+Fermi coupling constant                                     1.166 3787 e-5           0.000 0006 e-5           GeV^-2
+fine-structure constant                                     7.297 352 5693 e-3       0.000 000 0011 e-3
+first radiation constant                                    3.741 771 852... e-16    (exact)                  W m^2
+first radiation constant for spectral radiance              1.191 042 972... e-16    (exact)                  W m^2 sr^-1
+hartree-atomic mass unit relationship                       2.921 262 322 05 e-8     0.000 000 000 88 e-8     u
+hartree-electron volt relationship                          27.211 386 245 988       0.000 000 000 053        eV
+Hartree energy                                              4.359 744 722 2071 e-18  0.000 000 000 0085 e-18  J
+Hartree energy in eV                                        27.211 386 245 988       0.000 000 000 053        eV
+hartree-hertz relationship                                  6.579 683 920 502 e15    0.000 000 000 013 e15    Hz
+hartree-inverse meter relationship                          2.194 746 313 6320 e7    0.000 000 000 0043 e7    m^-1
+hartree-joule relationship                                  4.359 744 722 2071 e-18  0.000 000 000 0085 e-18  J
+hartree-kelvin relationship                                 3.157 750 248 0407 e5    0.000 000 000 0061 e5    K
+hartree-kilogram relationship                               4.850 870 209 5432 e-35  0.000 000 000 0094 e-35  kg
+helion-electron mass ratio                                  5495.885 280 07          0.000 000 24
+helion g factor                                             -4.255 250 615           0.000 000 050
+helion mag. mom.                                            -1.074 617 532 e-26      0.000 000 013 e-26       J T^-1
+helion mag. mom. to Bohr magneton ratio                     -1.158 740 958 e-3       0.000 000 014 e-3
+helion mag. mom. to nuclear magneton ratio                  -2.127 625 307           0.000 000 025
+helion mass                                                 5.006 412 7796 e-27      0.000 000 0015 e-27      kg
+helion mass energy equivalent                               4.499 539 4125 e-10      0.000 000 0014 e-10      J
+helion mass energy equivalent in MeV                        2808.391 607 43          0.000 000 85             MeV
+helion mass in u                                            3.014 932 247 175        0.000 000 000 097        u
+helion molar mass                                           3.014 932 246 13 e-3     0.000 000 000 91 e-3     kg mol^-1
+helion-proton mass ratio                                    2.993 152 671 67         0.000 000 000 13
+helion relative atomic mass                                 3.014 932 247 175        0.000 000 000 097
+helion shielding shift                                      5.996 743 e-5            0.000 010 e-5
+hertz-atomic mass unit relationship                         4.439 821 6652 e-24      0.000 000 0013 e-24      u
+hertz-electron volt relationship                            4.135 667 696... e-15    (exact)                  eV
+hertz-hartree relationship                                  1.519 829 846 0570 e-16  0.000 000 000 0029 e-16  E_h
+hertz-inverse meter relationship                            3.335 640 951... e-9     (exact)                  m^-1
+hertz-joule relationship                                    6.626 070 15 e-34        (exact)                  J
+hertz-kelvin relationship                                   4.799 243 073... e-11    (exact)                  K
+hertz-kilogram relationship                                 7.372 497 323... e-51    (exact)                  kg
+hyperfine transition frequency of Cs-133                    9 192 631 770            (exact)                  Hz
+inverse fine-structure constant                             137.035 999 084          0.000 000 021
+inverse meter-atomic mass unit relationship                 1.331 025 050 10 e-15    0.000 000 000 40 e-15    u
+inverse meter-electron volt relationship                    1.239 841 984... e-6     (exact)                  eV
+inverse meter-hartree relationship                          4.556 335 252 9120 e-8   0.000 000 000 0088 e-8   E_h
+inverse meter-hertz relationship                            299 792 458              (exact)                  Hz
+inverse meter-joule relationship                            1.986 445 857... e-25    (exact)                  J
+inverse meter-kelvin relationship                           1.438 776 877... e-2     (exact)                  K
+inverse meter-kilogram relationship                         2.210 219 094... e-42    (exact)                  kg
+inverse of conductance quantum                              12 906.403 72...         (exact)                  ohm
+Josephson constant                                          483 597.848 4... e9      (exact)                  Hz V^-1
+joule-atomic mass unit relationship                         6.700 535 2565 e9        0.000 000 0020 e9        u
+joule-electron volt relationship                            6.241 509 074... e18     (exact)                  eV
+joule-hartree relationship                                  2.293 712 278 3963 e17   0.000 000 000 0045 e17   E_h
+joule-hertz relationship                                    1.509 190 179... e33     (exact)                  Hz
+joule-inverse meter relationship                            5.034 116 567... e24     (exact)                  m^-1
+joule-kelvin relationship                                   7.242 970 516... e22     (exact)                  K
+joule-kilogram relationship                                 1.112 650 056... e-17    (exact)                  kg
+kelvin-atomic mass unit relationship                        9.251 087 3014 e-14      0.000 000 0028 e-14      u
+kelvin-electron volt relationship                           8.617 333 262... e-5     (exact)                  eV
+kelvin-hartree relationship                                 3.166 811 563 4556 e-6   0.000 000 000 0061 e-6   E_h
+kelvin-hertz relationship                                   2.083 661 912... e10     (exact)                  Hz
+kelvin-inverse meter relationship                           69.503 480 04...         (exact)                  m^-1
+kelvin-joule relationship                                   1.380 649 e-23           (exact)                  J
+kelvin-kilogram relationship                                1.536 179 187... e-40    (exact)                  kg
+kilogram-atomic mass unit relationship                      6.022 140 7621 e26       0.000 000 0018 e26       u
+kilogram-electron volt relationship                         5.609 588 603... e35     (exact)                  eV
+kilogram-hartree relationship                               2.061 485 788 7409 e34   0.000 000 000 0040 e34   E_h
+kilogram-hertz relationship                                 1.356 392 489... e50     (exact)                  Hz
+kilogram-inverse meter relationship                         4.524 438 335... e41     (exact)                  m^-1
+kilogram-joule relationship                                 8.987 551 787... e16     (exact)                  J
+kilogram-kelvin relationship                                6.509 657 260... e39     (exact)                  K
+lattice parameter of silicon                                5.431 020 511 e-10       0.000 000 089 e-10       m
+lattice spacing of ideal Si (220)                           1.920 155 716 e-10       0.000 000 032 e-10       m
+Loschmidt constant (273.15 K, 100 kPa)                      2.651 645 804... e25     (exact)                  m^-3
+Loschmidt constant (273.15 K, 101.325 kPa)                  2.686 780 111... e25     (exact)                  m^-3
+luminous efficacy                                           683                      (exact)                  lm W^-1
+mag. flux quantum                                           2.067 833 848... e-15    (exact)                  Wb
+molar gas constant                                          8.314 462 618...         (exact)                  J mol^-1 K^-1
+molar mass constant                                         0.999 999 999 65 e-3     0.000 000 000 30 e-3     kg mol^-1
+molar mass of carbon-12                                     11.999 999 9958 e-3      0.000 000 0036 e-3       kg mol^-1
+molar Planck constant                                       3.990 312 712... e-10    (exact)                  J Hz^-1 mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)               22.710 954 64... e-3     (exact)                  m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)           22.413 969 54... e-3     (exact)                  m^3 mol^-1
+molar volume of silicon                                     1.205 883 199 e-5        0.000 000 060 e-5        m^3 mol^-1
+Mo x unit                                                   1.002 099 52 e-13        0.000 000 53 e-13        m
+muon Compton wavelength                                     1.173 444 110 e-14       0.000 000 026 e-14       m
+muon-electron mass ratio                                    206.768 2830             0.000 0046
+muon g factor                                               -2.002 331 8418          0.000 000 0013
+muon mag. mom.                                              -4.490 448 30 e-26       0.000 000 10 e-26        J T^-1
+muon mag. mom. anomaly                                      1.165 920 89 e-3         0.000 000 63 e-3
+muon mag. mom. to Bohr magneton ratio                       -4.841 970 47 e-3        0.000 000 11 e-3
+muon mag. mom. to nuclear magneton ratio                    -8.890 597 03            0.000 000 20
+muon mass                                                   1.883 531 627 e-28       0.000 000 042 e-28       kg
+muon mass energy equivalent                                 1.692 833 804 e-11       0.000 000 038 e-11       J
+muon mass energy equivalent in MeV                          105.658 3755             0.000 0023               MeV
+muon mass in u                                              0.113 428 9259           0.000 000 0025           u
+muon molar mass                                             1.134 289 259 e-4        0.000 000 025 e-4        kg mol^-1
+muon-neutron mass ratio                                     0.112 454 5170           0.000 000 0025
+muon-proton mag. mom. ratio                                 -3.183 345 142           0.000 000 071
+muon-proton mass ratio                                      0.112 609 5264           0.000 000 0025
+muon-tau mass ratio                                         5.946 35 e-2             0.000 40 e-2
+natural unit of action                                      1.054 571 817... e-34    (exact)                  J s
+natural unit of action in eV s                              6.582 119 569... e-16    (exact)                  eV s
+natural unit of energy                                      8.187 105 7769 e-14      0.000 000 0025 e-14      J
+natural unit of energy in MeV                               0.510 998 950 00         0.000 000 000 15         MeV
+natural unit of length                                      3.861 592 6796 e-13      0.000 000 0012 e-13      m
+natural unit of mass                                        9.109 383 7015 e-31      0.000 000 0028 e-31      kg
+natural unit of momentum                                    2.730 924 530 75 e-22    0.000 000 000 82 e-22    kg m s^-1
+natural unit of momentum in MeV/c                           0.510 998 950 00         0.000 000 000 15         MeV/c
+natural unit of time                                        1.288 088 668 19 e-21    0.000 000 000 39 e-21    s
+natural unit of velocity                                    299 792 458              (exact)                  m s^-1
+neutron Compton wavelength                                  1.319 590 905 81 e-15    0.000 000 000 75 e-15    m
+neutron-electron mag. mom. ratio                            1.040 668 82 e-3         0.000 000 25 e-3
+neutron-electron mass ratio                                 1838.683 661 73          0.000 000 89
+neutron g factor                                            -3.826 085 45            0.000 000 90
+neutron gyromag. ratio                                      1.832 471 71 e8          0.000 000 43 e8          s^-1 T^-1
+neutron gyromag. ratio in MHz/T                             29.164 6931              0.000 0069               MHz T^-1
+neutron mag. mom.                                           -9.662 3651 e-27         0.000 0023 e-27          J T^-1
+neutron mag. mom. to Bohr magneton ratio                    -1.041 875 63 e-3        0.000 000 25 e-3
+neutron mag. mom. to nuclear magneton ratio                 -1.913 042 73            0.000 000 45
+neutron mass                                                1.674 927 498 04 e-27    0.000 000 000 95 e-27    kg
+neutron mass energy equivalent                              1.505 349 762 87 e-10    0.000 000 000 86 e-10    J
+neutron mass energy equivalent in MeV                       939.565 420 52           0.000 000 54             MeV
+neutron mass in u                                           1.008 664 915 95         0.000 000 000 49         u
+neutron molar mass                                          1.008 664 915 60 e-3     0.000 000 000 57 e-3     kg mol^-1
+neutron-muon mass ratio                                     8.892 484 06             0.000 000 20
+neutron-proton mag. mom. ratio                              -0.684 979 34            0.000 000 16
+neutron-proton mass difference                              2.305 574 35 e-30        0.000 000 82 e-30        kg
+neutron-proton mass difference energy equivalent            2.072 146 89 e-13        0.000 000 74 e-13        J
+neutron-proton mass difference energy equivalent in MeV     1.293 332 36             0.000 000 46             MeV
+neutron-proton mass difference in u                         1.388 449 33 e-3         0.000 000 49 e-3         u
+neutron-proton mass ratio                                   1.001 378 419 31         0.000 000 000 49
+neutron relative atomic mass                                1.008 664 915 95         0.000 000 000 49
+neutron-tau mass ratio                                      0.528 779                0.000 036
+neutron to shielded proton mag. mom. ratio                  -0.684 996 94            0.000 000 16
+Newtonian constant of gravitation                           6.674 30 e-11            0.000 15 e-11            m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c              6.708 83 e-39            0.000 15 e-39            (GeV/c^2)^-2
+nuclear magneton                                            5.050 783 7461 e-27      0.000 000 0015 e-27      J T^-1
+nuclear magneton in eV/T                                    3.152 451 258 44 e-8     0.000 000 000 96 e-8     eV T^-1
+nuclear magneton in inverse meter per tesla                 2.542 623 413 53 e-2     0.000 000 000 78 e-2     m^-1 T^-1
+nuclear magneton in K/T                                     3.658 267 7756 e-4       0.000 000 0011 e-4       K T^-1
+nuclear magneton in MHz/T                                   7.622 593 2291           0.000 000 0023           MHz T^-1
+Planck constant                                             6.626 070 15 e-34        (exact)                  J Hz^-1
+Planck constant in eV/Hz                                    4.135 667 696... e-15    (exact)                  eV Hz^-1
+Planck length                                               1.616 255 e-35           0.000 018 e-35           m
+Planck mass                                                 2.176 434 e-8            0.000 024 e-8            kg
+Planck mass energy equivalent in GeV                        1.220 890 e19            0.000 014 e19            GeV
+Planck temperature                                          1.416 784 e32            0.000 016 e32            K
+Planck time                                                 5.391 247 e-44           0.000 060 e-44           s
+proton charge to mass quotient                              9.578 833 1560 e7        0.000 000 0029 e7        C kg^-1
+proton Compton wavelength                                   1.321 409 855 39 e-15    0.000 000 000 40 e-15    m
+proton-electron mass ratio                                  1836.152 673 43          0.000 000 11
+proton g factor                                             5.585 694 6893           0.000 000 0016
+proton gyromag. ratio                                       2.675 221 8744 e8        0.000 000 0011 e8        s^-1 T^-1
+proton gyromag. ratio in MHz/T                              42.577 478 518           0.000 000 018            MHz T^-1
+proton mag. mom.                                            1.410 606 797 36 e-26    0.000 000 000 60 e-26    J T^-1
+proton mag. mom. to Bohr magneton ratio                     1.521 032 202 30 e-3     0.000 000 000 46 e-3
+proton mag. mom. to nuclear magneton ratio                  2.792 847 344 63         0.000 000 000 82
+proton mag. shielding correction                            2.5689 e-5               0.0011 e-5
+proton mass                                                 1.672 621 923 69 e-27    0.000 000 000 51 e-27    kg
+proton mass energy equivalent                               1.503 277 615 98 e-10    0.000 000 000 46 e-10    J
+proton mass energy equivalent in MeV                        938.272 088 16           0.000 000 29             MeV
+proton mass in u                                            1.007 276 466 621        0.000 000 000 053        u
+proton molar mass                                           1.007 276 466 27 e-3     0.000 000 000 31 e-3     kg mol^-1
+proton-muon mass ratio                                      8.880 243 37             0.000 000 20
+proton-neutron mag. mom. ratio                              -1.459 898 05            0.000 000 34
+proton-neutron mass ratio                                   0.998 623 478 12         0.000 000 000 49
+proton relative atomic mass                                 1.007 276 466 621        0.000 000 000 053
+proton rms charge radius                                    8.414 e-16               0.019 e-16               m
+proton-tau mass ratio                                       0.528 051                0.000 036
+quantum of circulation                                      3.636 947 5516 e-4       0.000 000 0011 e-4       m^2 s^-1
+quantum of circulation times 2                              7.273 895 1032 e-4       0.000 000 0022 e-4       m^2 s^-1
+reduced Compton wavelength                                  3.861 592 6796 e-13      0.000 000 0012 e-13      m
+reduced muon Compton wavelength                             1.867 594 306 e-15       0.000 000 042 e-15       m
+reduced neutron Compton wavelength                          2.100 194 1552 e-16      0.000 000 0012 e-16      m
+reduced Planck constant                                     1.054 571 817... e-34    (exact)                  J s
+reduced Planck constant in eV s                             6.582 119 569... e-16    (exact)                  eV s
+reduced Planck constant times c in MeV fm                   197.326 980 4...         (exact)                  MeV fm
+reduced proton Compton wavelength                           2.103 089 103 36 e-16    0.000 000 000 64 e-16    m
+reduced tau Compton wavelength                              1.110 538 e-16           0.000 075 e-16           m
+Rydberg constant                                            10 973 731.568 160       0.000 021                m^-1
+Rydberg constant times c in Hz                              3.289 841 960 2508 e15   0.000 000 000 0064 e15   Hz
+Rydberg constant times hc in eV                             13.605 693 122 994       0.000 000 000 026        eV
+Rydberg constant times hc in J                              2.179 872 361 1035 e-18  0.000 000 000 0042 e-18  J
+Sackur-Tetrode constant (1 K, 100 kPa)                      -1.151 707 537 06        0.000 000 000 45
+Sackur-Tetrode constant (1 K, 101.325 kPa)                  -1.164 870 523 58        0.000 000 000 45
+second radiation constant                                   1.438 776 877... e-2     (exact)                  m K
+shielded helion gyromag. ratio                              2.037 894 569 e8         0.000 000 024 e8         s^-1 T^-1
+shielded helion gyromag. ratio in MHz/T                     32.434 099 42            0.000 000 38             MHz T^-1
+shielded helion mag. mom.                                   -1.074 553 090 e-26      0.000 000 013 e-26       J T^-1
+shielded helion mag. mom. to Bohr magneton ratio            -1.158 671 471 e-3       0.000 000 014 e-3
+shielded helion mag. mom. to nuclear magneton ratio         -2.127 497 719           0.000 000 025
+shielded helion to proton mag. mom. ratio                   -0.761 766 5618          0.000 000 0089
+shielded helion to shielded proton mag. mom. ratio          -0.761 786 1313          0.000 000 0033
+shielded proton gyromag. ratio                              2.675 153 151 e8         0.000 000 029 e8         s^-1 T^-1
+shielded proton gyromag. ratio in MHz/T                     42.576 384 74            0.000 000 46             MHz T^-1
+shielded proton mag. mom.                                   1.410 570 560 e-26       0.000 000 015 e-26       J T^-1
+shielded proton mag. mom. to Bohr magneton ratio            1.520 993 128 e-3        0.000 000 017 e-3
+shielded proton mag. mom. to nuclear magneton ratio         2.792 775 599            0.000 000 030
+shielding difference of d and p in HD                       2.0200 e-8               0.0020 e-8
+shielding difference of t and p in HT                       2.4140 e-8               0.0020 e-8
+speed of light in vacuum                                    299 792 458              (exact)                  m s^-1
+standard acceleration of gravity                            9.806 65                 (exact)                  m s^-2
+standard atmosphere                                         101 325                  (exact)                  Pa
+standard-state pressure                                     100 000                  (exact)                  Pa
+Stefan-Boltzmann constant                                   5.670 374 419... e-8     (exact)                  W m^-2 K^-4
+tau Compton wavelength                                      6.977 71 e-16            0.000 47 e-16            m
+tau-electron mass ratio                                     3477.23                  0.23
+tau energy equivalent                                       1776.86                  0.12                     MeV
+tau mass                                                    3.167 54 e-27            0.000 21 e-27            kg
+tau mass energy equivalent                                  2.846 84 e-10            0.000 19 e-10            J
+tau mass in u                                               1.907 54                 0.000 13                 u
+tau molar mass                                              1.907 54 e-3             0.000 13 e-3             kg mol^-1
+tau-muon mass ratio                                         16.8170                  0.0011
+tau-neutron mass ratio                                      1.891 15                 0.000 13
+tau-proton mass ratio                                       1.893 76                 0.000 13
+Thomson cross section                                       6.652 458 7321 e-29      0.000 000 0060 e-29      m^2
+triton-electron mass ratio                                  5496.921 535 73          0.000 000 27
+triton g factor                                             5.957 924 931            0.000 000 012
+triton mag. mom.                                            1.504 609 5202 e-26      0.000 000 0030 e-26      J T^-1
+triton mag. mom. to Bohr magneton ratio                     1.622 393 6651 e-3       0.000 000 0032 e-3
+triton mag. mom. to nuclear magneton ratio                  2.978 962 4656           0.000 000 0059
+triton mass                                                 5.007 356 7446 e-27      0.000 000 0015 e-27      kg
+triton mass energy equivalent                               4.500 387 8060 e-10      0.000 000 0014 e-10      J
+triton mass energy equivalent in MeV                        2808.921 132 98          0.000 000 85             MeV
+triton mass in u                                            3.015 500 716 21         0.000 000 000 12         u
+triton molar mass                                           3.015 500 715 17 e-3     0.000 000 000 92 e-3     kg mol^-1
+triton-proton mass ratio                                    2.993 717 034 14         0.000 000 000 15
+triton relative atomic mass                                 3.015 500 716 21         0.000 000 000 12
+triton to proton mag. mom. ratio                            1.066 639 9191           0.000 000 0021
+unified atomic mass unit                                    1.660 539 066 60 e-27    0.000 000 000 50 e-27    kg
+vacuum electric permittivity                                8.854 187 8128 e-12      0.000 000 0013 e-12      F m^-1
+vacuum mag. permeability                                    1.256 637 062 12 e-6     0.000 000 000 19 e-6     N A^-2
+von Klitzing constant                                       25 812.807 45...         (exact)                  ohm
+weak mixing angle                                           0.222 90                 0.000 30
+Wien frequency displacement law constant                    5.878 925 757... e10     (exact)                  Hz K^-1
+Wien wavelength displacement law constant                   2.897 771 955... e-3     (exact)                  m K
+W to Z mass ratio                                           0.881 53                 0.000 17                   """
+
+
+def exact2018(exact):
+    # SI base constants
+    c = exact['speed of light in vacuum']
+    h = exact['Planck constant']
+    e = exact['elementary charge']
+    k = exact['Boltzmann constant']
+    N_A = exact['Avogadro constant']
+
+    # Other useful constants
+    R = N_A * k
+    hbar = h / (2*math.pi)
+    G_0 = 2 * e**2 / h
+
+    # Wien law numerical constants: https://en.wikipedia.org/wiki/Wien%27s_displacement_law
+    # (alpha - 3)*exp(alpha) + 3 = 0
+    # (x - 5)*exp(x) + 5 = 0
+    alpha_W = 2.821439372122078893403  # 3 + lambertw(-3 * exp(-3))
+    x_W = 4.965114231744276303699  # 5 + lambertw(-5 * exp(-5))
+
+    # Conventional electrical unit
+    # See https://en.wikipedia.org/wiki/Conventional_electrical_unit
+    K_J90 = exact['conventional value of Josephson constant']
+    K_J = 2 * e / h
+    R_K90 = exact['conventional value of von Klitzing constant']
+    R_K = h / e**2
+    V_90 = K_J90 / K_J
+    ohm_90 = R_K / R_K90
+    A_90 = V_90 / ohm_90
+
+    replace = {
+        'atomic unit of action': hbar,
+        'Boltzmann constant in eV/K': k / e,
+        'Boltzmann constant in Hz/K': k / h,
+        'Boltzmann constant in inverse meter per kelvin': k / (h * c),
+        'conductance quantum': G_0,
+        'conventional value of ampere-90': A_90,
+        'conventional value of coulomb-90': A_90,
+        'conventional value of farad-90': 1 / ohm_90,
+        'conventional value of henry-90': ohm_90,
+        'conventional value of ohm-90': ohm_90,
+        'conventional value of volt-90': V_90,
+        'conventional value of watt-90': V_90**2 / ohm_90,
+        'electron volt-hertz relationship': e / h,
+        'electron volt-inverse meter relationship': e / (h * c),
+        'electron volt-kelvin relationship': e / k,
+        'electron volt-kilogram relationship': e / c**2,
+        'elementary charge over h-bar': e / hbar,
+        'Faraday constant': e * N_A,
+        'first radiation constant': 2 * math.pi * h * c**2,
+        'first radiation constant for spectral radiance': 2 * h * c**2,
+        'hertz-electron volt relationship': h / e,
+        'hertz-inverse meter relationship': 1 / c,
+        'hertz-kelvin relationship': h / k,
+        'hertz-kilogram relationship': h / c**2,
+        'inverse meter-electron volt relationship': (h * c) / e,
+        'inverse meter-joule relationship': h * c,
+        'inverse meter-kelvin relationship': h * c / k,
+        'inverse meter-kilogram relationship': h / c,
+        'inverse of conductance quantum': 1 / G_0,
+        'Josephson constant': K_J,
+        'joule-electron volt relationship': 1 / e,
+        'joule-hertz relationship': 1 / h,
+        'joule-inverse meter relationship': 1 / (h * c),
+        'joule-kelvin relationship': 1 / k,
+        'joule-kilogram relationship': 1 / c**2,
+        'kelvin-electron volt relationship': k / e,
+        'kelvin-hertz relationship': k / h,
+        'kelvin-inverse meter relationship': k / (h * c),
+        'kelvin-kilogram relationship': k / c**2,
+        'kilogram-electron volt relationship': c**2 / e,
+        'kilogram-hertz relationship': c**2 / h,
+        'kilogram-inverse meter relationship': c / h,
+        'kilogram-joule relationship': c**2,
+        'kilogram-kelvin relationship': c**2 / k,
+        'Loschmidt constant (273.15 K, 100 kPa)': 100e3 / 273.15 / k,
+        'Loschmidt constant (273.15 K, 101.325 kPa)': 101.325e3 / 273.15 / k,
+        'mag. flux quantum': h / (2 * e),
+        'molar gas constant': R,
+        'molar Planck constant': h * N_A,
+        'molar volume of ideal gas (273.15 K, 100 kPa)': R * 273.15 / 100e3,
+        'molar volume of ideal gas (273.15 K, 101.325 kPa)': R * 273.15 / 101.325e3,
+        'natural unit of action': hbar,
+        'natural unit of action in eV s': hbar / e,
+        'Planck constant in eV/Hz': h / e,
+        'reduced Planck constant': hbar,
+        'reduced Planck constant in eV s': hbar / e,
+        'reduced Planck constant times c in MeV fm': hbar * c / (e * 1e6 * 1e-15),
+        'second radiation constant': h * c / k,
+        'Stefan-Boltzmann constant': 2 * math.pi**5 * k**4 / (15 * h**3 * c**2),
+        'von Klitzing constant': R_K,
+        'Wien frequency displacement law constant': alpha_W * k / h,
+        'Wien wavelength displacement law constant': h * c / (x_W * k),
+    }
+    return replace
+
+
+txt2022 = """\
+alpha particle-electron mass ratio                          7294.299 541 71          0.000 000 17             
+alpha particle mass                                         6.644 657 3450 e-27      0.000 000 0021 e-27      kg
+alpha particle mass energy equivalent                       5.971 920 1997 e-10      0.000 000 0019 e-10      J
+alpha particle mass energy equivalent in MeV                3727.379 4118            0.000 0012               MeV
+alpha particle mass in u                                    4.001 506 179 129        0.000 000 000 062        u
+alpha particle molar mass                                   4.001 506 1833 e-3       0.000 000 0012 e-3       kg mol^-1
+alpha particle-proton mass ratio                            3.972 599 690 252        0.000 000 000 070        
+alpha particle relative atomic mass                         4.001 506 179 129        0.000 000 000 062        
+alpha particle rms charge radius                            1.6785 e-15              0.0021 e-15              m
+Angstrom star                                               1.000 014 95 e-10        0.000 000 90 e-10        m
+atomic mass constant                                        1.660 539 068 92 e-27    0.000 000 000 52 e-27    kg
+atomic mass constant energy equivalent                      1.492 418 087 68 e-10    0.000 000 000 46 e-10    J
+atomic mass constant energy equivalent in MeV               931.494 103 72           0.000 000 29             MeV
+atomic mass unit-electron volt relationship                 9.314 941 0372 e8        0.000 000 0029 e8        eV
+atomic mass unit-hartree relationship                       3.423 177 6922 e7        0.000 000 0011 e7        E_h
+atomic mass unit-hertz relationship                         2.252 342 721 85 e23     0.000 000 000 70 e23     Hz
+atomic mass unit-inverse meter relationship                 7.513 006 6209 e14       0.000 000 0023 e14       m^-1
+atomic mass unit-joule relationship                         1.492 418 087 68 e-10    0.000 000 000 46 e-10    J
+atomic mass unit-kelvin relationship                        1.080 954 020 67 e13     0.000 000 000 34 e13     K
+atomic mass unit-kilogram relationship                      1.660 539 068 92 e-27    0.000 000 000 52 e-27    kg
+atomic unit of 1st hyperpolarizability                      3.206 361 2996 e-53      0.000 000 0015 e-53      C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                      6.235 379 9735 e-65      0.000 000 0039 e-65      C^4 m^4 J^-3
+atomic unit of action                                       1.054 571 817... e-34    (exact)                  J s
+atomic unit of charge                                       1.602 176 634 e-19       (exact)                  C
+atomic unit of charge density                               1.081 202 386 77 e12     0.000 000 000 51 e12     C m^-3
+atomic unit of current                                      6.623 618 237 5082 e-3   0.000 000 000 0072 e-3   A
+atomic unit of electric dipole mom.                         8.478 353 6198 e-30      0.000 000 0013 e-30      C m
+atomic unit of electric field                               5.142 206 751 12 e11     0.000 000 000 80 e11     V m^-1
+atomic unit of electric field gradient                      9.717 362 4424 e21       0.000 000 0030 e21       V m^-2
+atomic unit of electric polarizability                      1.648 777 272 12 e-41    0.000 000 000 51 e-41    C^2 m^2 J^-1
+atomic unit of electric potential                           27.211 386 245 981       0.000 000 000 030        V
+atomic unit of electric quadrupole mom.                     4.486 551 5185 e-40      0.000 000 0014 e-40      C m^2
+atomic unit of energy                                       4.359 744 722 2060 e-18  0.000 000 000 0048 e-18  J
+atomic unit of force                                        8.238 723 5038 e-8       0.000 000 0013 e-8       N
+atomic unit of length                                       5.291 772 105 44 e-11    0.000 000 000 82 e-11    m
+atomic unit of mag. dipole mom.                             1.854 802 013 15 e-23    0.000 000 000 58 e-23    J T^-1
+atomic unit of mag. flux density                            2.350 517 570 77 e5      0.000 000 000 73 e5      T
+atomic unit of magnetizability                              7.891 036 5794 e-29      0.000 000 0049 e-29      J T^-2
+atomic unit of mass                                         9.109 383 7139 e-31      0.000 000 0028 e-31      kg
+atomic unit of momentum                                     1.992 851 915 45 e-24    0.000 000 000 31 e-24    kg m s^-1
+atomic unit of permittivity                                 1.112 650 056 20 e-10    0.000 000 000 17 e-10    F m^-1
+atomic unit of time                                         2.418 884 326 5864 e-17  0.000 000 000 0026 e-17  s
+atomic unit of velocity                                     2.187 691 262 16 e6      0.000 000 000 34 e6      m s^-1
+Avogadro constant                                           6.022 140 76 e23         (exact)                  mol^-1
+Bohr magneton                                               9.274 010 0657 e-24      0.000 000 0029 e-24      J T^-1
+Bohr magneton in eV/T                                       5.788 381 7982 e-5       0.000 000 0018 e-5       eV T^-1
+Bohr magneton in Hz/T                                       1.399 624 491 71 e10     0.000 000 000 44 e10     Hz T^-1
+Bohr magneton in inverse meter per tesla                    46.686 447 719           0.000 000 015            m^-1 T^-1
+Bohr magneton in K/T                                        0.671 713 814 72         0.000 000 000 21         K T^-1
+Bohr radius                                                 5.291 772 105 44 e-11    0.000 000 000 82 e-11    m
+Boltzmann constant                                          1.380 649 e-23           (exact)                  J K^-1
+Boltzmann constant in eV/K                                  8.617 333 262... e-5     (exact)                  eV K^-1
+Boltzmann constant in Hz/K                                  2.083 661 912... e10     (exact)                  Hz K^-1
+Boltzmann constant in inverse meter per kelvin              69.503 480 04...         (exact)                  m^-1 K^-1
+characteristic impedance of vacuum                          376.730 313 412          0.000 000 059            ohm
+classical electron radius                                   2.817 940 3205 e-15      0.000 000 0013 e-15      m
+Compton wavelength                                          2.426 310 235 38 e-12    0.000 000 000 76 e-12    m
+conductance quantum                                         7.748 091 729... e-5     (exact)                  S
+conventional value of ampere-90                             1.000 000 088 87...      (exact)                  A
+conventional value of coulomb-90                            1.000 000 088 87...      (exact)                  C
+conventional value of farad-90                              0.999 999 982 20...      (exact)                  F
+conventional value of henry-90                              1.000 000 017 79...      (exact)                  H
+conventional value of Josephson constant                    483 597.9 e9             (exact)                  Hz V^-1
+conventional value of ohm-90                                1.000 000 017 79...      (exact)                  ohm
+conventional value of volt-90                               1.000 000 106 66...      (exact)                  V
+conventional value of von Klitzing constant                 25 812.807               (exact)                  ohm
+conventional value of watt-90                               1.000 000 195 53...      (exact)                  W
+Copper x unit                                               1.002 076 97 e-13        0.000 000 28 e-13        m
+deuteron-electron mag. mom. ratio                           -4.664 345 550 e-4       0.000 000 012 e-4        
+deuteron-electron mass ratio                                3670.482 967 655         0.000 000 063            
+deuteron g factor                                           0.857 438 2335           0.000 000 0022           
+deuteron mag. mom.                                          4.330 735 087 e-27       0.000 000 011 e-27       J T^-1
+deuteron mag. mom. to Bohr magneton ratio                   4.669 754 568 e-4        0.000 000 012 e-4        
+deuteron mag. mom. to nuclear magneton ratio                0.857 438 2335           0.000 000 0022           
+deuteron mass                                               3.343 583 7768 e-27      0.000 000 0010 e-27      kg
+deuteron mass energy equivalent                             3.005 063 234 91 e-10    0.000 000 000 94 e-10    J
+deuteron mass energy equivalent in MeV                      1875.612 945 00          0.000 000 58             MeV
+deuteron mass in u                                          2.013 553 212 544        0.000 000 000 015        u
+deuteron molar mass                                         2.013 553 214 66 e-3     0.000 000 000 63 e-3     kg mol^-1
+deuteron-neutron mag. mom. ratio                            -0.448 206 52            0.000 000 11             
+deuteron-proton mag. mom. ratio                             0.307 012 209 30         0.000 000 000 79         
+deuteron-proton mass ratio                                  1.999 007 501 2699       0.000 000 000 0084       
+deuteron relative atomic mass                               2.013 553 212 544        0.000 000 000 015        
+deuteron rms charge radius                                  2.127 78 e-15            0.000 27 e-15            m
+electron charge to mass quotient                            -1.758 820 008 38 e11    0.000 000 000 55 e11     C kg^-1
+electron-deuteron mag. mom. ratio                           -2143.923 4921           0.000 0056               
+electron-deuteron mass ratio                                2.724 437 107 629 e-4    0.000 000 000 047 e-4    
+electron g factor                                           -2.002 319 304 360 92    0.000 000 000 000 36     
+electron gyromag. ratio                                     1.760 859 627 84 e11     0.000 000 000 55 e11     s^-1 T^-1
+electron gyromag. ratio in MHz/T                            28 024.951 3861          0.000 0087               MHz T^-1
+electron-helion mass ratio                                  1.819 543 074 649 e-4    0.000 000 000 053 e-4    
+electron mag. mom.                                          -9.284 764 6917 e-24     0.000 000 0029 e-24      J T^-1
+electron mag. mom. anomaly                                  1.159 652 180 46 e-3     0.000 000 000 18 e-3     
+electron mag. mom. to Bohr magneton ratio                   -1.001 159 652 180 46    0.000 000 000 000 18     
+electron mag. mom. to nuclear magneton ratio                -1838.281 971 877        0.000 000 032            
+electron mass                                               9.109 383 7139 e-31      0.000 000 0028 e-31      kg
+electron mass energy equivalent                             8.187 105 7880 e-14      0.000 000 0026 e-14      J
+electron mass energy equivalent in MeV                      0.510 998 950 69         0.000 000 000 16         MeV
+electron mass in u                                          5.485 799 090 441 e-4    0.000 000 000 097 e-4    u
+electron molar mass                                         5.485 799 0962 e-7       0.000 000 0017 e-7       kg mol^-1
+electron-muon mag. mom. ratio                               206.766 9881             0.000 0046               
+electron-muon mass ratio                                    4.836 331 70 e-3         0.000 000 11 e-3         
+electron-neutron mag. mom. ratio                            960.920 48               0.000 23                 
+electron-neutron mass ratio                                 5.438 673 4416 e-4       0.000 000 0022 e-4       
+electron-proton mag. mom. ratio                             -658.210 687 89          0.000 000 19             
+electron-proton mass ratio                                  5.446 170 214 889 e-4    0.000 000 000 094 e-4    
+electron relative atomic mass                               5.485 799 090 441 e-4    0.000 000 000 097 e-4    
+electron-tau mass ratio                                     2.875 85 e-4             0.000 19 e-4             
+electron to alpha particle mass ratio                       1.370 933 554 733 e-4    0.000 000 000 032 e-4    
+electron to shielded helion mag. mom. ratio                 864.058 239 86           0.000 000 70             
+electron to shielded proton mag. mom. ratio                 -658.227 5856            0.000 0027               
+electron-triton mass ratio                                  1.819 200 062 327 e-4    0.000 000 000 068 e-4    
+electron volt                                               1.602 176 634 e-19       (exact)                  J
+electron volt-atomic mass unit relationship                 1.073 544 100 83 e-9     0.000 000 000 33 e-9     u
+electron volt-hartree relationship                          3.674 932 217 5665 e-2   0.000 000 000 0040 e-2   E_h
+electron volt-hertz relationship                            2.417 989 242... e14     (exact)                  Hz
+electron volt-inverse meter relationship                    8.065 543 937... e5      (exact)                  m^-1
+electron volt-joule relationship                            1.602 176 634 e-19       (exact)                  J
+electron volt-kelvin relationship                           1.160 451 812... e4      (exact)                  K
+electron volt-kilogram relationship                         1.782 661 921... e-36    (exact)                  kg
+elementary charge                                           1.602 176 634 e-19       (exact)                  C
+elementary charge over h-bar                                1.519 267 447... e15     (exact)                  A J^-1
+Faraday constant                                            96 485.332 12...         (exact)                  C mol^-1
+Fermi coupling constant                                     1.166 3787 e-5           0.000 0006 e-5           GeV^-2
+fine-structure constant                                     7.297 352 5643 e-3       0.000 000 0011 e-3       
+first radiation constant                                    3.741 771 852... e-16    (exact)                  W m^2
+first radiation constant for spectral radiance              1.191 042 972... e-16    (exact)                  W m^2 sr^-1
+hartree-atomic mass unit relationship                       2.921 262 317 97 e-8     0.000 000 000 91 e-8     u
+hartree-electron volt relationship                          27.211 386 245 981       0.000 000 000 030        eV
+Hartree energy                                              4.359 744 722 2060 e-18  0.000 000 000 0048 e-18  J
+Hartree energy in eV                                        27.211 386 245 981       0.000 000 000 030        eV
+hartree-hertz relationship                                  6.579 683 920 4999 e15   0.000 000 000 0072 e15   Hz
+hartree-inverse meter relationship                          2.194 746 313 6314 e7    0.000 000 000 0024 e7    m^-1
+hartree-joule relationship                                  4.359 744 722 2060 e-18  0.000 000 000 0048 e-18  J
+hartree-kelvin relationship                                 3.157 750 248 0398 e5    0.000 000 000 0034 e5    K
+hartree-kilogram relationship                               4.850 870 209 5419 e-35  0.000 000 000 0053 e-35  kg
+helion-electron mass ratio                                  5495.885 279 84          0.000 000 16             
+helion g factor                                             -4.255 250 6995          0.000 000 0034           
+helion mag. mom.                                            -1.074 617 551 98 e-26   0.000 000 000 93 e-26    J T^-1
+helion mag. mom. to Bohr magneton ratio                     -1.158 740 980 83 e-3    0.000 000 000 94 e-3     
+helion mag. mom. to nuclear magneton ratio                  -2.127 625 3498          0.000 000 0017           
+helion mass                                                 5.006 412 7862 e-27      0.000 000 0016 e-27      kg
+helion mass energy equivalent                               4.499 539 4185 e-10      0.000 000 0014 e-10      J
+helion mass energy equivalent in MeV                        2808.391 611 12          0.000 000 88             MeV
+helion mass in u                                            3.014 932 246 932        0.000 000 000 074        u
+helion molar mass                                           3.014 932 250 10 e-3     0.000 000 000 94 e-3     kg mol^-1
+helion-proton mass ratio                                    2.993 152 671 552        0.000 000 000 070        
+helion relative atomic mass                                 3.014 932 246 932        0.000 000 000 074        
+helion shielding shift                                      5.996 7029 e-5           0.000 0023 e-5           
+hertz-atomic mass unit relationship                         4.439 821 6590 e-24      0.000 000 0014 e-24      u
+hertz-electron volt relationship                            4.135 667 696... e-15    (exact)                  eV
+hertz-hartree relationship                                  1.519 829 846 0574 e-16  0.000 000 000 0017 e-16  E_h
+hertz-inverse meter relationship                            3.335 640 951... e-9     (exact)                  m^-1
+hertz-joule relationship                                    6.626 070 15 e-34        (exact)                  J
+hertz-kelvin relationship                                   4.799 243 073... e-11    (exact)                  K
+hertz-kilogram relationship                                 7.372 497 323... e-51    (exact)                  kg
+hyperfine transition frequency of Cs-133                    9 192 631 770            (exact)                  Hz
+inverse fine-structure constant                             137.035 999 177          0.000 000 021            
+inverse meter-atomic mass unit relationship                 1.331 025 048 24 e-15    0.000 000 000 41 e-15    u
+inverse meter-electron volt relationship                    1.239 841 984... e-6     (exact)                  eV
+inverse meter-hartree relationship                          4.556 335 252 9132 e-8   0.000 000 000 0050 e-8   E_h
+inverse meter-hertz relationship                            299 792 458              (exact)                  Hz
+inverse meter-joule relationship                            1.986 445 857... e-25    (exact)                  J
+inverse meter-kelvin relationship                           1.438 776 877... e-2     (exact)                  K
+inverse meter-kilogram relationship                         2.210 219 094... e-42    (exact)                  kg
+inverse of conductance quantum                              12 906.403 72...         (exact)                  ohm
+Josephson constant                                          483 597.848 4... e9      (exact)                  Hz V^-1
+joule-atomic mass unit relationship                         6.700 535 2471 e9        0.000 000 0021 e9        u
+joule-electron volt relationship                            6.241 509 074... e18     (exact)                  eV
+joule-hartree relationship                                  2.293 712 278 3969 e17   0.000 000 000 0025 e17   E_h
+joule-hertz relationship                                    1.509 190 179... e33     (exact)                  Hz
+joule-inverse meter relationship                            5.034 116 567... e24     (exact)                  m^-1
+joule-kelvin relationship                                   7.242 970 516... e22     (exact)                  K
+joule-kilogram relationship                                 1.112 650 056... e-17    (exact)                  kg
+kelvin-atomic mass unit relationship                        9.251 087 2884 e-14      0.000 000 0029 e-14      u
+kelvin-electron volt relationship                           8.617 333 262... e-5     (exact)                  eV
+kelvin-hartree relationship                                 3.166 811 563 4564 e-6   0.000 000 000 0035 e-6   E_h
+kelvin-hertz relationship                                   2.083 661 912... e10     (exact)                  Hz
+kelvin-inverse meter relationship                           69.503 480 04...         (exact)                  m^-1
+kelvin-joule relationship                                   1.380 649 e-23           (exact)                  J
+kelvin-kilogram relationship                                1.536 179 187... e-40    (exact)                  kg
+kilogram-atomic mass unit relationship                      6.022 140 7537 e26       0.000 000 0019 e26       u
+kilogram-electron volt relationship                         5.609 588 603... e35     (exact)                  eV
+kilogram-hartree relationship                               2.061 485 788 7415 e34   0.000 000 000 0022 e34   E_h
+kilogram-hertz relationship                                 1.356 392 489... e50     (exact)                  Hz
+kilogram-inverse meter relationship                         4.524 438 335... e41     (exact)                  m^-1
+kilogram-joule relationship                                 8.987 551 787... e16     (exact)                  J
+kilogram-kelvin relationship                                6.509 657 260... e39     (exact)                  K
+lattice parameter of silicon                                5.431 020 511 e-10       0.000 000 089 e-10       m
+lattice spacing of ideal Si (220)                           1.920 155 716 e-10       0.000 000 032 e-10       m
+Loschmidt constant (273.15 K, 100 kPa)                      2.651 645 804... e25     (exact)                  m^-3
+Loschmidt constant (273.15 K, 101.325 kPa)                  2.686 780 111... e25     (exact)                  m^-3
+luminous efficacy                                           683                      (exact)                  lm W^-1
+mag. flux quantum                                           2.067 833 848... e-15    (exact)                  Wb
+molar gas constant                                          8.314 462 618...         (exact)                  J mol^-1 K^-1
+molar mass constant                                         1.000 000 001 05 e-3     0.000 000 000 31 e-3     kg mol^-1
+molar mass of carbon-12                                     12.000 000 0126 e-3      0.000 000 0037 e-3       kg mol^-1
+molar Planck constant                                       3.990 312 712... e-10    (exact)                  J Hz^-1 mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)               22.710 954 64... e-3     (exact)                  m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)           22.413 969 54... e-3     (exact)                  m^3 mol^-1
+molar volume of silicon                                     1.205 883 199 e-5        0.000 000 060 e-5        m^3 mol^-1
+Molybdenum x unit                                           1.002 099 52 e-13        0.000 000 53 e-13        m
+muon Compton wavelength                                     1.173 444 110 e-14       0.000 000 026 e-14       m
+muon-electron mass ratio                                    206.768 2827             0.000 0046               
+muon g factor                                               -2.002 331 841 23        0.000 000 000 82         
+muon mag. mom.                                              -4.490 448 30 e-26       0.000 000 10 e-26        J T^-1
+muon mag. mom. anomaly                                      1.165 920 62 e-3         0.000 000 41 e-3         
+muon mag. mom. to Bohr magneton ratio                       -4.841 970 48 e-3        0.000 000 11 e-3         
+muon mag. mom. to nuclear magneton ratio                    -8.890 597 04            0.000 000 20             
+muon mass                                                   1.883 531 627 e-28       0.000 000 042 e-28       kg
+muon mass energy equivalent                                 1.692 833 804 e-11       0.000 000 038 e-11       J
+muon mass energy equivalent in MeV                          105.658 3755             0.000 0023               MeV
+muon mass in u                                              0.113 428 9257           0.000 000 0025           u
+muon molar mass                                             1.134 289 258 e-4        0.000 000 025 e-4        kg mol^-1
+muon-neutron mass ratio                                     0.112 454 5168           0.000 000 0025           
+muon-proton mag. mom. ratio                                 -3.183 345 146           0.000 000 071            
+muon-proton mass ratio                                      0.112 609 5262           0.000 000 0025           
+muon-tau mass ratio                                         5.946 35 e-2             0.000 40 e-2             
+natural unit of action                                      1.054 571 817... e-34    (exact)                  J s
+natural unit of action in eV s                              6.582 119 569... e-16    (exact)                  eV s
+natural unit of energy                                      8.187 105 7880 e-14      0.000 000 0026 e-14      J
+natural unit of energy in MeV                               0.510 998 950 69         0.000 000 000 16         MeV
+natural unit of length                                      3.861 592 6744 e-13      0.000 000 0012 e-13      m
+natural unit of mass                                        9.109 383 7139 e-31      0.000 000 0028 e-31      kg
+natural unit of momentum                                    2.730 924 534 46 e-22    0.000 000 000 85 e-22    kg m s^-1
+natural unit of momentum in MeV/c                           0.510 998 950 69         0.000 000 000 16         MeV/c
+natural unit of time                                        1.288 088 666 44 e-21    0.000 000 000 40 e-21    s
+natural unit of velocity                                    299 792 458              (exact)                  m s^-1
+neutron Compton wavelength                                  1.319 590 903 82 e-15    0.000 000 000 67 e-15    m
+neutron-electron mag. mom. ratio                            1.040 668 84 e-3         0.000 000 24 e-3         
+neutron-electron mass ratio                                 1838.683 662 00          0.000 000 74             
+neutron g factor                                            -3.826 085 52            0.000 000 90             
+neutron gyromag. ratio                                      1.832 471 74 e8          0.000 000 43 e8          s^-1 T^-1
+neutron gyromag. ratio in MHz/T                             29.164 6935              0.000 0069               MHz T^-1
+neutron mag. mom.                                           -9.662 3653 e-27         0.000 0023 e-27          J T^-1
+neutron mag. mom. to Bohr magneton ratio                    -1.041 875 65 e-3        0.000 000 25 e-3         
+neutron mag. mom. to nuclear magneton ratio                 -1.913 042 76            0.000 000 45             
+neutron mass                                                1.674 927 500 56 e-27    0.000 000 000 85 e-27    kg
+neutron mass energy equivalent                              1.505 349 765 14 e-10    0.000 000 000 76 e-10    J
+neutron mass energy equivalent in MeV                       939.565 421 94           0.000 000 48             MeV
+neutron mass in u                                           1.008 664 916 06         0.000 000 000 40         u
+neutron molar mass                                          1.008 664 917 12 e-3     0.000 000 000 51 e-3     kg mol^-1
+neutron-muon mass ratio                                     8.892 484 08             0.000 000 20             
+neutron-proton mag. mom. ratio                              -0.684 979 35            0.000 000 16             
+neutron-proton mass difference                              2.305 574 61 e-30        0.000 000 67 e-30        kg
+neutron-proton mass difference energy equivalent            2.072 147 12 e-13        0.000 000 60 e-13        J
+neutron-proton mass difference energy equivalent in MeV     1.293 332 51             0.000 000 38             MeV
+neutron-proton mass difference in u                         1.388 449 48 e-3         0.000 000 40 e-3         u
+neutron-proton mass ratio                                   1.001 378 419 46         0.000 000 000 40         
+neutron relative atomic mass                                1.008 664 916 06         0.000 000 000 40         
+neutron-tau mass ratio                                      0.528 779                0.000 036                
+neutron to shielded proton mag. mom. ratio                  -0.684 996 94            0.000 000 16             
+Newtonian constant of gravitation                           6.674 30 e-11            0.000 15 e-11            m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c              6.708 83 e-39            0.000 15 e-39            (GeV/c^2)^-2
+nuclear magneton                                            5.050 783 7393 e-27      0.000 000 0016 e-27      J T^-1
+nuclear magneton in eV/T                                    3.152 451 254 17 e-8     0.000 000 000 98 e-8     eV T^-1
+nuclear magneton in inverse meter per tesla                 2.542 623 410 09 e-2     0.000 000 000 79 e-2     m^-1 T^-1
+nuclear magneton in K/T                                     3.658 267 7706 e-4       0.000 000 0011 e-4       K T^-1
+nuclear magneton in MHz/T                                   7.622 593 2188           0.000 000 0024           MHz T^-1
+Planck constant                                             6.626 070 15 e-34        (exact)                  J Hz^-1
+Planck constant in eV/Hz                                    4.135 667 696... e-15    (exact)                  eV Hz^-1
+Planck length                                               1.616 255 e-35           0.000 018 e-35           m
+Planck mass                                                 2.176 434 e-8            0.000 024 e-8            kg
+Planck mass energy equivalent in GeV                        1.220 890 e19            0.000 014 e19            GeV
+Planck temperature                                          1.416 784 e32            0.000 016 e32            K
+Planck time                                                 5.391 247 e-44           0.000 060 e-44           s
+proton charge to mass quotient                              9.578 833 1430 e7        0.000 000 0030 e7        C kg^-1
+proton Compton wavelength                                   1.321 409 853 60 e-15    0.000 000 000 41 e-15    m
+proton-electron mass ratio                                  1836.152 673 426         0.000 000 032            
+proton g factor                                             5.585 694 6893           0.000 000 0016           
+proton gyromag. ratio                                       2.675 221 8708 e8        0.000 000 0011 e8        s^-1 T^-1
+proton gyromag. ratio in MHz/T                              42.577 478 461           0.000 000 018            MHz T^-1
+proton mag. mom.                                            1.410 606 795 45 e-26    0.000 000 000 60 e-26    J T^-1
+proton mag. mom. to Bohr magneton ratio                     1.521 032 202 30 e-3     0.000 000 000 45 e-3     
+proton mag. mom. to nuclear magneton ratio                  2.792 847 344 63         0.000 000 000 82         
+proton mag. shielding correction                            2.567 15 e-5             0.000 41 e-5             
+proton mass                                                 1.672 621 925 95 e-27    0.000 000 000 52 e-27    kg
+proton mass energy equivalent                               1.503 277 618 02 e-10    0.000 000 000 47 e-10    J
+proton mass energy equivalent in MeV                        938.272 089 43           0.000 000 29             MeV
+proton mass in u                                            1.007 276 466 5789       0.000 000 000 0083       u
+proton molar mass                                           1.007 276 467 64 e-3     0.000 000 000 31 e-3     kg mol^-1
+proton-muon mass ratio                                      8.880 243 38             0.000 000 20             
+proton-neutron mag. mom. ratio                              -1.459 898 02            0.000 000 34             
+proton-neutron mass ratio                                   0.998 623 477 97         0.000 000 000 40         
+proton relative atomic mass                                 1.007 276 466 5789       0.000 000 000 0083       
+proton rms charge radius                                    8.4075 e-16              0.0064 e-16              m
+proton-tau mass ratio                                       0.528 051                0.000 036                
+quantum of circulation                                      3.636 947 5467 e-4       0.000 000 0011 e-4       m^2 s^-1
+quantum of circulation times 2                              7.273 895 0934 e-4       0.000 000 0023 e-4       m^2 s^-1
+reduced Compton wavelength                                  3.861 592 6744 e-13      0.000 000 0012 e-13      m
+reduced muon Compton wavelength                             1.867 594 306 e-15       0.000 000 042 e-15       m
+reduced neutron Compton wavelength                          2.100 194 1520 e-16      0.000 000 0011 e-16      m
+reduced Planck constant                                     1.054 571 817... e-34    (exact)                  J s
+reduced Planck constant in eV s                             6.582 119 569... e-16    (exact)                  eV s
+reduced Planck constant times c in MeV fm                   197.326 980 4...         (exact)                  MeV fm
+reduced proton Compton wavelength                           2.103 089 100 51 e-16    0.000 000 000 66 e-16    m
+reduced tau Compton wavelength                              1.110 538 e-16           0.000 075 e-16           m
+Rydberg constant                                            10 973 731.568 157       0.000 012                m^-1
+Rydberg constant times c in Hz                              3.289 841 960 2500 e15   0.000 000 000 0036 e15   Hz
+Rydberg constant times hc in eV                             13.605 693 122 990       0.000 000 000 015        eV
+Rydberg constant times hc in J                              2.179 872 361 1030 e-18  0.000 000 000 0024 e-18  J
+Sackur-Tetrode constant (1 K, 100 kPa)                      -1.151 707 534 96        0.000 000 000 47         
+Sackur-Tetrode constant (1 K, 101.325 kPa)                  -1.164 870 521 49        0.000 000 000 47         
+second radiation constant                                   1.438 776 877... e-2     (exact)                  m K
+shielded helion gyromag. ratio                              2.037 894 6078 e8        0.000 000 0018 e8        s^-1 T^-1
+shielded helion gyromag. ratio in MHz/T                     32.434 100 033           0.000 000 028            MHz T^-1
+shielded helion mag. mom.                                   -1.074 553 110 35 e-26   0.000 000 000 93 e-26    J T^-1
+shielded helion mag. mom. to Bohr magneton ratio            -1.158 671 494 57 e-3    0.000 000 000 94 e-3     
+shielded helion mag. mom. to nuclear magneton ratio         -2.127 497 7624          0.000 000 0017           
+shielded helion to proton mag. mom. ratio                   -0.761 766 577 21        0.000 000 000 66         
+shielded helion to shielded proton mag. mom. ratio          -0.761 786 1334          0.000 000 0031           
+shielded proton gyromag. ratio                              2.675 153 194 e8         0.000 000 011 e8         s^-1 T^-1
+shielded proton gyromag. ratio in MHz/T                     42.576 385 43            0.000 000 17             MHz T^-1
+shielded proton mag. mom.                                   1.410 570 5830 e-26      0.000 000 0058 e-26      J T^-1
+shielded proton mag. mom. to Bohr magneton ratio            1.520 993 1551 e-3       0.000 000 0062 e-3       
+shielded proton mag. mom. to nuclear magneton ratio         2.792 775 648            0.000 000 011            
+shielding difference of d and p in HD                       1.987 70 e-8             0.000 10 e-8             
+shielding difference of t and p in HT                       2.394 50 e-8             0.000 20 e-8             
+speed of light in vacuum                                    299 792 458              (exact)                  m s^-1
+standard acceleration of gravity                            9.806 65                 (exact)                  m s^-2
+standard atmosphere                                         101 325                  (exact)                  Pa
+standard-state pressure                                     100 000                  (exact)                  Pa
+Stefan-Boltzmann constant                                   5.670 374 419... e-8     (exact)                  W m^-2 K^-4
+tau Compton wavelength                                      6.977 71 e-16            0.000 47 e-16            m
+tau-electron mass ratio                                     3477.23                  0.23                     
+tau energy equivalent                                       1776.86                  0.12                     MeV
+tau mass                                                    3.167 54 e-27            0.000 21 e-27            kg
+tau mass energy equivalent                                  2.846 84 e-10            0.000 19 e-10            J
+tau mass in u                                               1.907 54                 0.000 13                 u
+tau molar mass                                              1.907 54 e-3             0.000 13 e-3             kg mol^-1
+tau-muon mass ratio                                         16.8170                  0.0011                   
+tau-neutron mass ratio                                      1.891 15                 0.000 13                 
+tau-proton mass ratio                                       1.893 76                 0.000 13                 
+Thomson cross section                                       6.652 458 7051 e-29      0.000 000 0062 e-29      m^2
+triton-electron mass ratio                                  5496.921 535 51          0.000 000 21             
+triton g factor                                             5.957 924 930            0.000 000 012            
+triton mag. mom.                                            1.504 609 5178 e-26      0.000 000 0030 e-26      J T^-1
+triton mag. mom. to Bohr magneton ratio                     1.622 393 6648 e-3       0.000 000 0032 e-3       
+triton mag. mom. to nuclear magneton ratio                  2.978 962 4650           0.000 000 0059           
+triton mass                                                 5.007 356 7512 e-27      0.000 000 0016 e-27      kg
+triton mass energy equivalent                               4.500 387 8119 e-10      0.000 000 0014 e-10      J
+triton mass energy equivalent in MeV                        2808.921 136 68          0.000 000 88             MeV
+triton mass in u                                            3.015 500 715 97         0.000 000 000 10         u
+triton molar mass                                           3.015 500 719 13 e-3     0.000 000 000 94 e-3     kg mol^-1
+triton-proton mass ratio                                    2.993 717 034 03         0.000 000 000 10         
+triton relative atomic mass                                 3.015 500 715 97         0.000 000 000 10         
+triton to proton mag. mom. ratio                            1.066 639 9189           0.000 000 0021           
+unified atomic mass unit                                    1.660 539 068 92 e-27    0.000 000 000 52 e-27    kg
+vacuum electric permittivity                                8.854 187 8188 e-12      0.000 000 0014 e-12      F m^-1
+vacuum mag. permeability                                    1.256 637 061 27 e-6     0.000 000 000 20 e-6     N A^-2
+von Klitzing constant                                       25 812.807 45...         (exact)                  ohm
+weak mixing angle                                           0.223 05                 0.000 23                 
+Wien frequency displacement law constant                    5.878 925 757... e10     (exact)                  Hz K^-1
+Wien wavelength displacement law constant                   2.897 771 955... e-3     (exact)                  m K
+W to Z mass ratio                                           0.881 45                 0.000 13                    """
+
+
+exact2022 = exact2018
+
+
+# -----------------------------------------------------------------------------
+
+
+def parse_constants_2002to2014(
+    d: str, exact_func: Callable[[Any], Any]
+) -> dict[str, tuple[float, str, float]]:
+    constants: dict[str, tuple[float, str, float]] = {}
+    exact: dict[str, float] = {}
+    need_replace = set()
+    for line in d.split('\n'):
+        name = line[:55].rstrip()
+        val = float(line[55:77].replace(' ', '').replace('...', ''))
+        is_truncated = '...' in line[55:77]
+        is_exact = '(exact)' in line[77:99]
+        if is_truncated and is_exact:
+            # missing decimals, use computed exact value
+            need_replace.add(name)
+        elif is_exact:
+            exact[name] = val
+        else:
+            assert not is_truncated
+        uncert = float(line[77:99].replace(' ', '').replace('(exact)', '0'))
+        units = line[99:].rstrip()
+        constants[name] = (val, units, uncert)
+    replace = exact_func(exact)
+    replace_exact(constants, need_replace, replace)
+    return constants
+
+
+def parse_constants_2018toXXXX(
+    d: str, exact_func: Callable[[Any], Any]
+) -> dict[str, tuple[float, str, float]]:
+    constants: dict[str, tuple[float, str, float]] = {}
+    exact: dict[str, float] = {}
+    need_replace = set()
+    for line in d.split('\n'):
+        name = line[:60].rstrip()
+        val = float(line[60:85].replace(' ', '').replace('...', ''))
+        is_truncated = '...' in line[60:85]
+        is_exact = '(exact)' in line[85:110]
+        if is_truncated and is_exact:
+            # missing decimals, use computed exact value
+            need_replace.add(name)
+        elif is_exact:
+            exact[name] = val
+        else:
+            assert not is_truncated
+        uncert = float(line[85:110].replace(' ', '').replace('(exact)', '0'))
+        units = line[110:].rstrip()
+        constants[name] = (val, units, uncert)
+    replace = exact_func(exact)
+    replace_exact(constants, need_replace, replace)
+    return constants
+
+
+def replace_exact(d, to_replace, exact):
+    for name in to_replace:
+        assert name in exact, f'Missing exact value: {name}'
+        assert abs(exact[name]/d[name][0] - 1) <= 1e-9, \
+            f'Bad exact value: {name}: { exact[name]}, {d[name][0]}'
+        d[name] = (exact[name],) + d[name][1:]
+    assert set(exact.keys()) == set(to_replace)
+
+
+_physical_constants_2002 = parse_constants_2002to2014(txt2002, exact2002)
+_physical_constants_2006 = parse_constants_2002to2014(txt2006, exact2006)
+_physical_constants_2010 = parse_constants_2002to2014(txt2010, exact2010)
+_physical_constants_2014 = parse_constants_2002to2014(txt2014, exact2014)
+_physical_constants_2018 = parse_constants_2018toXXXX(txt2018, exact2018)
+_physical_constants_2022 = parse_constants_2018toXXXX(txt2022, exact2022)
+
+physical_constants: dict[str, tuple[float, str, float]] = {}
+physical_constants.update(_physical_constants_2002)
+physical_constants.update(_physical_constants_2006)
+physical_constants.update(_physical_constants_2010)
+physical_constants.update(_physical_constants_2014)
+physical_constants.update(_physical_constants_2018)
+physical_constants.update(_physical_constants_2022)
+_current_constants = _physical_constants_2022
+_current_codata = "CODATA 2022"
+
+# check obsolete values
+_obsolete_constants = {}
+for k in physical_constants:
+    if k not in _current_constants:
+        _obsolete_constants[k] = True
+
+# generate some additional aliases
+_aliases = {}
+for k in _physical_constants_2002:
+    if 'magn.' in k:
+        _aliases[k] = k.replace('magn.', 'mag.')
+for k in _physical_constants_2006:
+    if 'momentum' in k:
+        _aliases[k] = k.replace('momentum', 'mom.um')
+for k in _physical_constants_2018:
+    if 'momentum' in k:
+        _aliases[k] = k.replace('momentum', 'mom.um')
+for k in _physical_constants_2022:
+    if 'momentum' in k:
+        _aliases[k] = k.replace('momentum', 'mom.um')        
+
+# CODATA 2018 and 2022: renamed and no longer exact; use as aliases
+_aliases['mag. constant'] = 'vacuum mag. permeability'
+_aliases['electric constant'] = 'vacuum electric permittivity'
+
+
+_extra_alias_keys = ['natural unit of velocity',
+                     'natural unit of action',
+                     'natural unit of action in eV s',
+                     'natural unit of mass',
+                     'natural unit of energy',
+                     'natural unit of energy in MeV',
+                     'natural unit of mom.um',
+                     'natural unit of mom.um in MeV/c',
+                     'natural unit of length',
+                     'natural unit of time']
+
+# finally, insert aliases for values
+for k, v in list(_aliases.items()):
+    if v in _current_constants or v in _extra_alias_keys:
+        physical_constants[k] = physical_constants[v]
+    else:
+        del _aliases[k]
+
+
+class ConstantWarning(DeprecationWarning):
+    """Accessing a constant no longer in current CODATA data set"""
+    pass
+
+
+def _check_obsolete(key: str) -> None:
+    if key in _obsolete_constants and key not in _aliases:
+        warnings.warn(f"Constant '{key}' is not in current {_current_codata} data set",
+                      ConstantWarning, stacklevel=3)
+
+
+def value(key: str) -> float:
+    """
+    Value in physical_constants indexed by key
+
+    Parameters
+    ----------
+    key : Python string
+        Key in dictionary `physical_constants`
+
+    Returns
+    -------
+    value : float
+        Value in `physical_constants` corresponding to `key`
+
+    Examples
+    --------
+    >>> from scipy import constants
+    >>> constants.value('elementary charge')
+    1.602176634e-19
+
+    """
+    _check_obsolete(key)
+    return physical_constants[key][0]
+
+
+def unit(key: str) -> str:
+    """
+    Unit in physical_constants indexed by key
+
+    Parameters
+    ----------
+    key : Python string
+        Key in dictionary `physical_constants`
+
+    Returns
+    -------
+    unit : Python string
+        Unit in `physical_constants` corresponding to `key`
+
+    Examples
+    --------
+    >>> from scipy import constants
+    >>> constants.unit('proton mass')
+    'kg'
+
+    """
+    _check_obsolete(key)
+    return physical_constants[key][1]
+
+
+def precision(key: str) -> float:
+    """
+    Relative precision in physical_constants indexed by key
+
+    Parameters
+    ----------
+    key : Python string
+        Key in dictionary `physical_constants`
+
+    Returns
+    -------
+    prec : float
+        Relative precision in `physical_constants` corresponding to `key`
+
+    Examples
+    --------
+    >>> from scipy import constants
+    >>> constants.precision('proton mass')
+    5.1e-37
+
+    """
+    _check_obsolete(key)
+    return physical_constants[key][2] / physical_constants[key][0]
+
+
+def find(sub: str | None = None, disp: bool = False) -> Any:
+    """
+    Return list of physical_constant keys containing a given string.
+
+    Parameters
+    ----------
+    sub : str
+        Sub-string to search keys for. By default, return all keys.
+    disp : bool
+        If True, print the keys that are found and return None.
+        Otherwise, return the list of keys without printing anything.
+
+    Returns
+    -------
+    keys : list or None
+        If `disp` is False, the list of keys is returned.
+        Otherwise, None is returned.
+
+    Examples
+    --------
+    >>> from scipy.constants import find, physical_constants
+
+    Which keys in the ``physical_constants`` dictionary contain 'boltzmann'?
+
+    >>> find('boltzmann')
+    ['Boltzmann constant',
+     'Boltzmann constant in Hz/K',
+     'Boltzmann constant in eV/K',
+     'Boltzmann constant in inverse meter per kelvin',
+     'Stefan-Boltzmann constant']
+
+    Get the constant called 'Boltzmann constant in Hz/K':
+
+    >>> physical_constants['Boltzmann constant in Hz/K']
+    (20836619120.0, 'Hz K^-1', 0.0)
+
+    Find constants with 'radius' in the key:
+
+    >>> find('radius')
+    ['Bohr radius',
+     'alpha particle rms charge radius',
+     'classical electron radius',
+     'deuteron rms charge radius',
+     'proton rms charge radius']
+    >>> physical_constants['classical electron radius']
+    (2.8179403262e-15, 'm', 1.3e-24)
+
+    """
+    if sub is None:
+        result = list(_current_constants.keys())
+    else:
+        result = [key for key in _current_constants
+                  if sub.lower() in key.lower()]
+
+    result.sort()
+    if disp:
+        for key in result:
+            print(key)
+        return
+    else:
+        return result
+
+# This is not used here, but it must be defined to pass
+# scipy/_lib/tests/test_public_api.py::test_private_but_present_deprecation
+c = value('speed of light in vacuum')
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/constants/_constants.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/constants/_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc4bdf83d60e37e039b9b830f74f7024c1759d32
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/constants/_constants.py
@@ -0,0 +1,369 @@
+"""
+Collection of physical constants and conversion factors.
+
+Most constants are in SI units, so you can do
+print '10 mile per minute is', 10*mile/minute, 'm/s or', 10*mile/(minute*knot), 'knots'
+
+The list is not meant to be comprehensive, but just convenient for everyday use.
+"""
+
+import math as _math
+from typing import TYPE_CHECKING, Any
+
+from ._codata import value as _cd
+
+if TYPE_CHECKING:
+    import numpy.typing as npt
+
+from scipy._lib._array_api import array_namespace, _asarray, xp_capabilities
+
+
+"""
+BasSw 2006
+physical constants: imported from CODATA
+unit conversion: see e.g., NIST special publication 811
+Use at own risk: double-check values before calculating your Mars orbit-insertion burn.
+Some constants exist in a few variants, which are marked with suffixes.
+The ones without any suffix should be the most common ones.
+"""
+
+__all__ = [
+    'Avogadro', 'Boltzmann', 'Btu', 'Btu_IT', 'Btu_th', 'G',
+    'Julian_year', 'N_A', 'Planck', 'R', 'Rydberg',
+    'Stefan_Boltzmann', 'Wien', 'acre', 'alpha',
+    'angstrom', 'arcmin', 'arcminute', 'arcsec',
+    'arcsecond', 'astronomical_unit', 'atm',
+    'atmosphere', 'atomic_mass', 'atto', 'au', 'bar',
+    'barrel', 'bbl', 'blob', 'c', 'calorie',
+    'calorie_IT', 'calorie_th', 'carat', 'centi',
+    'convert_temperature', 'day', 'deci', 'degree',
+    'degree_Fahrenheit', 'deka', 'dyn', 'dyne', 'e',
+    'eV', 'electron_mass', 'electron_volt',
+    'elementary_charge', 'epsilon_0', 'erg',
+    'exa', 'exbi', 'femto', 'fermi', 'fine_structure',
+    'fluid_ounce', 'fluid_ounce_US', 'fluid_ounce_imp',
+    'foot', 'g', 'gallon', 'gallon_US', 'gallon_imp',
+    'gas_constant', 'gibi', 'giga', 'golden', 'golden_ratio',
+    'grain', 'gram', 'gravitational_constant', 'h', 'hbar',
+    'hectare', 'hecto', 'horsepower', 'hour', 'hp',
+    'inch', 'k', 'kgf', 'kibi', 'kilo', 'kilogram_force',
+    'kmh', 'knot', 'lambda2nu', 'lb', 'lbf',
+    'light_year', 'liter', 'litre', 'long_ton', 'm_e',
+    'm_n', 'm_p', 'm_u', 'mach', 'mebi', 'mega',
+    'metric_ton', 'micro', 'micron', 'mil', 'mile',
+    'milli', 'minute', 'mmHg', 'mph', 'mu_0', 'nano',
+    'nautical_mile', 'neutron_mass', 'nu2lambda',
+    'ounce', 'oz', 'parsec', 'pebi', 'peta',
+    'pi', 'pico', 'point', 'pound', 'pound_force',
+    'proton_mass', 'psi', 'pt', 'quecto', 'quetta', 'ronna', 'ronto',
+    'short_ton', 'sigma', 'slinch', 'slug', 'speed_of_light',
+    'speed_of_sound', 'stone', 'survey_foot',
+    'survey_mile', 'tebi', 'tera', 'ton_TNT',
+    'torr', 'troy_ounce', 'troy_pound', 'u',
+    'week', 'yard', 'year', 'yobi', 'yocto',
+    'yotta', 'zebi', 'zepto', 'zero_Celsius', 'zetta'
+]
+
+
+# mathematical constants
+pi = _math.pi
+golden = golden_ratio = (1 + _math.sqrt(5)) / 2
+
+# SI prefixes
+quetta = 1e30
+ronna = 1e27
+yotta = 1e24
+zetta = 1e21
+exa = 1e18
+peta = 1e15
+tera = 1e12
+giga = 1e9
+mega = 1e6
+kilo = 1e3
+hecto = 1e2
+deka = 1e1
+deci = 1e-1
+centi = 1e-2
+milli = 1e-3
+micro = 1e-6
+nano = 1e-9
+pico = 1e-12
+femto = 1e-15
+atto = 1e-18
+zepto = 1e-21
+yocto = 1e-24
+ronto = 1e-27
+quecto = 1e-30
+
+# binary prefixes
+kibi = 2**10
+mebi = 2**20
+gibi = 2**30
+tebi = 2**40
+pebi = 2**50
+exbi = 2**60
+zebi = 2**70
+yobi = 2**80
+
+# physical constants
+c = speed_of_light = _cd('speed of light in vacuum')
+mu_0 = _cd('vacuum mag. permeability')
+epsilon_0 = _cd('vacuum electric permittivity')
+h = Planck = _cd('Planck constant')
+hbar = _cd('reduced Planck constant')
+G = gravitational_constant = _cd('Newtonian constant of gravitation')
+g = _cd('standard acceleration of gravity')
+e = elementary_charge = _cd('elementary charge')
+R = gas_constant = _cd('molar gas constant')
+alpha = fine_structure = _cd('fine-structure constant')
+N_A = Avogadro = _cd('Avogadro constant')
+k = Boltzmann = _cd('Boltzmann constant')
+sigma = Stefan_Boltzmann = _cd('Stefan-Boltzmann constant')
+Wien = _cd('Wien wavelength displacement law constant')
+Rydberg = _cd('Rydberg constant')
+
+# mass in kg
+gram = 1e-3
+metric_ton = 1e3
+grain = 64.79891e-6
+lb = pound = 7000 * grain  # avoirdupois
+blob = slinch = pound * g / 0.0254  # lbf*s**2/in (added in 1.0.0)
+slug = blob / 12  # lbf*s**2/foot (added in 1.0.0)
+oz = ounce = pound / 16
+stone = 14 * pound
+long_ton = 2240 * pound
+short_ton = 2000 * pound
+
+troy_ounce = 480 * grain  # only for metals / gems
+troy_pound = 12 * troy_ounce
+carat = 200e-6
+
+m_e = electron_mass = _cd('electron mass')
+m_p = proton_mass = _cd('proton mass')
+m_n = neutron_mass = _cd('neutron mass')
+m_u = u = atomic_mass = _cd('atomic mass constant')
+
+# angle in rad
+degree = pi / 180
+arcmin = arcminute = degree / 60
+arcsec = arcsecond = arcmin / 60
+
+# time in second
+minute = 60.0
+hour = 60 * minute
+day = 24 * hour
+week = 7 * day
+year = 365 * day
+Julian_year = 365.25 * day
+
+# length in meter
+inch = 0.0254
+foot = 12 * inch
+yard = 3 * foot
+mile = 1760 * yard
+mil = inch / 1000
+pt = point = inch / 72  # typography
+survey_foot = 1200.0 / 3937
+survey_mile = 5280 * survey_foot
+nautical_mile = 1852.0
+fermi = 1e-15
+angstrom = 1e-10
+micron = 1e-6
+au = astronomical_unit = 149597870700.0
+light_year = Julian_year * c
+parsec = au / arcsec
+
+# pressure in pascal
+atm = atmosphere = _cd('standard atmosphere')
+bar = 1e5
+torr = mmHg = atm / 760
+psi = pound * g / (inch * inch)
+
+# area in meter**2
+hectare = 1e4
+acre = 43560 * foot**2
+
+# volume in meter**3
+litre = liter = 1e-3
+gallon = gallon_US = 231 * inch**3  # US
+# pint = gallon_US / 8
+fluid_ounce = fluid_ounce_US = gallon_US / 128
+bbl = barrel = 42 * gallon_US  # for oil
+
+gallon_imp = 4.54609e-3  # UK
+fluid_ounce_imp = gallon_imp / 160
+
+# speed in meter per second
+kmh = 1e3 / hour
+mph = mile / hour
+# approx value of mach at 15 degrees in 1 atm. Is this a common value?
+mach = speed_of_sound = 340.5
+knot = nautical_mile / hour
+
+# temperature in kelvin
+zero_Celsius = 273.15
+degree_Fahrenheit = 1/1.8  # only for differences
+
+# energy in joule
+eV = electron_volt = elementary_charge  # * 1 Volt
+calorie = calorie_th = 4.184
+calorie_IT = 4.1868
+erg = 1e-7
+Btu_th = pound * degree_Fahrenheit * calorie_th / gram
+Btu = Btu_IT = pound * degree_Fahrenheit * calorie_IT / gram
+ton_TNT = 1e9 * calorie_th
+# Wh = watt_hour
+
+# power in watt
+hp = horsepower = 550 * foot * pound * g
+
+# force in newton
+dyn = dyne = 1e-5
+lbf = pound_force = pound * g
+kgf = kilogram_force = g  # * 1 kg
+
+# functions for conversions that are not linear
+
+
+@xp_capabilities()
+def convert_temperature(
+    val: "npt.ArrayLike",
+    old_scale: str,
+    new_scale: str,
+) -> Any:
+    """
+    Convert from a temperature scale to another one among Celsius, Kelvin,
+    Fahrenheit, and Rankine scales.
+
+    Parameters
+    ----------
+    val : array_like
+        Value(s) of the temperature(s) to be converted expressed in the
+        original scale.
+    old_scale : str
+        Specifies as a string the original scale from which the temperature
+        value(s) will be converted. Supported scales are Celsius ('Celsius',
+        'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'),
+        Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f'), and Rankine
+        ('Rankine', 'rankine', 'R', 'r').
+    new_scale : str
+        Specifies as a string the new scale to which the temperature
+        value(s) will be converted. Supported scales are Celsius ('Celsius',
+        'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'),
+        Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f'), and Rankine
+        ('Rankine', 'rankine', 'R', 'r').
+
+    Returns
+    -------
+    res : float or array of floats
+        Value(s) of the converted temperature(s) expressed in the new scale.
+
+    Notes
+    -----
+    .. versionadded:: 0.18.0
+
+    Examples
+    --------
+    >>> from scipy.constants import convert_temperature
+    >>> import numpy as np
+    >>> convert_temperature(np.array([-40, 40]), 'Celsius', 'Kelvin')
+    array([ 233.15,  313.15])
+
+    """
+    xp = array_namespace(val)
+    _val = _asarray(val, xp=xp, subok=True)
+    # Convert from `old_scale` to Kelvin
+    if old_scale.lower() in ['celsius', 'c']:
+        tempo = _val + zero_Celsius
+    elif old_scale.lower() in ['kelvin', 'k']:
+        tempo = _val
+    elif old_scale.lower() in ['fahrenheit', 'f']:
+        tempo = (_val - 32) * 5 / 9 + zero_Celsius
+    elif old_scale.lower() in ['rankine', 'r']:
+        tempo = _val * 5 / 9
+    else:
+        raise NotImplementedError(f"{old_scale=} is unsupported: supported scales "
+                                   "are Celsius, Kelvin, Fahrenheit, and "
+                                   "Rankine")
+    # and from Kelvin to `new_scale`.
+    if new_scale.lower() in ['celsius', 'c']:
+        res = tempo - zero_Celsius
+    elif new_scale.lower() in ['kelvin', 'k']:
+        res = tempo
+    elif new_scale.lower() in ['fahrenheit', 'f']:
+        res = (tempo - zero_Celsius) * 9 / 5 + 32
+    elif new_scale.lower() in ['rankine', 'r']:
+        res = tempo * 9 / 5
+    else:
+        raise NotImplementedError(f"{new_scale=} is unsupported: supported "
+                                   "scales are 'Celsius', 'Kelvin', "
+                                   "'Fahrenheit', and 'Rankine'")
+
+    return res
+
+
+# optics
+
+
+@xp_capabilities()
+def lambda2nu(lambda_: "npt.ArrayLike") -> Any:
+    """
+    Convert wavelength to optical frequency
+
+    Parameters
+    ----------
+    lambda_ : array_like
+        Wavelength(s) to be converted.
+
+    Returns
+    -------
+    nu : float or array of floats
+        Equivalent optical frequency.
+
+    Notes
+    -----
+    Computes ``nu = c / lambda`` where c = 299792458.0, i.e., the
+    (vacuum) speed of light in meters/second.
+
+    Examples
+    --------
+    >>> from scipy.constants import lambda2nu, speed_of_light
+    >>> import numpy as np
+    >>> lambda2nu(np.array((1, speed_of_light)))
+    array([  2.99792458e+08,   1.00000000e+00])
+
+    """
+    xp = array_namespace(lambda_)
+    return c / _asarray(lambda_, xp=xp, subok=True)
+
+
+@xp_capabilities()
+def nu2lambda(nu: "npt.ArrayLike") -> Any:
+    """
+    Convert optical frequency to wavelength.
+
+    Parameters
+    ----------
+    nu : array_like
+        Optical frequency to be converted.
+
+    Returns
+    -------
+    lambda : float or array of floats
+        Equivalent wavelength(s).
+
+    Notes
+    -----
+    Computes ``lambda = c / nu`` where c = 299792458.0, i.e., the
+    (vacuum) speed of light in meters/second.
+
+    Examples
+    --------
+    >>> from scipy.constants import nu2lambda, speed_of_light
+    >>> import numpy as np
+    >>> nu2lambda(np.array((1, speed_of_light)))
+    array([  2.99792458e+08,   1.00000000e+00])
+
+    """
+    xp = array_namespace(nu)
+    return c / _asarray(nu, xp=xp, subok=True)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/constants/codata.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/constants/codata.py
new file mode 100644
index 0000000000000000000000000000000000000000..912e0bbf7c4f14d23ced4546b6704f7789996d97
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/constants/codata.py
@@ -0,0 +1,21 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.constants` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'physical_constants', 'value', 'unit', 'precision', 'find',
+    'ConstantWarning', 'k', 'c',
+
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="constants", module="codata",
+                                   private_modules=["_codata"], all=__all__,
+                                   attribute=name)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/constants/constants.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/constants/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..855901ba802881090b99b7e8972de741331c7ab9
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/constants/constants.py
@@ -0,0 +1,53 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.constants` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'Avogadro', 'Boltzmann', 'Btu', 'Btu_IT', 'Btu_th', 'G',
+    'Julian_year', 'N_A', 'Planck', 'R', 'Rydberg',
+    'Stefan_Boltzmann', 'Wien', 'acre', 'alpha',
+    'angstrom', 'arcmin', 'arcminute', 'arcsec',
+    'arcsecond', 'astronomical_unit', 'atm',
+    'atmosphere', 'atomic_mass', 'atto', 'au', 'bar',
+    'barrel', 'bbl', 'blob', 'c', 'calorie',
+    'calorie_IT', 'calorie_th', 'carat', 'centi',
+    'convert_temperature', 'day', 'deci', 'degree',
+    'degree_Fahrenheit', 'deka', 'dyn', 'dyne', 'e',
+    'eV', 'electron_mass', 'electron_volt',
+    'elementary_charge', 'epsilon_0', 'erg',
+    'exa', 'exbi', 'femto', 'fermi', 'fine_structure',
+    'fluid_ounce', 'fluid_ounce_US', 'fluid_ounce_imp',
+    'foot', 'g', 'gallon', 'gallon_US', 'gallon_imp',
+    'gas_constant', 'gibi', 'giga', 'golden', 'golden_ratio',
+    'grain', 'gram', 'gravitational_constant', 'h', 'hbar',
+    'hectare', 'hecto', 'horsepower', 'hour', 'hp',
+    'inch', 'k', 'kgf', 'kibi', 'kilo', 'kilogram_force',
+    'kmh', 'knot', 'lambda2nu', 'lb', 'lbf',
+    'light_year', 'liter', 'litre', 'long_ton', 'm_e',
+    'm_n', 'm_p', 'm_u', 'mach', 'mebi', 'mega',
+    'metric_ton', 'micro', 'micron', 'mil', 'mile',
+    'milli', 'minute', 'mmHg', 'mph', 'mu_0', 'nano',
+    'nautical_mile', 'neutron_mass', 'nu2lambda',
+    'ounce', 'oz', 'parsec', 'pebi', 'peta',
+    'pi', 'pico', 'point', 'pound', 'pound_force',
+    'proton_mass', 'psi', 'pt', 'short_ton',
+    'sigma', 'slinch', 'slug', 'speed_of_light',
+    'speed_of_sound', 'stone', 'survey_foot',
+    'survey_mile', 'tebi', 'tera', 'ton_TNT',
+    'torr', 'troy_ounce', 'troy_pound', 'u',
+    'week', 'yard', 'year', 'yobi', 'yocto',
+    'yotta', 'zebi', 'zepto', 'zero_Celsius', 'zetta'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="constants", module="constants",
+                                   private_modules=["_constants"], all=__all__,
+                                   attribute=name)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdd4ffebec4c57f6d399a0f76df2b66056f0b225
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/__init__.py
@@ -0,0 +1,90 @@
+"""
+================================
+Datasets (:mod:`scipy.datasets`)
+================================
+
+.. currentmodule:: scipy.datasets
+
+Dataset Methods
+===============
+
+.. autosummary::
+   :toctree: generated/
+
+   ascent
+   face
+   electrocardiogram
+
+Utility Methods
+===============
+
+.. autosummary::
+   :toctree: generated/
+
+   download_all    -- Download all the dataset files to specified path.
+   clear_cache     -- Clear cached dataset directory.
+
+
+Usage of Datasets
+=================
+
+SciPy dataset methods can be simply called as follows: ``'()'``
+This downloads the dataset files over the network once, and saves the cache,
+before returning a `numpy.ndarray` object representing the dataset.
+
+Note that the return data structure and data type might be different for
+different dataset methods. For a more detailed example on usage, please look
+into the particular dataset method documentation above.
+
+
+How dataset retrieval and storage works
+=======================================
+
+SciPy dataset files are stored within individual GitHub repositories under the
+SciPy GitHub organization, following a naming convention as
+``'dataset-'``, for example `scipy.datasets.face` files live at
+https://github.com/scipy/dataset-face.  The `scipy.datasets` submodule utilizes
+and depends on `Pooch `_, a Python
+package built to simplify fetching data files. Pooch uses these repos to
+retrieve the respective dataset files when calling the dataset function.
+
+A registry of all the datasets, essentially a mapping of filenames with their
+SHA256 hash and repo urls are maintained, which Pooch uses to handle and verify
+the downloads on function call. After downloading the dataset once, the files
+are saved in the system cache directory under ``'scipy-data'``.
+
+Dataset cache locations may vary on different platforms.
+
+For macOS::
+
+    '~/Library/Caches/scipy-data'
+
+For Linux and other Unix-like platforms::
+
+    '~/.cache/scipy-data'  # or the value of the XDG_CACHE_HOME env var, if defined
+
+For Windows::
+
+    'C:\\Users\\\\AppData\\Local\\\\scipy-data\\Cache'
+
+
+In environments with constrained network connectivity for various security
+reasons or on systems without continuous internet connections, one may manually
+load the cache of the datasets by placing the contents of the dataset repo in
+the above mentioned cache directory to avoid fetching dataset errors without
+the internet connectivity.
+
+"""
+
+
+from ._fetchers import face, ascent, electrocardiogram
+from ._download_all import download_all
+from ._utils import clear_cache
+
+__all__ = ['ascent', 'electrocardiogram', 'face',
+           'download_all', 'clear_cache']
+
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/_download_all.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/_download_all.py
new file mode 100644
index 0000000000000000000000000000000000000000..2559a0cf645db5d8d68294e58a09270d3969df8a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/_download_all.py
@@ -0,0 +1,71 @@
+"""
+Platform independent script to download all the
+`scipy.datasets` module data files.
+This doesn't require a full scipy build.
+
+Run: python _download_all.py 
+"""
+
+import argparse
+try:
+    import pooch
+except ImportError:
+    pooch = None
+
+
+if __package__ is None or __package__ == '':
+    # Running as python script, use absolute import
+    import _registry  # type: ignore
+else:
+    # Running as python module, use relative import
+    from . import _registry
+
+
+def download_all(path=None):
+    """
+    Utility method to download all the dataset files
+    for `scipy.datasets` module.
+
+    Parameters
+    ----------
+    path : str, optional
+        Directory path to download all the dataset files.
+        If None, default to the system cache_dir detected by pooch.
+    
+    Examples
+    --------
+    Download the datasets to the default cache location:
+
+    >>> from scipy import datasets
+    >>> datasets.download_all()
+
+    Download the datasets to the current directory:
+
+    >>> datasets.download_all(".")
+    
+    """
+    if pooch is None:
+        raise ImportError("Missing optional dependency 'pooch' required "
+                          "for scipy.datasets module. Please use pip or "
+                          "conda to install 'pooch'.")
+    if path is None:
+        path = pooch.os_cache('scipy-data')
+    # https://github.com/scipy/scipy/issues/21879
+    downloader = pooch.HTTPDownloader(headers={"User-Agent": "SciPy"})
+    for dataset_name, dataset_hash in _registry.registry.items():
+        pooch.retrieve(url=_registry.registry_urls[dataset_name],
+                       known_hash=dataset_hash,
+                       fname=dataset_name, path=path, downloader=downloader)
+
+
+def main():
+    parser = argparse.ArgumentParser(description='Download SciPy data files.')
+    parser.add_argument("path", nargs='?', type=str,
+                        default=pooch.os_cache('scipy-data'),
+                        help="Directory path to download all the data files.")
+    args = parser.parse_args()
+    download_all(args.path)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/_fetchers.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/_fetchers.py
new file mode 100644
index 0000000000000000000000000000000000000000..15c3f3cceab5fa2e4ce2513af3cab4fd75b84965
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/_fetchers.py
@@ -0,0 +1,225 @@
+import sys
+
+from numpy import array, frombuffer, load
+from ._registry import registry, registry_urls
+
+try:
+    import pooch
+except ImportError:
+    pooch = None
+    data_fetcher = None
+else:
+    data_fetcher = pooch.create(
+        # Use the default cache folder for the operating system
+        # Pooch uses appdirs (https://github.com/ActiveState/appdirs) to
+        # select an appropriate directory for the cache on each platform.
+        path=pooch.os_cache("scipy-data"),
+
+        # The remote data is on Github
+        # base_url is a required param, even though we override this
+        # using individual urls in the registry.
+        base_url="https://github.com/scipy/",
+        registry=registry,
+        urls=registry_urls
+    )
+
+
+def fetch_data(dataset_name, data_fetcher=data_fetcher):
+    if data_fetcher is None:
+        raise ImportError("Missing optional dependency 'pooch' required "
+                          "for scipy.datasets module. Please use pip or "
+                          "conda to install 'pooch'.")
+    # https://github.com/scipy/scipy/issues/21879
+    downloader = pooch.HTTPDownloader(
+        headers={"User-Agent": f"SciPy {sys.modules['scipy'].__version__}"}
+    )
+    # The "fetch" method returns the full path to the downloaded data file.
+    return data_fetcher.fetch(dataset_name, downloader=downloader)
+
+
+def ascent():
+    """
+    Get an 8-bit grayscale bit-depth, 512 x 512 derived image for easy
+    use in demos.
+
+    The image is derived from
+    https://pixnio.com/people/accent-to-the-top
+
+    Parameters
+    ----------
+    None
+
+    Returns
+    -------
+    ascent : ndarray
+       convenient image to use for testing and demonstration
+
+    Examples
+    --------
+    >>> import scipy.datasets
+    >>> ascent = scipy.datasets.ascent()
+    >>> ascent.shape
+    (512, 512)
+    >>> ascent.max()
+    np.uint8(255)
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.gray()
+    >>> plt.imshow(ascent)
+    >>> plt.show()
+
+    """
+    import pickle
+
+    # The file will be downloaded automatically the first time this is run,
+    # returning the path to the downloaded file. Afterwards, Pooch finds
+    # it in the local cache and doesn't repeat the download.
+    fname = fetch_data("ascent.dat")
+    # Now we just need to load it with our standard Python tools.
+    with open(fname, 'rb') as f:
+        ascent = array(pickle.load(f))
+    return ascent
+
+
+def electrocardiogram():
+    """
+    Load an electrocardiogram as an example for a 1-D signal.
+
+    The returned signal is a 5 minute long electrocardiogram (ECG), a medical
+    recording of the heart's electrical activity, sampled at 360 Hz.
+
+    Returns
+    -------
+    ecg : ndarray
+        The electrocardiogram in millivolt (mV) sampled at 360 Hz.
+
+    Notes
+    -----
+    The provided signal is an excerpt (19:35 to 24:35) from the `record 208`_
+    (lead MLII) provided by the MIT-BIH Arrhythmia Database [1]_ on
+    PhysioNet [2]_. The excerpt includes noise induced artifacts, typical
+    heartbeats as well as pathological changes.
+
+    .. _record 208: https://physionet.org/physiobank/database/html/mitdbdir/records.htm#208
+
+    .. versionadded:: 1.1.0
+
+    References
+    ----------
+    .. [1] Moody GB, Mark RG. The impact of the MIT-BIH Arrhythmia Database.
+           IEEE Eng in Med and Biol 20(3):45-50 (May-June 2001).
+           (PMID: 11446209); :doi:`10.13026/C2F305`
+    .. [2] Goldberger AL, Amaral LAN, Glass L, Hausdorff JM, Ivanov PCh,
+           Mark RG, Mietus JE, Moody GB, Peng C-K, Stanley HE. PhysioBank,
+           PhysioToolkit, and PhysioNet: Components of a New Research Resource
+           for Complex Physiologic Signals. Circulation 101(23):e215-e220;
+           :doi:`10.1161/01.CIR.101.23.e215`
+
+    Examples
+    --------
+    >>> from scipy.datasets import electrocardiogram
+    >>> ecg = electrocardiogram()
+    >>> ecg
+    array([-0.245, -0.215, -0.185, ..., -0.405, -0.395, -0.385], shape=(108000,))
+    >>> ecg.shape, ecg.mean(), ecg.std()
+    ((108000,), -0.16510875, 0.5992473991177294)
+
+    As stated the signal features several areas with a different morphology.
+    E.g., the first few seconds show the electrical activity of a heart in
+    normal sinus rhythm as seen below.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> fs = 360
+    >>> time = np.arange(ecg.size) / fs
+    >>> plt.plot(time, ecg)
+    >>> plt.xlabel("time in s")
+    >>> plt.ylabel("ECG in mV")
+    >>> plt.xlim(9, 10.2)
+    >>> plt.ylim(-1, 1.5)
+    >>> plt.show()
+
+    After second 16, however, the first premature ventricular contractions,
+    also called extrasystoles, appear. These have a different morphology
+    compared to typical heartbeats. The difference can easily be observed
+    in the following plot.
+
+    >>> plt.plot(time, ecg)
+    >>> plt.xlabel("time in s")
+    >>> plt.ylabel("ECG in mV")
+    >>> plt.xlim(46.5, 50)
+    >>> plt.ylim(-2, 1.5)
+    >>> plt.show()
+
+    At several points large artifacts disturb the recording, e.g.:
+
+    >>> plt.plot(time, ecg)
+    >>> plt.xlabel("time in s")
+    >>> plt.ylabel("ECG in mV")
+    >>> plt.xlim(207, 215)
+    >>> plt.ylim(-2, 3.5)
+    >>> plt.show()
+
+    Finally, examining the power spectrum reveals that most of the biosignal is
+    made up of lower frequencies. At 60 Hz the noise induced by the mains
+    electricity can be clearly observed.
+
+    >>> from scipy.signal import welch
+    >>> f, Pxx = welch(ecg, fs=fs, nperseg=2048, scaling="spectrum")
+    >>> plt.semilogy(f, Pxx)
+    >>> plt.xlabel("Frequency in Hz")
+    >>> plt.ylabel("Power spectrum of the ECG in mV**2")
+    >>> plt.xlim(f[[0, -1]])
+    >>> plt.show()
+    """
+    fname = fetch_data("ecg.dat")
+    with load(fname) as file:
+        ecg = file["ecg"].astype(int)  # np.uint16 -> int
+    # Convert raw output of ADC to mV: (ecg - adc_zero) / adc_gain
+    ecg = (ecg - 1024) / 200.0
+    return ecg
+
+
+def face(gray=False):
+    """
+    Get a 1024 x 768, color image of a raccoon face.
+
+    The image is derived from
+    https://pixnio.com/fauna-animals/raccoons/raccoon-procyon-lotor
+
+    Parameters
+    ----------
+    gray : bool, optional
+        If True return 8-bit grey-scale image, otherwise return a color image
+
+    Returns
+    -------
+    face : ndarray
+        image of a raccoon face
+
+    Examples
+    --------
+    >>> import scipy.datasets
+    >>> face = scipy.datasets.face()
+    >>> face.shape
+    (768, 1024, 3)
+    >>> face.max()
+    np.uint8(255)
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.gray()
+    >>> plt.imshow(face)
+    >>> plt.show()
+
+    """
+    import bz2
+    fname = fetch_data("face.dat")
+    with open(fname, 'rb') as f:
+        rawdata = f.read()
+    face_data = bz2.decompress(rawdata)
+    face = frombuffer(face_data, dtype='uint8')
+    face.shape = (768, 1024, 3)
+    if gray is True:
+        face = (0.21 * face[:, :, 0] + 0.71 * face[:, :, 1] +
+                0.07 * face[:, :, 2]).astype('uint8')
+    return face
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/_registry.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/_registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..969384ad9843159e766100bfa9755aed8102dd09
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/_registry.py
@@ -0,0 +1,26 @@
+##########################################################################
+# This file serves as the dataset registry for SciPy Datasets SubModule.
+##########################################################################
+
+
+# To generate the SHA256 hash, use the command
+# openssl sha256 
+registry = {
+    "ascent.dat": "03ce124c1afc880f87b55f6b061110e2e1e939679184f5614e38dacc6c1957e2",
+    "ecg.dat": "f20ad3365fb9b7f845d0e5c48b6fe67081377ee466c3a220b7f69f35c8958baf",
+    "face.dat": "9d8b0b4d081313e2b485748c770472e5a95ed1738146883d84c7030493e82886"
+}
+
+registry_urls = {
+    "ascent.dat": "https://raw.githubusercontent.com/scipy/dataset-ascent/main/ascent.dat",
+    "ecg.dat": "https://raw.githubusercontent.com/scipy/dataset-ecg/main/ecg.dat",
+    "face.dat": "https://raw.githubusercontent.com/scipy/dataset-face/main/face.dat"
+}
+
+# dataset method mapping with their associated filenames
+#  : ["filename1", "filename2", ...]
+method_files_map = {
+    "ascent": ["ascent.dat"],
+    "electrocardiogram": ["ecg.dat"],
+    "face": ["face.dat"]
+}
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/_utils.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab6ae22a191a896ce8c65394433c9a6b0148f599
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/datasets/_utils.py
@@ -0,0 +1,81 @@
+import os
+import shutil
+from ._registry import method_files_map
+
+try:
+    import platformdirs
+except ImportError:
+    platformdirs = None  # type: ignore[assignment]
+
+
+def _clear_cache(datasets, cache_dir=None, method_map=None):
+    if method_map is None:
+        # Use SciPy Datasets method map
+        method_map = method_files_map
+    if cache_dir is None:
+        # Use default cache_dir path
+        if platformdirs is None:
+            # platformdirs is pooch dependency
+            raise ImportError("Missing optional dependency 'pooch' required "
+                              "for scipy.datasets module. Please use pip or "
+                              "conda to install 'pooch'.")
+        cache_dir = platformdirs.user_cache_dir("scipy-data")
+
+    if not os.path.exists(cache_dir):
+        print(f"Cache Directory {cache_dir} doesn't exist. Nothing to clear.")
+        return
+
+    if datasets is None:
+        print(f"Cleaning the cache directory {cache_dir}!")
+        shutil.rmtree(cache_dir)
+    else:
+        if not isinstance(datasets, list | tuple):
+            # single dataset method passed should be converted to list
+            datasets = [datasets, ]
+        for dataset in datasets:
+            assert callable(dataset)
+            dataset_name = dataset.__name__  # Name of the dataset method
+            if dataset_name not in method_map:
+                raise ValueError(f"Dataset method {dataset_name} doesn't "
+                                 "exist. Please check if the passed dataset "
+                                 "is a subset of the following dataset "
+                                 f"methods: {list(method_map.keys())}")
+
+            data_files = method_map[dataset_name]
+            data_filepaths = [os.path.join(cache_dir, file)
+                              for file in data_files]
+            for data_filepath in data_filepaths:
+                if os.path.exists(data_filepath):
+                    print("Cleaning the file "
+                          f"{os.path.split(data_filepath)[1]} "
+                          f"for dataset {dataset_name}")
+                    os.remove(data_filepath)
+                else:
+                    print(f"Path {data_filepath} doesn't exist. "
+                          "Nothing to clear.")
+
+
+def clear_cache(datasets=None):
+    """
+    Cleans the scipy datasets cache directory.
+
+    If a scipy.datasets method or a list/tuple of the same is
+    provided, then clear_cache removes all the data files
+    associated to the passed dataset method callable(s).
+
+    By default, it removes all the cached data files.
+
+    Parameters
+    ----------
+    datasets : callable or list/tuple of callable or None
+
+    Examples
+    --------
+    >>> from scipy import datasets
+    >>> ascent_array = datasets.ascent()
+    >>> ascent_array.shape
+    (512, 512)
+    >>> datasets.clear_cache([datasets.ascent])
+    Cleaning the file ascent.dat for dataset ascent
+    """
+    _clear_cache(datasets)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/differentiate/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/differentiate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3a7ccc4b33f27dbae7958641a89106cf9580326
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/differentiate/__init__.py
@@ -0,0 +1,27 @@
+"""
+==============================================================
+Finite Difference Differentiation (:mod:`scipy.differentiate`)
+==============================================================
+
+.. currentmodule:: scipy.differentiate
+
+SciPy ``differentiate`` provides functions for performing finite difference
+numerical differentiation of black-box functions.
+
+.. autosummary::
+   :toctree: generated/
+
+   derivative
+   jacobian
+   hessian
+
+"""
+
+
+from ._differentiate import *
+
+__all__ = ['derivative', 'jacobian', 'hessian']
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/differentiate/_differentiate.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/differentiate/_differentiate.py
new file mode 100644
index 0000000000000000000000000000000000000000..44ac8400b090731df066286f2a203ad4566a14bb
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/differentiate/_differentiate.py
@@ -0,0 +1,1129 @@
+# mypy: disable-error-code="attr-defined"
+import warnings
+import numpy as np
+import scipy._lib._elementwise_iterative_method as eim
+from scipy._lib._util import _RichResult
+from scipy._lib._array_api import array_namespace, xp_copy, xp_promote
+import scipy._lib.array_api_extra as xpx
+
+_EERRORINCREASE = -1  # used in derivative
+
+def _derivative_iv(f, x, args, tolerances, maxiter, order, initial_step,
+                   step_factor, step_direction, preserve_shape, callback):
+    # Input validation for `derivative`
+    xp = array_namespace(x)
+
+    if not callable(f):
+        raise ValueError('`f` must be callable.')
+
+    if not np.iterable(args):
+        args = (args,)
+
+    tolerances = {} if tolerances is None else tolerances
+    atol = tolerances.get('atol', None)
+    rtol = tolerances.get('rtol', None)
+
+    # tolerances are floats, not arrays; OK to use NumPy
+    message = 'Tolerances and step parameters must be non-negative scalars.'
+    tols = np.asarray([atol if atol is not None else 1,
+                       rtol if rtol is not None else 1,
+                       step_factor])
+    if (not np.issubdtype(tols.dtype, np.number) or np.any(tols < 0)
+            or np.any(np.isnan(tols)) or tols.shape != (3,)):
+        raise ValueError(message)
+    step_factor = float(tols[2])
+
+    maxiter_int = int(maxiter)
+    if maxiter != maxiter_int or maxiter <= 0:
+        raise ValueError('`maxiter` must be a positive integer.')
+
+    order_int = int(order)
+    if order_int != order or order <= 0:
+        raise ValueError('`order` must be a positive integer.')
+
+    step_direction = xp.asarray(step_direction)
+    initial_step = xp.asarray(initial_step)
+    temp = xp.broadcast_arrays(x, step_direction, initial_step)
+    x, step_direction, initial_step = temp
+
+    message = '`preserve_shape` must be True or False.'
+    if preserve_shape not in {True, False}:
+        raise ValueError(message)
+
+    if callback is not None and not callable(callback):
+        raise ValueError('`callback` must be callable.')
+
+    return (f, x, args, atol, rtol, maxiter_int, order_int, initial_step,
+            step_factor, step_direction, preserve_shape, callback)
+
+
+def derivative(f, x, *, args=(), tolerances=None, maxiter=10,
+               order=8, initial_step=0.5, step_factor=2.0,
+               step_direction=0, preserve_shape=False, callback=None):
+    """Evaluate the derivative of a elementwise, real scalar function numerically.
+
+    For each element of the output of `f`, `derivative` approximates the first
+    derivative of `f` at the corresponding element of `x` using finite difference
+    differentiation.
+
+    This function works elementwise when `x`, `step_direction`, and `args` contain
+    (broadcastable) arrays.
+
+    Parameters
+    ----------
+    f : callable
+        The function whose derivative is desired. The signature must be::
+
+            f(xi: ndarray, *argsi) -> ndarray
+
+        where each element of ``xi`` is a finite real number and ``argsi`` is a tuple,
+        which may contain an arbitrary number of arrays that are broadcastable with
+        ``xi``. `f` must be an elementwise function: each scalar element ``f(xi)[j]``
+        must equal ``f(xi[j])`` for valid indices ``j``. It must not mutate the array
+        ``xi`` or the arrays in ``argsi``.
+    x : float array_like
+        Abscissae at which to evaluate the derivative. Must be broadcastable with
+        `args` and `step_direction`.
+    args : tuple of array_like, optional
+        Additional positional array arguments to be passed to `f`. Arrays
+        must be broadcastable with one another and the arrays of `init`.
+        If the callable for which the root is desired requires arguments that are
+        not broadcastable with `x`, wrap that callable with `f` such that `f`
+        accepts only `x` and broadcastable ``*args``.
+    tolerances : dictionary of floats, optional
+        Absolute and relative tolerances. Valid keys of the dictionary are:
+
+        - ``atol`` - absolute tolerance on the derivative
+        - ``rtol`` - relative tolerance on the derivative
+
+        Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
+        `atol` is the smallest normal number of the appropriate dtype, and
+        the default `rtol` is the square root of the precision of the
+        appropriate dtype.
+    order : int, default: 8
+        The (positive integer) order of the finite difference formula to be
+        used. Odd integers will be rounded up to the next even integer.
+    initial_step : float array_like, default: 0.5
+        The (absolute) initial step size for the finite difference derivative
+        approximation.
+    step_factor : float, default: 2.0
+        The factor by which the step size is *reduced* in each iteration; i.e.
+        the step size in iteration 1 is ``initial_step/step_factor``. If
+        ``step_factor < 1``, subsequent steps will be greater than the initial
+        step; this may be useful if steps smaller than some threshold are
+        undesirable (e.g. due to subtractive cancellation error).
+    maxiter : int, default: 10
+        The maximum number of iterations of the algorithm to perform. See
+        Notes.
+    step_direction : integer array_like
+        An array representing the direction of the finite difference steps (for
+        use when `x` lies near to the boundary of the domain of the function.)
+        Must be broadcastable with `x` and all `args`.
+        Where 0 (default), central differences are used; where negative (e.g.
+        -1), steps are non-positive; and where positive (e.g. 1), all steps are
+        non-negative.
+    preserve_shape : bool, default: False
+        In the following, "arguments of `f`" refers to the array ``xi`` and
+        any arrays within ``argsi``. Let ``shape`` be the broadcasted shape
+        of `x` and all elements of `args` (which is conceptually
+        distinct from ``xi` and ``argsi`` passed into `f`).
+
+        - When ``preserve_shape=False`` (default), `f` must accept arguments
+          of *any* broadcastable shapes.
+
+        - When ``preserve_shape=True``, `f` must accept arguments of shape
+          ``shape`` *or* ``shape + (n,)``, where ``(n,)`` is the number of
+          abscissae at which the function is being evaluated.
+
+        In either case, for each scalar element ``xi[j]`` within ``xi``, the array
+        returned by `f` must include the scalar ``f(xi[j])`` at the same index.
+        Consequently, the shape of the output is always the shape of the input
+        ``xi``.
+
+        See Examples.
+    callback : callable, optional
+        An optional user-supplied function to be called before the first
+        iteration and after each iteration.
+        Called as ``callback(res)``, where ``res`` is a ``_RichResult``
+        similar to that returned by `derivative` (but containing the current
+        iterate's values of all variables). If `callback` raises a
+        ``StopIteration``, the algorithm will terminate immediately and
+        `derivative` will return a result. `callback` must not mutate
+        `res` or its attributes.
+
+    Returns
+    -------
+    res : _RichResult
+        An object similar to an instance of `scipy.optimize.OptimizeResult` with the
+        following attributes. The descriptions are written as though the values will
+        be scalars; however, if `f` returns an array, the outputs will be
+        arrays of the same shape.
+
+        success : bool array
+            ``True`` where the algorithm terminated successfully (status ``0``);
+            ``False`` otherwise.
+        status : int array
+            An integer representing the exit status of the algorithm.
+
+            - ``0`` : The algorithm converged to the specified tolerances.
+            - ``-1`` : The error estimate increased, so iteration was terminated.
+            - ``-2`` : The maximum number of iterations was reached.
+            - ``-3`` : A non-finite value was encountered.
+            - ``-4`` : Iteration was terminated by `callback`.
+            - ``1`` : The algorithm is proceeding normally (in `callback` only).
+
+        df : float array
+            The derivative of `f` at `x`, if the algorithm terminated
+            successfully.
+        error : float array
+            An estimate of the error: the magnitude of the difference between
+            the current estimate of the derivative and the estimate in the
+            previous iteration.
+        nit : int array
+            The number of iterations of the algorithm that were performed.
+        nfev : int array
+            The number of points at which `f` was evaluated.
+        x : float array
+            The value at which the derivative of `f` was evaluated
+            (after broadcasting with `args` and `step_direction`).
+
+    See Also
+    --------
+    jacobian, hessian
+
+    Notes
+    -----
+    The implementation was inspired by jacobi [1]_, numdifftools [2]_, and
+    DERIVEST [3]_, but the implementation follows the theory of Taylor series
+    more straightforwardly (and arguably naively so).
+    In the first iteration, the derivative is estimated using a finite
+    difference formula of order `order` with maximum step size `initial_step`.
+    Each subsequent iteration, the maximum step size is reduced by
+    `step_factor`, and the derivative is estimated again until a termination
+    condition is reached. The error estimate is the magnitude of the difference
+    between the current derivative approximation and that of the previous
+    iteration.
+
+    The stencils of the finite difference formulae are designed such that
+    abscissae are "nested": after `f` is evaluated at ``order + 1``
+    points in the first iteration, `f` is evaluated at only two new points
+    in each subsequent iteration; ``order - 1`` previously evaluated function
+    values required by the finite difference formula are reused, and two
+    function values (evaluations at the points furthest from `x`) are unused.
+
+    Step sizes are absolute. When the step size is small relative to the
+    magnitude of `x`, precision is lost; for example, if `x` is ``1e20``, the
+    default initial step size of ``0.5`` cannot be resolved. Accordingly,
+    consider using larger initial step sizes for large magnitudes of `x`.
+
+    The default tolerances are challenging to satisfy at points where the
+    true derivative is exactly zero. If the derivative may be exactly zero,
+    consider specifying an absolute tolerance (e.g. ``atol=1e-12``) to
+    improve convergence.
+
+    References
+    ----------
+    .. [1] Hans Dembinski (@HDembinski). jacobi.
+           https://github.com/HDembinski/jacobi
+    .. [2] Per A. Brodtkorb and John D'Errico. numdifftools.
+           https://numdifftools.readthedocs.io/en/latest/
+    .. [3] John D'Errico. DERIVEST: Adaptive Robust Numerical Differentiation.
+           https://www.mathworks.com/matlabcentral/fileexchange/13490-adaptive-robust-numerical-differentiation
+    .. [4] Numerical Differentition. Wikipedia.
+           https://en.wikipedia.org/wiki/Numerical_differentiation
+
+    Examples
+    --------
+    Evaluate the derivative of ``np.exp`` at several points ``x``.
+
+    >>> import numpy as np
+    >>> from scipy.differentiate import derivative
+    >>> f = np.exp
+    >>> df = np.exp  # true derivative
+    >>> x = np.linspace(1, 2, 5)
+    >>> res = derivative(f, x)
+    >>> res.df  # approximation of the derivative
+    array([2.71828183, 3.49034296, 4.48168907, 5.75460268, 7.3890561 ])
+    >>> res.error  # estimate of the error
+    array([7.13740178e-12, 9.16600129e-12, 1.17594823e-11, 1.51061386e-11,
+           1.94262384e-11])
+    >>> abs(res.df - df(x))  # true error
+    array([2.53130850e-14, 3.55271368e-14, 5.77315973e-14, 5.59552404e-14,
+           6.92779167e-14])
+
+    Show the convergence of the approximation as the step size is reduced.
+    Each iteration, the step size is reduced by `step_factor`, so for
+    sufficiently small initial step, each iteration reduces the error by a
+    factor of ``1/step_factor**order`` until finite precision arithmetic
+    inhibits further improvement.
+
+    >>> import matplotlib.pyplot as plt
+    >>> iter = list(range(1, 12))  # maximum iterations
+    >>> hfac = 2  # step size reduction per iteration
+    >>> hdir = [-1, 0, 1]  # compare left-, central-, and right- steps
+    >>> order = 4  # order of differentiation formula
+    >>> x = 1
+    >>> ref = df(x)
+    >>> errors = []  # true error
+    >>> for i in iter:
+    ...     res = derivative(f, x, maxiter=i, step_factor=hfac,
+    ...                      step_direction=hdir, order=order,
+    ...                      # prevent early termination
+    ...                      tolerances=dict(atol=0, rtol=0))
+    ...     errors.append(abs(res.df - ref))
+    >>> errors = np.array(errors)
+    >>> plt.semilogy(iter, errors[:, 0], label='left differences')
+    >>> plt.semilogy(iter, errors[:, 1], label='central differences')
+    >>> plt.semilogy(iter, errors[:, 2], label='right differences')
+    >>> plt.xlabel('iteration')
+    >>> plt.ylabel('error')
+    >>> plt.legend()
+    >>> plt.show()
+    >>> (errors[1, 1] / errors[0, 1], 1 / hfac**order)
+    (0.06215223140159822, 0.0625)
+
+    The implementation is vectorized over `x`, `step_direction`, and `args`.
+    The function is evaluated once before the first iteration to perform input
+    validation and standardization, and once per iteration thereafter.
+
+    >>> def f(x, p):
+    ...     f.nit += 1
+    ...     return x**p
+    >>> f.nit = 0
+    >>> def df(x, p):
+    ...     return p*x**(p-1)
+    >>> x = np.arange(1, 5)
+    >>> p = np.arange(1, 6).reshape((-1, 1))
+    >>> hdir = np.arange(-1, 2).reshape((-1, 1, 1))
+    >>> res = derivative(f, x, args=(p,), step_direction=hdir, maxiter=1)
+    >>> np.allclose(res.df, df(x, p))
+    True
+    >>> res.df.shape
+    (3, 5, 4)
+    >>> f.nit
+    2
+
+    By default, `preserve_shape` is False, and therefore the callable
+    `f` may be called with arrays of any broadcastable shapes.
+    For example:
+
+    >>> shapes = []
+    >>> def f(x, c):
+    ...    shape = np.broadcast_shapes(x.shape, c.shape)
+    ...    shapes.append(shape)
+    ...    return np.sin(c*x)
+    >>>
+    >>> c = [1, 5, 10, 20]
+    >>> res = derivative(f, 0, args=(c,))
+    >>> shapes
+    [(4,), (4, 8), (4, 2), (3, 2), (2, 2), (1, 2)]
+
+    To understand where these shapes are coming from - and to better
+    understand how `derivative` computes accurate results - note that
+    higher values of ``c`` correspond with higher frequency sinusoids.
+    The higher frequency sinusoids make the function's derivative change
+    faster, so more function evaluations are required to achieve the target
+    accuracy:
+
+    >>> res.nfev
+    array([11, 13, 15, 17], dtype=int32)
+
+    The initial ``shape``, ``(4,)``, corresponds with evaluating the
+    function at a single abscissa and all four frequencies; this is used
+    for input validation and to determine the size and dtype of the arrays
+    that store results. The next shape corresponds with evaluating the
+    function at an initial grid of abscissae and all four frequencies.
+    Successive calls to the function evaluate the function at two more
+    abscissae, increasing the effective order of the approximation by two.
+    However, in later function evaluations, the function is evaluated at
+    fewer frequencies because the corresponding derivative has already
+    converged to the required tolerance. This saves function evaluations to
+    improve performance, but it requires the function to accept arguments of
+    any shape.
+
+    "Vector-valued" functions are unlikely to satisfy this requirement.
+    For example, consider
+
+    >>> def f(x):
+    ...    return [x, np.sin(3*x), x+np.sin(10*x), np.sin(20*x)*(x-1)**2]
+
+    This integrand is not compatible with `derivative` as written; for instance,
+    the shape of the output will not be the same as the shape of ``x``. Such a
+    function *could* be converted to a compatible form with the introduction of
+    additional parameters, but this would be inconvenient. In such cases,
+    a simpler solution would be to use `preserve_shape`.
+
+    >>> shapes = []
+    >>> def f(x):
+    ...     shapes.append(x.shape)
+    ...     x0, x1, x2, x3 = x
+    ...     return [x0, np.sin(3*x1), x2+np.sin(10*x2), np.sin(20*x3)*(x3-1)**2]
+    >>>
+    >>> x = np.zeros(4)
+    >>> res = derivative(f, x, preserve_shape=True)
+    >>> shapes
+    [(4,), (4, 8), (4, 2), (4, 2), (4, 2), (4, 2)]
+
+    Here, the shape of ``x`` is ``(4,)``. With ``preserve_shape=True``, the
+    function may be called with argument ``x`` of shape ``(4,)`` or ``(4, n)``,
+    and this is what we observe.
+
+    """
+    # TODO (followup):
+    #  - investigate behavior at saddle points
+    #  - multivariate functions?
+    #  - relative steps?
+    #  - show example of `np.vectorize`
+
+    res = _derivative_iv(f, x, args, tolerances, maxiter, order, initial_step,
+                            step_factor, step_direction, preserve_shape, callback)
+    (func, x, args, atol, rtol, maxiter, order,
+     h0, fac, hdir, preserve_shape, callback) = res
+
+    # Initialization
+    # Since f(x) (no step) is not needed for central differences, it may be
+    # possible to eliminate this function evaluation. However, it's useful for
+    # input validation and standardization, and everything else is designed to
+    # reduce function calls, so let's keep it simple.
+    temp = eim._initialize(func, (x,), args, preserve_shape=preserve_shape)
+    func, xs, fs, args, shape, dtype, xp = temp
+
+    finfo = xp.finfo(dtype)
+    atol = finfo.smallest_normal if atol is None else atol
+    rtol = finfo.eps**0.5 if rtol is None else rtol  # keep same as `hessian`
+
+    x, f = xs[0], fs[0]
+    df = xp.full_like(f, xp.nan)
+
+    # Ideally we'd broadcast the shape of `hdir` in `_elementwise_algo_init`, but
+    # it's simpler to do it here than to generalize `_elementwise_algo_init` further.
+    # `hdir` and `x` are already broadcasted in `_derivative_iv`, so we know
+    # that `hdir` can be broadcasted to the final shape. Same with `h0`.
+    hdir = xp.broadcast_to(hdir, shape)
+    hdir = xp.reshape(hdir, (-1,))
+    hdir = xp.astype(xp.sign(hdir), dtype)
+    h0 = xp.broadcast_to(h0, shape)
+    h0 = xp.reshape(h0, (-1,))
+    h0 = xp.astype(h0, dtype)
+    h0 = xpx.at(h0)[h0 <= 0].set(xp.nan)
+
+    status = xp.full_like(x, eim._EINPROGRESS, dtype=xp.int32)  # in progress
+    nit, nfev = 0, 1  # one function evaluations performed above
+    # Boolean indices of left, central, right, and (all) one-sided steps
+    il = hdir < 0
+    ic = hdir == 0
+    ir = hdir > 0
+    io = il | ir
+
+    # Most of these attributes are reasonably obvious, but:
+    # - `fs` holds all the function values of all active `x`. The zeroth
+    #   axis corresponds with active points `x`, the first axis corresponds
+    #   with the different steps (in the order described in
+    #   `_derivative_weights`).
+    # - `terms` (which could probably use a better name) is half the `order`,
+    #   which is always even.
+    work = _RichResult(x=x, df=df, fs=f[:, xp.newaxis], error=xp.nan, h=h0,
+                       df_last=xp.nan, error_last=xp.nan, fac=fac,
+                       atol=atol, rtol=rtol, nit=nit, nfev=nfev,
+                       status=status, dtype=dtype, terms=(order+1)//2,
+                       hdir=hdir, il=il, ic=ic, ir=ir, io=io,
+                       # Store the weights in an object so they can't get compressed
+                       # Using RichResult to allow dot notation, but a dict would work
+                       diff_state=_RichResult(central=[], right=[], fac=None))
+
+    # This is the correspondence between terms in the `work` object and the
+    # final result. In this case, the mapping is trivial. Note that `success`
+    # is prepended automatically.
+    res_work_pairs = [('status', 'status'), ('df', 'df'), ('error', 'error'),
+                      ('nit', 'nit'), ('nfev', 'nfev'), ('x', 'x')]
+
+    def pre_func_eval(work):
+        """Determine the abscissae at which the function needs to be evaluated.
+
+        See `_derivative_weights` for a description of the stencil (pattern
+        of the abscissae).
+
+        In the first iteration, there is only one stored function value in
+        `work.fs`, `f(x)`, so we need to evaluate at `order` new points. In
+        subsequent iterations, we evaluate at two new points. Note that
+        `work.x` is always flattened into a 1D array after broadcasting with
+        all `args`, so we add a new axis at the end and evaluate all point
+        in one call to the function.
+
+        For improvement:
+        - Consider measuring the step size actually taken, since ``(x + h) - x``
+          is not identically equal to `h` with floating point arithmetic.
+        - Adjust the step size automatically if `x` is too big to resolve the
+          step.
+        - We could probably save some work if there are no central difference
+          steps or no one-sided steps.
+        """
+        n = work.terms  # half the order
+        h = work.h[:, xp.newaxis]  # step size
+        c = work.fac  # step reduction factor
+        d = c**0.5  # square root of step reduction factor (one-sided stencil)
+        # Note - no need to be careful about dtypes until we allocate `x_eval`
+
+        if work.nit == 0:
+            hc = h / c**xp.arange(n, dtype=work.dtype)
+            hc = xp.concat((-xp.flip(hc, axis=-1), hc), axis=-1)
+        else:
+            hc = xp.concat((-h, h), axis=-1) / c**(n-1)
+
+        if work.nit == 0:
+            hr = h / d**xp.arange(2*n, dtype=work.dtype)
+        else:
+            hr = xp.concat((h, h/d), axis=-1) / c**(n-1)
+
+        n_new = 2*n if work.nit == 0 else 2  # number of new abscissae
+        x_eval = xp.zeros((work.hdir.shape[0], n_new), dtype=work.dtype)
+        il, ic, ir = work.il, work.ic, work.ir
+        x_eval = xpx.at(x_eval)[ir].set(work.x[ir][:, xp.newaxis] + hr[ir])
+        x_eval = xpx.at(x_eval)[ic].set(work.x[ic][:, xp.newaxis] + hc[ic])
+        x_eval = xpx.at(x_eval)[il].set(work.x[il][:, xp.newaxis] - hr[il])
+        return x_eval
+
+    def post_func_eval(x, f, work):
+        """ Estimate the derivative and error from the function evaluations
+
+        As in `pre_func_eval`: in the first iteration, there is only one stored
+        function value in `work.fs`, `f(x)`, so we need to add the `order` new
+        points. In subsequent iterations, we add two new points. The tricky
+        part is getting the order to match that of the weights, which is
+        described in `_derivative_weights`.
+
+        For improvement:
+        - Change the order of the weights (and steps in `pre_func_eval`) to
+          simplify `work_fc` concatenation and eliminate `fc` concatenation.
+        - It would be simple to do one-step Richardson extrapolation with `df`
+          and `df_last` to increase the order of the estimate and/or improve
+          the error estimate.
+        - Process the function evaluations in a more numerically favorable
+          way. For instance, combining the pairs of central difference evals
+          into a second-order approximation and using Richardson extrapolation
+          to produce a higher order approximation seemed to retain accuracy up
+          to very high order.
+        - Alternatively, we could use `polyfit` like Jacobi. An advantage of
+          fitting polynomial to more points than necessary is improved noise
+          tolerance.
+        """
+        n = work.terms
+        n_new = n if work.nit == 0 else 1
+        il, ic, io = work.il, work.ic, work.io
+
+        # Central difference
+        # `work_fc` is *all* the points at which the function has been evaluated
+        # `fc` is the points we're using *this iteration* to produce the estimate
+        work_fc = (f[ic][:, :n_new], work.fs[ic], f[ic][:, -n_new:])
+        work_fc = xp.concat(work_fc, axis=-1)
+        if work.nit == 0:
+            fc = work_fc
+        else:
+            fc = (work_fc[:, :n], work_fc[:, n:n+1], work_fc[:, -n:])
+            fc = xp.concat(fc, axis=-1)
+
+        # One-sided difference
+        work_fo = xp.concat((work.fs[io], f[io]), axis=-1)
+        if work.nit == 0:
+            fo = work_fo
+        else:
+            fo = xp.concat((work_fo[:, 0:1], work_fo[:, -2*n:]), axis=-1)
+
+        work.fs = xp.zeros((ic.shape[0], work.fs.shape[-1] + 2*n_new), dtype=work.dtype)
+        work.fs = xpx.at(work.fs)[ic].set(work_fc)
+        work.fs = xpx.at(work.fs)[io].set(work_fo)
+
+        wc, wo = _derivative_weights(work, n, xp)
+        work.df_last = xp.asarray(work.df, copy=True)
+        work.df = xpx.at(work.df)[ic].set(fc @ wc / work.h[ic])
+        work.df = xpx.at(work.df)[io].set(fo @ wo / work.h[io])
+        work.df = xpx.at(work.df)[il].multiply(-1)
+
+        work.h /= work.fac
+        work.error_last = work.error
+        # Simple error estimate - the difference in derivative estimates between
+        # this iteration and the last. This is typically conservative because if
+        # convergence has begin, the true error is much closer to the difference
+        # between the current estimate and the *next* error estimate. However,
+        # we could use Richarson extrapolation to produce an error estimate that
+        # is one order higher, and take the difference between that and
+        # `work.df` (which would just be constant factor that depends on `fac`.)
+        work.error = xp.abs(work.df - work.df_last)
+
+    def check_termination(work):
+        """Terminate due to convergence, non-finite values, or error increase"""
+        stop = xp.astype(xp.zeros_like(work.df), xp.bool)
+
+        i = work.error < work.atol + work.rtol*abs(work.df)
+        work.status = xpx.at(work.status)[i].set(eim._ECONVERGED)
+        stop = xpx.at(stop)[i].set(True)
+
+        if work.nit > 0:
+            i = ~((xp.isfinite(work.x) & xp.isfinite(work.df)) | stop)
+            work.df = xpx.at(work.df)[i].set(xp.nan)
+            work.status = xpx.at(work.status)[i].set(eim._EVALUEERR)
+            stop = xpx.at(stop)[i].set(True)
+
+        # With infinite precision, there is a step size below which
+        # all smaller step sizes will reduce the error. But in floating point
+        # arithmetic, catastrophic cancellation will begin to cause the error
+        # to increase again. This heuristic tries to avoid step sizes that are
+        # too small. There may be more theoretically sound approaches for
+        # detecting a step size that minimizes the total error, but this
+        # heuristic seems simple and effective.
+        i = (work.error > work.error_last*10) & ~stop
+        work.status = xpx.at(work.status)[i].set(_EERRORINCREASE)
+        stop = xpx.at(stop)[i].set(True)
+
+        return stop
+
+    def post_termination_check(work):
+        return
+
+    def customize_result(res, shape):
+        return shape
+
+    return eim._loop(work, callback, shape, maxiter, func, args, dtype,
+                     pre_func_eval, post_func_eval, check_termination,
+                     post_termination_check, customize_result, res_work_pairs,
+                     xp, preserve_shape)
+
+
+def _derivative_weights(work, n, xp):
+    # This produces the weights of the finite difference formula for a given
+    # stencil. In experiments, use of a second-order central difference formula
+    # with Richardson extrapolation was more accurate numerically, but it was
+    # more complicated, and it would have become even more complicated when
+    # adding support for one-sided differences. However, now that all the
+    # function evaluation values are stored, they can be processed in whatever
+    # way is desired to produce the derivative estimate. We leave alternative
+    # approaches to future work. To be more self-contained, here is the theory
+    # for deriving the weights below.
+    #
+    # Recall that the Taylor expansion of a univariate, scalar-values function
+    # about a point `x` may be expressed as:
+    #      f(x + h)  =     f(x) + f'(x)*h + f''(x)/2!*h**2  + O(h**3)
+    # Suppose we evaluate f(x), f(x+h), and f(x-h).  We have:
+    #      f(x)      =     f(x)
+    #      f(x + h)  =     f(x) + f'(x)*h + f''(x)/2!*h**2  + O(h**3)
+    #      f(x - h)  =     f(x) - f'(x)*h + f''(x)/2!*h**2  + O(h**3)
+    # We can solve for weights `wi` such that:
+    #   w1*f(x)      = w1*(f(x))
+    # + w2*f(x + h)  = w2*(f(x) + f'(x)*h + f''(x)/2!*h**2) + O(h**3)
+    # + w3*f(x - h)  = w3*(f(x) - f'(x)*h + f''(x)/2!*h**2) + O(h**3)
+    #                =     0    + f'(x)*h + 0               + O(h**3)
+    # Then
+    #     f'(x) ~ (w1*f(x) + w2*f(x+h) + w3*f(x-h))/h
+    # is a finite difference derivative approximation with error O(h**2),
+    # and so it is said to be a "second-order" approximation. Under certain
+    # conditions (e.g. well-behaved function, `h` sufficiently small), the
+    # error in the approximation will decrease with h**2; that is, if `h` is
+    # reduced by a factor of 2, the error is reduced by a factor of 4.
+    #
+    # By default, we use eighth-order formulae. Our central-difference formula
+    # uses abscissae:
+    #   x-h/c**3, x-h/c**2, x-h/c, x-h, x, x+h, x+h/c, x+h/c**2, x+h/c**3
+    # where `c` is the step factor. (Typically, the step factor is greater than
+    # one, so the outermost points - as written above - are actually closest to
+    # `x`.) This "stencil" is chosen so that each iteration, the step can be
+    # reduced by the factor `c`, and most of the function evaluations can be
+    # reused with the new step size. For example, in the next iteration, we
+    # will have:
+    #   x-h/c**4, x-h/c**3, x-h/c**2, x-h/c, x, x+h/c, x+h/c**2, x+h/c**3, x+h/c**4
+    # We do not reuse `x-h` and `x+h` for the new derivative estimate.
+    # While this would increase the order of the formula and thus the
+    # theoretical convergence rate, it is also less stable numerically.
+    # (As noted above, there are other ways of processing the values that are
+    # more stable. Thus, even now we store `f(x-h)` and `f(x+h)` in `work.fs`
+    # to simplify future development of this sort of improvement.)
+    #
+    # The (right) one-sided formula is produced similarly using abscissae
+    #   x, x+h, x+h/d, x+h/d**2, ..., x+h/d**6, x+h/d**7, x+h/d**7
+    # where `d` is the square root of `c`. (The left one-sided formula simply
+    # uses -h.) When the step size is reduced by factor `c = d**2`, we have
+    # abscissae:
+    #   x, x+h/d**2, x+h/d**3..., x+h/d**8, x+h/d**9, x+h/d**9
+    # `d` is chosen as the square root of `c` so that the rate of the step-size
+    # reduction is the same per iteration as in the central difference case.
+    # Note that because the central difference formulas are inherently of even
+    # order, for simplicity, we use only even-order formulas for one-sided
+    # differences, too.
+
+    # It's possible for the user to specify `fac` in, say, double precision but
+    # `x` and `args` in single precision. `fac` gets converted to single
+    # precision, but we should always use double precision for the intermediate
+    # calculations here to avoid additional error in the weights.
+    fac = float(work.fac)
+
+    # Note that if the user switches back to floating point precision with
+    # `x` and `args`, then `fac` will not necessarily equal the (lower
+    # precision) cached `_derivative_weights.fac`, and the weights will
+    # need to be recalculated. This could be fixed, but it's late, and of
+    # low consequence.
+
+    diff_state = work.diff_state
+    if fac != diff_state.fac:
+        diff_state.central = []
+        diff_state.right = []
+        diff_state.fac = fac
+
+    if len(diff_state.central) != 2*n + 1:
+        # Central difference weights. Consider refactoring this; it could
+        # probably be more compact.
+        # Note: Using NumPy here is OK; we convert to xp-type at the end
+        i = np.arange(-n, n + 1)
+        p = np.abs(i) - 1.  # center point has power `p` -1, but sign `s` is 0
+        s = np.sign(i)
+
+        h = s / fac ** p
+        A = np.vander(h, increasing=True).T
+        b = np.zeros(2*n + 1)
+        b[1] = 1
+        weights = np.linalg.solve(A, b)
+
+        # Enforce identities to improve accuracy
+        weights[n] = 0
+        for i in range(n):
+            weights[-i-1] = -weights[i]
+
+        # Cache the weights. We only need to calculate them once unless
+        # the step factor changes.
+        diff_state.central = weights
+
+        # One-sided difference weights. The left one-sided weights (with
+        # negative steps) are simply the negative of the right one-sided
+        # weights, so no need to compute them separately.
+        i = np.arange(2*n + 1)
+        p = i - 1.
+        s = np.sign(i)
+
+        h = s / np.sqrt(fac) ** p
+        A = np.vander(h, increasing=True).T
+        b = np.zeros(2 * n + 1)
+        b[1] = 1
+        weights = np.linalg.solve(A, b)
+
+        diff_state.right = weights
+
+    return (xp.asarray(diff_state.central, dtype=work.dtype),
+            xp.asarray(diff_state.right, dtype=work.dtype))
+
+
+def jacobian(f, x, *, tolerances=None, maxiter=10, order=8, initial_step=0.5,
+             step_factor=2.0, step_direction=0):
+    r"""Evaluate the Jacobian of a function numerically.
+
+    Parameters
+    ----------
+    f : callable
+        The function whose Jacobian is desired. The signature must be::
+
+            f(xi: ndarray) -> ndarray
+
+        where each element of ``xi`` is a finite real. If the function to be
+        differentiated accepts additional arguments, wrap it (e.g. using
+        `functools.partial` or ``lambda``) and pass the wrapped callable
+        into `jacobian`. `f` must not mutate the array ``xi``. See Notes
+        regarding vectorization and the dimensionality of the input and output.
+    x : float array_like
+        Points at which to evaluate the Jacobian. Must have at least one dimension.
+        See Notes regarding the dimensionality and vectorization.
+    tolerances : dictionary of floats, optional
+        Absolute and relative tolerances. Valid keys of the dictionary are:
+
+        - ``atol`` - absolute tolerance on the derivative
+        - ``rtol`` - relative tolerance on the derivative
+
+        Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
+        `atol` is the smallest normal number of the appropriate dtype, and
+        the default `rtol` is the square root of the precision of the
+        appropriate dtype.
+    maxiter : int, default: 10
+        The maximum number of iterations of the algorithm to perform. See
+        Notes.
+    order : int, default: 8
+        The (positive integer) order of the finite difference formula to be
+        used. Odd integers will be rounded up to the next even integer.
+    initial_step : float array_like, default: 0.5
+        The (absolute) initial step size for the finite difference derivative
+        approximation. Must be broadcastable with `x` and `step_direction`.
+    step_factor : float, default: 2.0
+        The factor by which the step size is *reduced* in each iteration; i.e.
+        the step size in iteration 1 is ``initial_step/step_factor``. If
+        ``step_factor < 1``, subsequent steps will be greater than the initial
+        step; this may be useful if steps smaller than some threshold are
+        undesirable (e.g. due to subtractive cancellation error).
+    step_direction : integer array_like
+        An array representing the direction of the finite difference steps (e.g.
+        for use when `x` lies near to the boundary of the domain of the function.)
+        Must be broadcastable with `x` and `initial_step`.
+        Where 0 (default), central differences are used; where negative (e.g.
+        -1), steps are non-positive; and where positive (e.g. 1), all steps are
+        non-negative.
+
+    Returns
+    -------
+    res : _RichResult
+        An object similar to an instance of `scipy.optimize.OptimizeResult` with the
+        following attributes. The descriptions are written as though the values will
+        be scalars; however, if `f` returns an array, the outputs will be
+        arrays of the same shape.
+
+        success : bool array
+            ``True`` where the algorithm terminated successfully (status ``0``);
+            ``False`` otherwise.
+        status : int array
+            An integer representing the exit status of the algorithm.
+
+            - ``0`` : The algorithm converged to the specified tolerances.
+            - ``-1`` : The error estimate increased, so iteration was terminated.
+            - ``-2`` : The maximum number of iterations was reached.
+            - ``-3`` : A non-finite value was encountered.
+
+        df : float array
+            The Jacobian of `f` at `x`, if the algorithm terminated
+            successfully.
+        error : float array
+            An estimate of the error: the magnitude of the difference between
+            the current estimate of the Jacobian and the estimate in the
+            previous iteration.
+        nit : int array
+            The number of iterations of the algorithm that were performed.
+        nfev : int array
+            The number of points at which `f` was evaluated.
+
+        Each element of an attribute is associated with the corresponding
+        element of `df`. For instance, element ``i`` of `nfev` is the
+        number of points at which `f` was evaluated for the sake of
+        computing element ``i`` of `df`.
+
+    See Also
+    --------
+    derivative, hessian
+
+    Notes
+    -----
+    Suppose we wish to evaluate the Jacobian of a function
+    :math:`f: \mathbf{R}^m \rightarrow \mathbf{R}^n`. Assign to variables
+    ``m`` and ``n`` the positive integer values of :math:`m` and :math:`n`,
+    respectively, and let ``...`` represent an arbitrary tuple of integers.
+    If we wish to evaluate the Jacobian at a single point, then:
+
+    - argument `x` must be an array of shape ``(m,)``
+    - argument `f` must be vectorized to accept an array of shape ``(m, ...)``.
+      The first axis represents the :math:`m` inputs of :math:`f`; the remainder
+      are for evaluating the function at multiple points in a single call.
+    - argument `f` must return an array of shape ``(n, ...)``. The first
+      axis represents the :math:`n` outputs of :math:`f`; the remainder
+      are for the result of evaluating the function at multiple points.
+    - attribute ``df`` of the result object will be an array of shape ``(n, m)``,
+      the Jacobian.
+
+    This function is also vectorized in the sense that the Jacobian can be
+    evaluated at ``k`` points in a single call. In this case, `x` would be an
+    array of shape ``(m, k)``, `f` would accept an array of shape
+    ``(m, k, ...)`` and return an array of shape ``(n, k, ...)``, and the ``df``
+    attribute of the result would have shape ``(n, m, k)``.
+
+    Suppose the desired callable ``f_not_vectorized`` is not vectorized; it can
+    only accept an array of shape ``(m,)``. A simple solution to satisfy the required
+    interface is to wrap ``f_not_vectorized`` as follows::
+
+        def f(x):
+            return np.apply_along_axis(f_not_vectorized, axis=0, arr=x)
+
+    Alternatively, suppose the desired callable ``f_vec_q`` is vectorized, but
+    only for 2-D arrays of shape ``(m, q)``. To satisfy the required interface,
+    consider::
+
+        def f(x):
+            m, batch = x.shape[0], x.shape[1:]  # x.shape is (m, ...)
+            x = np.reshape(x, (m, -1))  # `-1` is short for q = prod(batch)
+            res = f_vec_q(x)  # pass shape (m, q) to function
+            n = res.shape[0]
+            return np.reshape(res, (n,) + batch)  # return shape (n, ...)
+
+    Then pass the wrapped callable ``f`` as the first argument of `jacobian`.
+
+    References
+    ----------
+    .. [1] Jacobian matrix and determinant, *Wikipedia*,
+           https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant
+
+    Examples
+    --------
+    The Rosenbrock function maps from :math:`\mathbf{R}^m \rightarrow \mathbf{R}`;
+    the SciPy implementation `scipy.optimize.rosen` is vectorized to accept an
+    array of shape ``(m, p)`` and return an array of shape ``p``. Suppose we wish
+    to evaluate the Jacobian (AKA the gradient because the function returns a scalar)
+    at ``[0.5, 0.5, 0.5]``.
+
+    >>> import numpy as np
+    >>> from scipy.differentiate import jacobian
+    >>> from scipy.optimize import rosen, rosen_der
+    >>> m = 3
+    >>> x = np.full(m, 0.5)
+    >>> res = jacobian(rosen, x)
+    >>> ref = rosen_der(x)  # reference value of the gradient
+    >>> res.df, ref
+    (array([-51.,  -1.,  50.]), array([-51.,  -1.,  50.]))
+
+    As an example of a function with multiple outputs, consider Example 4
+    from [1]_.
+
+    >>> def f(x):
+    ...     x1, x2, x3 = x
+    ...     return [x1, 5*x3, 4*x2**2 - 2*x3, x3*np.sin(x1)]
+
+    The true Jacobian is given by:
+
+    >>> def df(x):
+    ...         x1, x2, x3 = x
+    ...         one = np.ones_like(x1)
+    ...         return [[one, 0*one, 0*one],
+    ...                 [0*one, 0*one, 5*one],
+    ...                 [0*one, 8*x2, -2*one],
+    ...                 [x3*np.cos(x1), 0*one, np.sin(x1)]]
+
+    Evaluate the Jacobian at an arbitrary point.
+
+    >>> rng = np.random.default_rng(389252938452)
+    >>> x = rng.random(size=3)
+    >>> res = jacobian(f, x)
+    >>> ref = df(x)
+    >>> res.df.shape == (4, 3)
+    True
+    >>> np.allclose(res.df, ref)
+    True
+
+    Evaluate the Jacobian at 10 arbitrary points in a single call.
+
+    >>> x = rng.random(size=(3, 10))
+    >>> res = jacobian(f, x)
+    >>> ref = df(x)
+    >>> res.df.shape == (4, 3, 10)
+    True
+    >>> np.allclose(res.df, ref)
+    True
+
+    """
+    xp = array_namespace(x)
+    x0 = xp_promote(x, force_floating=True, xp=xp)
+
+    if x0.ndim < 1:
+        message = "Argument `x` must be at least 1-D."
+        raise ValueError(message)
+
+    m = x0.shape[0]
+    i = xp.arange(m)
+
+    def wrapped(x):
+        p = () if x.ndim == x0.ndim else (x.shape[-1],)  # number of abscissae
+
+        new_shape = (m, m) + x0.shape[1:] + p
+        xph = xp.expand_dims(x0, axis=1)
+        if x.ndim != x0.ndim:
+            xph = xp.expand_dims(xph, axis=-1)
+        xph = xp_copy(xp.broadcast_to(xph, new_shape), xp=xp)
+        xph = xpx.at(xph)[i, i].set(x)
+        return f(xph)
+
+    res = derivative(wrapped, x, tolerances=tolerances,
+                     maxiter=maxiter, order=order, initial_step=initial_step,
+                     step_factor=step_factor, preserve_shape=True,
+                     step_direction=step_direction)
+
+    del res.x  # the user knows `x`, and the way it gets broadcasted is meaningless here
+    return res
+
+
+def hessian(f, x, *, tolerances=None, maxiter=10,
+            order=8, initial_step=0.5, step_factor=2.0):
+    r"""Evaluate the Hessian of a function numerically.
+
+    Parameters
+    ----------
+    f : callable
+        The function whose Hessian is desired. The signature must be::
+
+            f(xi: ndarray) -> ndarray
+
+        where each element of ``xi`` is a finite real. If the function to be
+        differentiated accepts additional arguments, wrap it (e.g. using
+        `functools.partial` or ``lambda``) and pass the wrapped callable
+        into `hessian`. `f` must not mutate the array ``xi``. See Notes
+        regarding vectorization and the dimensionality of the input and output.
+    x : float array_like
+        Points at which to evaluate the Hessian. Must have at least one dimension.
+        See Notes regarding the dimensionality and vectorization.
+    tolerances : dictionary of floats, optional
+        Absolute and relative tolerances. Valid keys of the dictionary are:
+
+        - ``atol`` - absolute tolerance on the derivative
+        - ``rtol`` - relative tolerance on the derivative
+
+        Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
+        `atol` is the smallest normal number of the appropriate dtype, and
+        the default `rtol` is the square root of the precision of the
+        appropriate dtype.
+    order : int, default: 8
+        The (positive integer) order of the finite difference formula to be
+        used. Odd integers will be rounded up to the next even integer.
+    initial_step : float, default: 0.5
+        The (absolute) initial step size for the finite difference derivative
+        approximation.
+    step_factor : float, default: 2.0
+        The factor by which the step size is *reduced* in each iteration; i.e.
+        the step size in iteration 1 is ``initial_step/step_factor``. If
+        ``step_factor < 1``, subsequent steps will be greater than the initial
+        step; this may be useful if steps smaller than some threshold are
+        undesirable (e.g. due to subtractive cancellation error).
+    maxiter : int, default: 10
+        The maximum number of iterations of the algorithm to perform. See
+        Notes.
+
+    Returns
+    -------
+    res : _RichResult
+        An object similar to an instance of `scipy.optimize.OptimizeResult` with the
+        following attributes. The descriptions are written as though the values will
+        be scalars; however, if `f` returns an array, the outputs will be
+        arrays of the same shape.
+
+        success : bool array
+            ``True`` where the algorithm terminated successfully (status ``0``);
+            ``False`` otherwise.
+        status : int array
+            An integer representing the exit status of the algorithm.
+
+            - ``0`` : The algorithm converged to the specified tolerances.
+            - ``-1`` : The error estimate increased, so iteration was terminated.
+            - ``-2`` : The maximum number of iterations was reached.
+            - ``-3`` : A non-finite value was encountered.
+
+        ddf : float array
+            The Hessian of `f` at `x`, if the algorithm terminated
+            successfully.
+        error : float array
+            An estimate of the error: the magnitude of the difference between
+            the current estimate of the Hessian and the estimate in the
+            previous iteration.
+        nfev : int array
+            The number of points at which `f` was evaluated.
+
+        Each element of an attribute is associated with the corresponding
+        element of `ddf`. For instance, element ``[i, j]`` of `nfev` is the
+        number of points at which `f` was evaluated for the sake of
+        computing element ``[i, j]`` of `ddf`.
+
+    See Also
+    --------
+    derivative, jacobian
+
+    Notes
+    -----
+    Suppose we wish to evaluate the Hessian of a function
+    :math:`f: \mathbf{R}^m \rightarrow \mathbf{R}`, and we assign to variable
+    ``m`` the positive integer value of :math:`m`. If we wish to evaluate
+    the Hessian at a single point, then:
+
+    - argument `x` must be an array of shape ``(m,)``
+    - argument `f` must be vectorized to accept an array of shape
+      ``(m, ...)``. The first axis represents the :math:`m` inputs of
+      :math:`f`; the remaining axes indicated by ellipses are for evaluating
+      the function at several abscissae in a single call.
+    - argument `f` must return an array of shape ``(...)``.
+    - attribute ``dff`` of the result object will be an array of shape ``(m, m)``,
+      the Hessian.
+
+    This function is also vectorized in the sense that the Hessian can be
+    evaluated at ``k`` points in a single call. In this case, `x` would be an
+    array of shape ``(m, k)``, `f` would accept an array of shape
+    ``(m, ...)`` and return an array of shape ``(...)``, and the ``ddf``
+    attribute of the result would have shape ``(m, m, k)``. Note that the
+    axis associated with the ``k`` points is included within the axes
+    denoted by ``(...)``.
+
+    Currently, `hessian` is implemented by nesting calls to `jacobian`.
+    All options passed to `hessian` are used for both the inner and outer
+    calls with one exception: the `rtol` used in the inner `jacobian` call
+    is tightened by a factor of 100 with the expectation that the inner
+    error can be ignored. A consequence is that `rtol` should not be set
+    less than 100 times the precision of the dtype of `x`; a warning is
+    emitted otherwise.
+
+    References
+    ----------
+    .. [1] Hessian matrix, *Wikipedia*,
+           https://en.wikipedia.org/wiki/Hessian_matrix
+
+    Examples
+    --------
+    The Rosenbrock function maps from :math:`\mathbf{R}^m \rightarrow \mathbf{R}`;
+    the SciPy implementation `scipy.optimize.rosen` is vectorized to accept an
+    array of shape ``(m, ...)`` and return an array of shape ``...``. Suppose we
+    wish to evaluate the Hessian at ``[0.5, 0.5, 0.5]``.
+
+    >>> import numpy as np
+    >>> from scipy.differentiate import hessian
+    >>> from scipy.optimize import rosen, rosen_hess
+    >>> m = 3
+    >>> x = np.full(m, 0.5)
+    >>> res = hessian(rosen, x)
+    >>> ref = rosen_hess(x)  # reference value of the Hessian
+    >>> np.allclose(res.ddf, ref)
+    True
+
+    `hessian` is vectorized to evaluate the Hessian at multiple points
+    in a single call.
+
+    >>> rng = np.random.default_rng(4589245925010)
+    >>> x = rng.random((m, 10))
+    >>> res = hessian(rosen, x)
+    >>> ref = [rosen_hess(xi) for xi in x.T]
+    >>> ref = np.moveaxis(ref, 0, -1)
+    >>> np.allclose(res.ddf, ref)
+    True
+
+    """
+    # todo:
+    # - add ability to vectorize over additional parameters (*args?)
+    # - error estimate stack with inner jacobian (or use legit 2D stencil)
+
+    kwargs = dict(maxiter=maxiter, order=order, initial_step=initial_step,
+                  step_factor=step_factor)
+    tolerances = {} if tolerances is None else tolerances
+    atol = tolerances.get('atol', None)
+    rtol = tolerances.get('rtol', None)
+
+    xp = array_namespace(x)
+    x0 = xp_promote(x, force_floating=True, xp=xp)
+
+    finfo = xp.finfo(x0.dtype)
+    rtol = finfo.eps**0.5 if rtol is None else rtol  # keep same as `derivative`
+
+    # tighten the inner tolerance to make the inner error negligible
+    rtol_min = finfo.eps * 100
+    message = (f"The specified `{rtol=}`, but error estimates are likely to be "
+               f"unreliable when `rtol < {rtol_min}`.")
+    if 0 < rtol < rtol_min:  # rtol <= 0 is an error
+        warnings.warn(message, RuntimeWarning, stacklevel=2)
+        rtol = rtol_min
+
+    def df(x):
+        tolerances = dict(rtol=rtol/100, atol=atol)
+        temp = jacobian(f, x, tolerances=tolerances, **kwargs)
+        nfev.append(temp.nfev if len(nfev) == 0 else temp.nfev.sum(axis=-1))
+        return temp.df
+
+    nfev = []  # track inner function evaluations
+    res = jacobian(df, x, tolerances=tolerances, **kwargs)  # jacobian of jacobian
+
+    nfev = xp.cumulative_sum(xp.stack(nfev), axis=0)
+    res_nit = xp.astype(res.nit[xp.newaxis, ...], xp.int64)  # appease torch
+    res.nfev = xp.take_along_axis(nfev, res_nit, axis=0)[0]
+    res.ddf = res.df
+    del res.df  # this is renamed to ddf
+    del res.nit  # this is only the outer-jacobian nit
+
+    return res
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c545a00b9fd63427088ac873fa3fa65678b77f71
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/__init__.py
@@ -0,0 +1,114 @@
+"""
+==============================================
+Discrete Fourier transforms (:mod:`scipy.fft`)
+==============================================
+
+.. currentmodule:: scipy.fft
+
+Fast Fourier Transforms (FFTs)
+==============================
+
+.. autosummary::
+   :toctree: generated/
+
+   fft - Fast (discrete) Fourier Transform (FFT)
+   ifft - Inverse FFT
+   fft2 - 2-D FFT
+   ifft2 - 2-D inverse FFT
+   fftn - N-D FFT
+   ifftn - N-D inverse FFT
+   rfft - FFT of strictly real-valued sequence
+   irfft - Inverse of rfft
+   rfft2 - 2-D FFT of real sequence
+   irfft2 - Inverse of rfft2
+   rfftn - N-D FFT of real sequence
+   irfftn - Inverse of rfftn
+   hfft - FFT of a Hermitian sequence (real spectrum)
+   ihfft - Inverse of hfft
+   hfft2 - 2-D FFT of a Hermitian sequence
+   ihfft2 - Inverse of hfft2
+   hfftn - N-D FFT of a Hermitian sequence
+   ihfftn - Inverse of hfftn
+
+Discrete Sin and Cosine Transforms (DST and DCT)
+================================================
+
+.. autosummary::
+   :toctree: generated/
+
+   dct - Discrete cosine transform
+   idct - Inverse discrete cosine transform
+   dctn - N-D Discrete cosine transform
+   idctn - N-D Inverse discrete cosine transform
+   dst - Discrete sine transform
+   idst - Inverse discrete sine transform
+   dstn - N-D Discrete sine transform
+   idstn - N-D Inverse discrete sine transform
+
+Fast Hankel Transforms
+======================
+
+.. autosummary::
+   :toctree: generated/
+
+   fht - Fast Hankel transform
+   ifht - Inverse of fht
+
+Helper functions
+================
+
+.. autosummary::
+   :toctree: generated/
+
+   fftshift - Shift the zero-frequency component to the center of the spectrum
+   ifftshift - The inverse of `fftshift`
+   fftfreq - Return the Discrete Fourier Transform sample frequencies
+   rfftfreq - DFT sample frequencies (for usage with rfft, irfft)
+   fhtoffset - Compute an optimal offset for the Fast Hankel Transform
+   next_fast_len - Find the optimal length to zero-pad an FFT for speed
+   prev_fast_len - Find the maximum slice length that results in a fast FFT
+   set_workers - Context manager to set default number of workers
+   get_workers - Get the current default number of workers
+
+Backend control
+===============
+
+.. autosummary::
+   :toctree: generated/
+
+   set_backend - Context manager to set the backend within a fixed scope
+   skip_backend - Context manager to skip a backend within a fixed scope
+   set_global_backend - Sets the global fft backend
+   register_backend - Register a backend for permanent use
+
+"""
+
+from ._basic import (
+    fft, ifft, fft2, ifft2, fftn, ifftn,
+    rfft, irfft, rfft2, irfft2, rfftn, irfftn,
+    hfft, ihfft, hfft2, ihfft2, hfftn, ihfftn)
+from ._realtransforms import dct, idct, dst, idst, dctn, idctn, dstn, idstn
+from ._fftlog import fht, ifht, fhtoffset
+from ._helper import (
+    next_fast_len, prev_fast_len, fftfreq,
+    rfftfreq, fftshift, ifftshift)
+from ._backend import (set_backend, skip_backend, set_global_backend,
+                       register_backend)
+from ._pocketfft.helper import set_workers, get_workers
+
+__all__ = [
+    'fft', 'ifft', 'fft2', 'ifft2', 'fftn', 'ifftn',
+    'rfft', 'irfft', 'rfft2', 'irfft2', 'rfftn', 'irfftn',
+    'hfft', 'ihfft', 'hfft2', 'ihfft2', 'hfftn', 'ihfftn',
+    'fftfreq', 'rfftfreq', 'fftshift', 'ifftshift',
+    'next_fast_len', 'prev_fast_len',
+    'dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn',
+    'fht', 'ifht',
+    'fhtoffset',
+    'set_backend', 'skip_backend', 'set_global_backend', 'register_backend',
+    'get_workers', 'set_workers']
+
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_backend.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1e5cfcad5c4cbc43276e151d2da33039368630d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_backend.py
@@ -0,0 +1,196 @@
+import scipy._lib.uarray as ua
+from . import _basic_backend
+from . import _realtransforms_backend
+from . import _fftlog_backend
+
+
+class _ScipyBackend:
+    """The default backend for fft calculations
+
+    Notes
+    -----
+    We use the domain ``numpy.scipy`` rather than ``scipy`` because ``uarray``
+    treats the domain as a hierarchy. This means the user can install a single
+    backend for ``numpy`` and have it implement ``numpy.scipy.fft`` as well.
+    """
+    __ua_domain__ = "numpy.scipy.fft"
+
+    @staticmethod
+    def __ua_function__(method, args, kwargs):
+
+        fn = getattr(_basic_backend, method.__name__, None)
+        if fn is None:
+            fn = getattr(_realtransforms_backend, method.__name__, None)
+        if fn is None:
+            fn = getattr(_fftlog_backend, method.__name__, None)
+        if fn is None:
+            return NotImplemented
+        return fn(*args, **kwargs)
+
+
+_named_backends = {
+    'scipy': _ScipyBackend,
+}
+
+
+def _backend_from_arg(backend):
+    """Maps strings to known backends and validates the backend"""
+
+    if isinstance(backend, str):
+        try:
+            backend = _named_backends[backend]
+        except KeyError as e:
+            raise ValueError(f'Unknown backend {backend}') from e
+
+    if backend.__ua_domain__ != 'numpy.scipy.fft':
+        raise ValueError('Backend does not implement "numpy.scipy.fft"')
+
+    return backend
+
+
+def set_global_backend(backend, coerce=False, only=False, try_last=False):
+    """Sets the global fft backend
+
+    This utility method replaces the default backend for permanent use. It
+    will be tried in the list of backends automatically, unless the
+    ``only`` flag is set on a backend. This will be the first tried
+    backend outside the :obj:`set_backend` context manager.
+
+    Parameters
+    ----------
+    backend : {object, 'scipy'}
+        The backend to use.
+        Can either be a ``str`` containing the name of a known backend
+        {'scipy'} or an object that implements the uarray protocol.
+    coerce : bool
+        Whether to coerce input types when trying this backend.
+    only : bool
+        If ``True``, no more backends will be tried if this fails.
+        Implied by ``coerce=True``.
+    try_last : bool
+        If ``True``, the global backend is tried after registered backends.
+
+    Raises
+    ------
+    ValueError: If the backend does not implement ``numpy.scipy.fft``.
+
+    Notes
+    -----
+    This will overwrite the previously set global backend, which, by default, is
+    the SciPy implementation.
+
+    Examples
+    --------
+    We can set the global fft backend:
+
+    >>> from scipy.fft import fft, set_global_backend
+    >>> set_global_backend("scipy")  # Sets global backend (default is "scipy").
+    >>> fft([1])  # Calls the global backend
+    array([1.+0.j])
+    """
+    backend = _backend_from_arg(backend)
+    ua.set_global_backend(backend, coerce=coerce, only=only, try_last=try_last)
+
+
+def register_backend(backend):
+    """
+    Register a backend for permanent use.
+
+    Registered backends have the lowest priority and will be tried after the
+    global backend.
+
+    Parameters
+    ----------
+    backend : {object, 'scipy'}
+        The backend to use.
+        Can either be a ``str`` containing the name of a known backend
+        {'scipy'} or an object that implements the uarray protocol.
+
+    Raises
+    ------
+    ValueError: If the backend does not implement ``numpy.scipy.fft``.
+
+    Examples
+    --------
+    We can register a new fft backend:
+
+    >>> from scipy.fft import fft, register_backend, set_global_backend
+    >>> class NoopBackend:  # Define an invalid Backend
+    ...     __ua_domain__ = "numpy.scipy.fft"
+    ...     def __ua_function__(self, func, args, kwargs):
+    ...          return NotImplemented
+    >>> set_global_backend(NoopBackend())  # Set the invalid backend as global
+    >>> register_backend("scipy")  # Register a new backend
+    # The registered backend is called because
+    # the global backend returns `NotImplemented`
+    >>> fft([1])
+    array([1.+0.j])
+    >>> set_global_backend("scipy")  # Restore global backend to default
+
+    """
+    backend = _backend_from_arg(backend)
+    ua.register_backend(backend)
+
+
+def set_backend(backend, coerce=False, only=False):
+    """Context manager to set the backend within a fixed scope.
+
+    Upon entering the ``with`` statement, the given backend will be added to
+    the list of available backends with the highest priority. Upon exit, the
+    backend is reset to the state before entering the scope.
+
+    Parameters
+    ----------
+    backend : {object, 'scipy'}
+        The backend to use.
+        Can either be a ``str`` containing the name of a known backend
+        {'scipy'} or an object that implements the uarray protocol.
+    coerce : bool, optional
+        Whether to allow expensive conversions for the ``x`` parameter. e.g.,
+        copying a NumPy array to the GPU for a CuPy backend. Implies ``only``.
+    only : bool, optional
+        If only is ``True`` and this backend returns ``NotImplemented``, then a
+        BackendNotImplemented error will be raised immediately. Ignoring any
+        lower priority backends.
+
+    Examples
+    --------
+    >>> import scipy.fft as fft
+    >>> with fft.set_backend('scipy', only=True):
+    ...     fft.fft([1])  # Always calls the scipy implementation
+    array([1.+0.j])
+    """
+    backend = _backend_from_arg(backend)
+    return ua.set_backend(backend, coerce=coerce, only=only)
+
+
+def skip_backend(backend):
+    """Context manager to skip a backend within a fixed scope.
+
+    Within the context of a ``with`` statement, the given backend will not be
+    called. This covers backends registered both locally and globally. Upon
+    exit, the backend will again be considered.
+
+    Parameters
+    ----------
+    backend : {object, 'scipy'}
+        The backend to skip.
+        Can either be a ``str`` containing the name of a known backend
+        {'scipy'} or an object that implements the uarray protocol.
+
+    Examples
+    --------
+    >>> import scipy.fft as fft
+    >>> fft.fft([1])  # Calls default SciPy backend
+    array([1.+0.j])
+    >>> with fft.skip_backend('scipy'):  # We explicitly skip the SciPy backend
+    ...     fft.fft([1])                 # leaving no implementation available
+    Traceback (most recent call last):
+        ...
+    BackendNotImplementedError: No selected backends had an implementation ...
+    """
+    backend = _backend_from_arg(backend)
+    return ua.skip_backend(backend)
+
+
+set_global_backend('scipy', try_last=True)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_basic.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c07ee697b3c853bd6d25e4cdb5f289ec323836e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_basic.py
@@ -0,0 +1,1650 @@
+from scipy._lib.uarray import generate_multimethod, Dispatchable
+import numpy as np
+
+
+def _x_replacer(args, kwargs, dispatchables):
+    """
+    uarray argument replacer to replace the transform input array (``x``)
+    """
+    if len(args) > 0:
+        return (dispatchables[0],) + args[1:], kwargs
+    kw = kwargs.copy()
+    kw['x'] = dispatchables[0]
+    return args, kw
+
+
+def _dispatch(func):
+    """
+    Function annotation that creates a uarray multimethod from the function
+    """
+    return generate_multimethod(func, _x_replacer, domain="numpy.scipy.fft")
+
+
+@_dispatch
+def fft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+        plan=None):
+    """
+    Compute the 1-D discrete Fourier Transform.
+
+    This function computes the 1-D *n*-point discrete Fourier
+    Transform (DFT) with the efficient Fast Fourier Transform (FFT)
+    algorithm [1]_.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    n : int, optional
+        Length of the transformed axis of the output.
+        If `n` is smaller than the length of the input, the input is cropped.
+        If it is larger, the input is padded with zeros. If `n` is not given,
+        the length of the input along the axis specified by `axis` is used.
+    axis : int, optional
+        Axis over which to compute the FFT. If not given, the last axis is
+        used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode. Default is "backward", meaning no normalization on
+        the forward transforms and scaling by ``1/n`` on the `ifft`.
+        "forward" instead applies the ``1/n`` factor on the forward transform.
+        For ``norm="ortho"``, both directions are scaled by ``1/sqrt(n)``.
+
+        .. versionadded:: 1.6.0
+           ``norm={"forward", "backward"}`` options were added
+
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See the notes below for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``. See below for more
+        details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+
+    Raises
+    ------
+    IndexError
+        if `axes` is larger than the last axis of `x`.
+
+    See Also
+    --------
+    ifft : The inverse of `fft`.
+    fft2 : The 2-D FFT.
+    fftn : The N-D FFT.
+    rfftn : The N-D FFT of real input.
+    fftfreq : Frequency bins for given FFT parameters.
+    next_fast_len : Size to pad input to for most efficient transforms
+
+    Notes
+    -----
+    FFT (Fast Fourier Transform) refers to a way the discrete Fourier Transform
+    (DFT) can be calculated efficiently, by using symmetries in the calculated
+    terms. The symmetry is highest when `n` is a power of 2, and the transform
+    is therefore most efficient for these sizes. For poorly factorizable sizes,
+    `scipy.fft` uses Bluestein's algorithm [2]_ and so is never worse than
+    O(`n` log `n`). Further performance improvements may be seen by zero-padding
+    the input using `next_fast_len`.
+
+    If ``x`` is a 1d array, then the `fft` is equivalent to ::
+
+        y[k] = np.sum(x * np.exp(-2j * np.pi * k * np.arange(n)/n))
+
+    The frequency term ``f=k/n`` is found at ``y[k]``. At ``y[n/2]`` we reach
+    the Nyquist frequency and wrap around to the negative-frequency terms. So,
+    for an 8-point transform, the frequencies of the result are
+    [0, 1, 2, 3, -4, -3, -2, -1]. To rearrange the fft output so that the
+    zero-frequency component is centered, like [-4, -3, -2, -1, 0, 1, 2, 3],
+    use `fftshift`.
+
+    Transforms can be done in single, double, or extended precision (long
+    double) floating point. Half precision inputs will be converted to single
+    precision and non-floating-point inputs will be converted to double
+    precision.
+
+    If the data type of ``x`` is real, a "real FFT" algorithm is automatically
+    used, which roughly halves the computation time. To increase efficiency
+    a little further, use `rfft`, which does the same calculation, but only
+    outputs half of the symmetrical spectrum. If the data are both real and
+    symmetrical, the `dct` can again double the efficiency, by generating
+    half of the spectrum from half of the signal.
+
+    When ``overwrite_x=True`` is specified, the memory referenced by ``x`` may
+    be used by the implementation in any way. This may include reusing the
+    memory for the result, but this is in no way guaranteed. You should not
+    rely on the contents of ``x`` after the transform as this may change in
+    future without warning.
+
+    The ``workers`` argument specifies the maximum number of parallel jobs to
+    split the FFT computation into. This will execute independent 1-D
+    FFTs within ``x``. So, ``x`` must be at least 2-D and the
+    non-transformed axes must be large enough to split into chunks. If ``x`` is
+    too small, fewer jobs may be used than requested.
+
+    References
+    ----------
+    .. [1] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the
+           machine calculation of complex Fourier series," *Math. Comput.*
+           19: 297-301.
+    .. [2] Bluestein, L., 1970, "A linear filtering approach to the
+           computation of discrete Fourier transform". *IEEE Transactions on
+           Audio and Electroacoustics.* 18 (4): 451-455.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> scipy.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8))
+    array([-2.33486982e-16+1.14423775e-17j,  8.00000000e+00-1.25557246e-15j,
+            2.33486982e-16+2.33486982e-16j,  0.00000000e+00+1.22464680e-16j,
+           -1.14423775e-17+2.33486982e-16j,  0.00000000e+00+5.20784380e-16j,
+            1.14423775e-17+1.14423775e-17j,  0.00000000e+00+1.22464680e-16j])
+
+    In this example, real input has an FFT which is Hermitian, i.e., symmetric
+    in the real part and anti-symmetric in the imaginary part:
+
+    >>> from scipy.fft import fft, fftfreq, fftshift
+    >>> import matplotlib.pyplot as plt
+    >>> t = np.arange(256)
+    >>> sp = fftshift(fft(np.sin(t)))
+    >>> freq = fftshift(fftfreq(t.shape[-1]))
+    >>> plt.plot(freq, sp.real, freq, sp.imag)
+    [,
+     ]
+    >>> plt.show()
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def ifft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the 1-D inverse discrete Fourier Transform.
+
+    This function computes the inverse of the 1-D *n*-point
+    discrete Fourier transform computed by `fft`.  In other words,
+    ``ifft(fft(x)) == x`` to within numerical accuracy.
+
+    The input should be ordered in the same way as is returned by `fft`,
+    i.e.,
+
+    * ``x[0]`` should contain the zero frequency term,
+    * ``x[1:n//2]`` should contain the positive-frequency terms,
+    * ``x[n//2 + 1:]`` should contain the negative-frequency terms, in
+      increasing order starting from the most negative frequency.
+
+    For an even number of input points, ``x[n//2]`` represents the sum of
+    the values at the positive and negative Nyquist frequencies, as the two
+    are aliased together. See `fft` for details.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    n : int, optional
+        Length of the transformed axis of the output.
+        If `n` is smaller than the length of the input, the input is cropped.
+        If it is larger, the input is padded with zeros. If `n` is not given,
+        the length of the input along the axis specified by `axis` is used.
+        See notes about padding issues.
+    axis : int, optional
+        Axis over which to compute the inverse DFT. If not given, the last
+        axis is used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+
+    Raises
+    ------
+    IndexError
+        If `axes` is larger than the last axis of `x`.
+
+    See Also
+    --------
+    fft : The 1-D (forward) FFT, of which `ifft` is the inverse.
+    ifft2 : The 2-D inverse FFT.
+    ifftn : The N-D inverse FFT.
+
+    Notes
+    -----
+    If the input parameter `n` is larger than the size of the input, the input
+    is padded by appending zeros at the end. Even though this is the common
+    approach, it might lead to surprising results. If a different padding is
+    desired, it must be performed before calling `ifft`.
+
+    If ``x`` is a 1-D array, then the `ifft` is equivalent to ::
+
+        y[k] = np.sum(x * np.exp(2j * np.pi * k * np.arange(n)/n)) / len(x)
+
+    As with `fft`, `ifft` has support for all floating point types and is
+    optimized for real input.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> scipy.fft.ifft([0, 4, 0, 0])
+    array([ 1.+0.j,  0.+1.j, -1.+0.j,  0.-1.j]) # may vary
+
+    Create and plot a band-limited signal with random phases:
+
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> t = np.arange(400)
+    >>> n = np.zeros((400,), dtype=complex)
+    >>> n[40:60] = np.exp(1j*rng.uniform(0, 2*np.pi, (20,)))
+    >>> s = scipy.fft.ifft(n)
+    >>> plt.plot(t, s.real, 'b-', t, s.imag, 'r--')
+    [, ]
+    >>> plt.legend(('real', 'imaginary'))
+    
+    >>> plt.show()
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def rfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the 1-D discrete Fourier Transform for real input.
+
+    This function computes the 1-D *n*-point discrete Fourier
+    Transform (DFT) of a real-valued array by means of an efficient algorithm
+    called the Fast Fourier Transform (FFT).
+
+    Parameters
+    ----------
+    x : array_like
+        Input array
+    n : int, optional
+        Number of points along transformation axis in the input to use.
+        If `n` is smaller than the length of the input, the input is cropped.
+        If it is larger, the input is padded with zeros. If `n` is not given,
+        the length of the input along the axis specified by `axis` is used.
+    axis : int, optional
+        Axis over which to compute the FFT. If not given, the last axis is
+        used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+        If `n` is even, the length of the transformed axis is ``(n/2)+1``.
+        If `n` is odd, the length is ``(n+1)/2``.
+
+    Raises
+    ------
+    IndexError
+        If `axis` is larger than the last axis of `a`.
+
+    See Also
+    --------
+    irfft : The inverse of `rfft`.
+    fft : The 1-D FFT of general (complex) input.
+    fftn : The N-D FFT.
+    rfft2 : The 2-D FFT of real input.
+    rfftn : The N-D FFT of real input.
+
+    Notes
+    -----
+    When the DFT is computed for purely real input, the output is
+    Hermitian-symmetric, i.e., the negative frequency terms are just the complex
+    conjugates of the corresponding positive-frequency terms, and the
+    negative-frequency terms are therefore redundant. This function does not
+    compute the negative frequency terms, and the length of the transformed
+    axis of the output is therefore ``n//2 + 1``.
+
+    When ``X = rfft(x)`` and fs is the sampling frequency, ``X[0]`` contains
+    the zero-frequency term 0*fs, which is real due to Hermitian symmetry.
+
+    If `n` is even, ``A[-1]`` contains the term representing both positive
+    and negative Nyquist frequency (+fs/2 and -fs/2), and must also be purely
+    real. If `n` is odd, there is no term at fs/2; ``A[-1]`` contains
+    the largest positive frequency (fs/2*(n-1)/n), and is complex in the
+    general case.
+
+    If the input `a` contains an imaginary part, it is silently discarded.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> scipy.fft.fft([0, 1, 0, 0])
+    array([ 1.+0.j,  0.-1.j, -1.+0.j,  0.+1.j]) # may vary
+    >>> scipy.fft.rfft([0, 1, 0, 0])
+    array([ 1.+0.j,  0.-1.j, -1.+0.j]) # may vary
+
+    Notice how the final element of the `fft` output is the complex conjugate
+    of the second element, for real input. For `rfft`, this symmetry is
+    exploited to compute only the non-negative frequency terms.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def irfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Computes the inverse of `rfft`.
+
+    This function computes the inverse of the 1-D *n*-point
+    discrete Fourier Transform of real input computed by `rfft`.
+    In other words, ``irfft(rfft(x), len(x)) == x`` to within numerical
+    accuracy. (See Notes below for why ``len(a)`` is necessary here.)
+
+    The input is expected to be in the form returned by `rfft`, i.e., the
+    real zero-frequency term followed by the complex positive frequency terms
+    in order of increasing frequency. Since the discrete Fourier Transform of
+    real input is Hermitian-symmetric, the negative frequency terms are taken
+    to be the complex conjugates of the corresponding positive frequency terms.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    n : int, optional
+        Length of the transformed axis of the output.
+        For `n` output points, ``n//2+1`` input points are necessary. If the
+        input is longer than this, it is cropped. If it is shorter than this,
+        it is padded with zeros. If `n` is not given, it is taken to be
+        ``2*(m-1)``, where ``m`` is the length of the input along the axis
+        specified by `axis`.
+    axis : int, optional
+        Axis over which to compute the inverse FFT. If not given, the last
+        axis is used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+        The length of the transformed axis is `n`, or, if `n` is not given,
+        ``2*(m-1)`` where ``m`` is the length of the transformed axis of the
+        input. To get an odd number of output points, `n` must be specified.
+
+    Raises
+    ------
+    IndexError
+        If `axis` is larger than the last axis of `x`.
+
+    See Also
+    --------
+    rfft : The 1-D FFT of real input, of which `irfft` is inverse.
+    fft : The 1-D FFT.
+    irfft2 : The inverse of the 2-D FFT of real input.
+    irfftn : The inverse of the N-D FFT of real input.
+
+    Notes
+    -----
+    Returns the real valued `n`-point inverse discrete Fourier transform
+    of `x`, where `x` contains the non-negative frequency terms of a
+    Hermitian-symmetric sequence. `n` is the length of the result, not the
+    input.
+
+    If you specify an `n` such that `a` must be zero-padded or truncated, the
+    extra/removed values will be added/removed at high frequencies. One can
+    thus resample a series to `m` points via Fourier interpolation by:
+    ``a_resamp = irfft(rfft(a), m)``.
+
+    The default value of `n` assumes an even output length. By the Hermitian
+    symmetry, the last imaginary component must be 0 and so is ignored. To
+    avoid losing information, the correct length of the real input *must* be
+    given.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> scipy.fft.ifft([1, -1j, -1, 1j])
+    array([0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j]) # may vary
+    >>> scipy.fft.irfft([1, -1j, -1])
+    array([0.,  1.,  0.,  0.])
+
+    Notice how the last term in the input to the ordinary `ifft` is the
+    complex conjugate of the second term, and the output has zero imaginary
+    part everywhere. When calling `irfft`, the negative frequencies are not
+    specified, and the output array is purely real.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def hfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the FFT of a signal that has Hermitian symmetry, i.e., a real
+    spectrum.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    n : int, optional
+        Length of the transformed axis of the output. For `n` output
+        points, ``n//2 + 1`` input points are necessary. If the input is
+        longer than this, it is cropped. If it is shorter than this, it is
+        padded with zeros. If `n` is not given, it is taken to be ``2*(m-1)``,
+        where ``m`` is the length of the input along the axis specified by
+        `axis`.
+    axis : int, optional
+        Axis over which to compute the FFT. If not given, the last
+        axis is used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See `fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+        The length of the transformed axis is `n`, or, if `n` is not given,
+        ``2*m - 2``, where ``m`` is the length of the transformed axis of
+        the input. To get an odd number of output points, `n` must be
+        specified, for instance, as ``2*m - 1`` in the typical case,
+
+    Raises
+    ------
+    IndexError
+        If `axis` is larger than the last axis of `a`.
+
+    See Also
+    --------
+    rfft : Compute the 1-D FFT for real input.
+    ihfft : The inverse of `hfft`.
+    hfftn : Compute the N-D FFT of a Hermitian signal.
+
+    Notes
+    -----
+    `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
+    opposite case: here the signal has Hermitian symmetry in the time
+    domain and is real in the frequency domain. So, here, it's `hfft`, for
+    which you must supply the length of the result if it is to be odd.
+    * even: ``ihfft(hfft(a, 2*len(a) - 2) == a``, within roundoff error,
+    * odd: ``ihfft(hfft(a, 2*len(a) - 1) == a``, within roundoff error.
+
+    Examples
+    --------
+    >>> from scipy.fft import fft, hfft
+    >>> import numpy as np
+    >>> a = 2 * np.pi * np.arange(10) / 10
+    >>> signal = np.cos(a) + 3j * np.sin(3 * a)
+    >>> fft(signal).round(10)
+    array([ -0.+0.j,   5.+0.j,  -0.+0.j,  15.-0.j,   0.+0.j,   0.+0.j,
+            -0.+0.j, -15.-0.j,   0.+0.j,   5.+0.j])
+    >>> hfft(signal[:6]).round(10) # Input first half of signal
+    array([  0.,   5.,   0.,  15.,  -0.,   0.,   0., -15.,  -0.,   5.])
+    >>> hfft(signal, 10)  # Input entire signal and truncate
+    array([  0.,   5.,   0.,  15.,  -0.,   0.,   0., -15.,  -0.,   5.])
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def ihfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the inverse FFT of a signal that has Hermitian symmetry.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    n : int, optional
+        Length of the inverse FFT, the number of points along
+        transformation axis in the input to use.  If `n` is smaller than
+        the length of the input, the input is cropped. If it is larger,
+        the input is padded with zeros. If `n` is not given, the length of
+        the input along the axis specified by `axis` is used.
+    axis : int, optional
+        Axis over which to compute the inverse FFT. If not given, the last
+        axis is used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See `fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+        The length of the transformed axis is ``n//2 + 1``.
+
+    See Also
+    --------
+    hfft, irfft
+
+    Notes
+    -----
+    `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
+    opposite case: here, the signal has Hermitian symmetry in the time
+    domain and is real in the frequency domain. So, here, it's `hfft`, for
+    which you must supply the length of the result if it is to be odd:
+    * even: ``ihfft(hfft(a, 2*len(a) - 2) == a``, within roundoff error,
+    * odd: ``ihfft(hfft(a, 2*len(a) - 1) == a``, within roundoff error.
+
+    Examples
+    --------
+    >>> from scipy.fft import ifft, ihfft
+    >>> import numpy as np
+    >>> spectrum = np.array([ 15, -4, 0, -1, 0, -4])
+    >>> ifft(spectrum)
+    array([1.+0.j,  2.+0.j,  3.+0.j,  4.+0.j,  3.+0.j,  2.+0.j]) # may vary
+    >>> ihfft(spectrum)
+    array([ 1.-0.j,  2.-0.j,  3.-0.j,  4.-0.j]) # may vary
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def fftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the N-D discrete Fourier Transform.
+
+    This function computes the N-D discrete Fourier Transform over
+    any number of axes in an M-D array by means of the Fast Fourier
+    Transform (FFT).
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        This corresponds to ``n`` for ``fft(x, n)``.
+        Along any axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` and `x`,
+        as explained in the parameters section above.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    ifftn : The inverse of `fftn`, the inverse N-D FFT.
+    fft : The 1-D FFT, with definitions and conventions used.
+    rfftn : The N-D FFT of real input.
+    fft2 : The 2-D FFT.
+    fftshift : Shifts zero-frequency terms to centre of array.
+
+    Notes
+    -----
+    The output, analogously to `fft`, contains the term for zero frequency in
+    the low-order corner of all axes, the positive frequency terms in the
+    first half of all axes, the term for the Nyquist frequency in the middle
+    of all axes and the negative frequency terms in the second half of all
+    axes, in order of decreasingly negative frequency.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.mgrid[:3, :3, :3][0]
+    >>> scipy.fft.fftn(x, axes=(1, 2))
+    array([[[ 0.+0.j,   0.+0.j,   0.+0.j], # may vary
+            [ 0.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j]],
+           [[ 9.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j]],
+           [[18.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j]]])
+    >>> scipy.fft.fftn(x, (2, 2), axes=(0, 1))
+    array([[[ 2.+0.j,  2.+0.j,  2.+0.j], # may vary
+            [ 0.+0.j,  0.+0.j,  0.+0.j]],
+           [[-2.+0.j, -2.+0.j, -2.+0.j],
+            [ 0.+0.j,  0.+0.j,  0.+0.j]]])
+
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> [X, Y] = np.meshgrid(2 * np.pi * np.arange(200) / 12,
+    ...                      2 * np.pi * np.arange(200) / 34)
+    >>> S = np.sin(X) + np.cos(Y) + rng.uniform(0, 1, X.shape)
+    >>> FS = scipy.fft.fftn(S)
+    >>> plt.imshow(np.log(np.abs(scipy.fft.fftshift(FS))**2))
+    
+    >>> plt.show()
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def ifftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the N-D inverse discrete Fourier Transform.
+
+    This function computes the inverse of the N-D discrete
+    Fourier Transform over any number of axes in an M-D array by
+    means of the Fast Fourier Transform (FFT).  In other words,
+    ``ifftn(fftn(x)) == x`` to within numerical accuracy.
+
+    The input, analogously to `ifft`, should be ordered in the same way as is
+    returned by `fftn`, i.e., it should have the term for zero frequency
+    in all axes in the low-order corner, the positive frequency terms in the
+    first half of all axes, the term for the Nyquist frequency in the middle
+    of all axes and the negative frequency terms in the second half of all
+    axes, in order of decreasingly negative frequency.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        This corresponds to ``n`` for ``ifft(x, n)``.
+        Along any axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used. See notes for issue on `ifft` zero padding.
+    axes : sequence of ints, optional
+        Axes over which to compute the IFFT.  If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` or `x`,
+        as explained in the parameters section above.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    fftn : The forward N-D FFT, of which `ifftn` is the inverse.
+    ifft : The 1-D inverse FFT.
+    ifft2 : The 2-D inverse FFT.
+    ifftshift : Undoes `fftshift`, shifts zero-frequency terms to beginning
+        of array.
+
+    Notes
+    -----
+    Zero-padding, analogously with `ifft`, is performed by appending zeros to
+    the input along the specified dimension. Although this is the common
+    approach, it might lead to surprising results. If another form of zero
+    padding is desired, it must be performed before `ifftn` is called.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.eye(4)
+    >>> scipy.fft.ifftn(scipy.fft.fftn(x, axes=(0,)), axes=(1,))
+    array([[1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j], # may vary
+           [0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j],
+           [0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j],
+           [0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j]])
+
+
+    Create and plot an image with band-limited frequency content:
+
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> n = np.zeros((200,200), dtype=complex)
+    >>> n[60:80, 20:40] = np.exp(1j*rng.uniform(0, 2*np.pi, (20, 20)))
+    >>> im = scipy.fft.ifftn(n).real
+    >>> plt.imshow(im)
+    
+    >>> plt.show()
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def fft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the 2-D discrete Fourier Transform
+
+    This function computes the N-D discrete Fourier Transform
+    over any axes in an M-D array by means of the
+    Fast Fourier Transform (FFT). By default, the transform is computed over
+    the last two axes of the input array, i.e., a 2-dimensional FFT.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        This corresponds to ``n`` for ``fft(x, n)``.
+        Along each axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last two axes are
+        used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or the last two axes if `axes` is not given.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length, or `axes` not given and
+        ``len(s) != 2``.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    ifft2 : The inverse 2-D FFT.
+    fft : The 1-D FFT.
+    fftn : The N-D FFT.
+    fftshift : Shifts zero-frequency terms to the center of the array.
+        For 2-D input, swaps first and third quadrants, and second
+        and fourth quadrants.
+
+    Notes
+    -----
+    `fft2` is just `fftn` with a different default for `axes`.
+
+    The output, analogously to `fft`, contains the term for zero frequency in
+    the low-order corner of the transformed axes, the positive frequency terms
+    in the first half of these axes, the term for the Nyquist frequency in the
+    middle of the axes and the negative frequency terms in the second half of
+    the axes, in order of decreasingly negative frequency.
+
+    See `fftn` for details and a plotting example, and `fft` for
+    definitions and conventions used.
+
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.mgrid[:5, :5][0]
+    >>> scipy.fft.fft2(x)
+    array([[ 50.  +0.j        ,   0.  +0.j        ,   0.  +0.j        , # may vary
+              0.  +0.j        ,   0.  +0.j        ],
+           [-12.5+17.20477401j,   0.  +0.j        ,   0.  +0.j        ,
+              0.  +0.j        ,   0.  +0.j        ],
+           [-12.5 +4.0614962j ,   0.  +0.j        ,   0.  +0.j        ,
+              0.  +0.j        ,   0.  +0.j        ],
+           [-12.5 -4.0614962j ,   0.  +0.j        ,   0.  +0.j        ,
+              0.  +0.j        ,   0.  +0.j        ],
+           [-12.5-17.20477401j,   0.  +0.j        ,   0.  +0.j        ,
+              0.  +0.j        ,   0.  +0.j        ]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def ifft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the 2-D inverse discrete Fourier Transform.
+
+    This function computes the inverse of the 2-D discrete Fourier
+    Transform over any number of axes in an M-D array by means of
+    the Fast Fourier Transform (FFT). In other words, ``ifft2(fft2(x)) == x``
+    to within numerical accuracy. By default, the inverse transform is
+    computed over the last two axes of the input array.
+
+    The input, analogously to `ifft`, should be ordered in the same way as is
+    returned by `fft2`, i.e., it should have the term for zero frequency
+    in the low-order corner of the two axes, the positive frequency terms in
+    the first half of these axes, the term for the Nyquist frequency in the
+    middle of the axes and the negative frequency terms in the second half of
+    both axes, in order of decreasingly negative frequency.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    s : sequence of ints, optional
+        Shape (length of each axis) of the output (``s[0]`` refers to axis 0,
+        ``s[1]`` to axis 1, etc.). This corresponds to `n` for ``ifft(x, n)``.
+        Along each axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.  See notes for issue on `ifft` zero padding.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last two
+        axes are used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or the last two axes if `axes` is not given.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length, or `axes` not given and
+        ``len(s) != 2``.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    fft2 : The forward 2-D FFT, of which `ifft2` is the inverse.
+    ifftn : The inverse of the N-D FFT.
+    fft : The 1-D FFT.
+    ifft : The 1-D inverse FFT.
+
+    Notes
+    -----
+    `ifft2` is just `ifftn` with a different default for `axes`.
+
+    See `ifftn` for details and a plotting example, and `fft` for
+    definition and conventions used.
+
+    Zero-padding, analogously with `ifft`, is performed by appending zeros to
+    the input along the specified dimension. Although this is the common
+    approach, it might lead to surprising results. If another form of zero
+    padding is desired, it must be performed before `ifft2` is called.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = 4 * np.eye(4)
+    >>> scipy.fft.ifft2(x)
+    array([[1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j], # may vary
+           [0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j],
+           [0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j],
+           [0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def rfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the N-D discrete Fourier Transform for real input.
+
+    This function computes the N-D discrete Fourier Transform over
+    any number of axes in an M-D real array by means of the Fast
+    Fourier Transform (FFT). By default, all axes are transformed, with the
+    real transform performed over the last axis, while the remaining
+    transforms are complex.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, taken to be real.
+    s : sequence of ints, optional
+        Shape (length along each transformed axis) to use from the input.
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        The final element of `s` corresponds to `n` for ``rfft(x, n)``, while
+        for the remaining axes, it corresponds to `n` for ``fft(x, n)``.
+        Along any axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` and `x`,
+        as explained in the parameters section above.
+        The length of the last axis transformed will be ``s[-1]//2+1``,
+        while the remaining transformed axes will have lengths according to
+        `s`, or unchanged from the input.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    irfftn : The inverse of `rfftn`, i.e., the inverse of the N-D FFT
+         of real input.
+    fft : The 1-D FFT, with definitions and conventions used.
+    rfft : The 1-D FFT of real input.
+    fftn : The N-D FFT.
+    rfft2 : The 2-D FFT of real input.
+
+    Notes
+    -----
+    The transform for real input is performed over the last transformation
+    axis, as by `rfft`, then the transform over the remaining axes is
+    performed as by `fftn`. The order of the output is as for `rfft` for the
+    final transformation axis, and as for `fftn` for the remaining
+    transformation axes.
+
+    See `fft` for details, definitions and conventions used.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.ones((2, 2, 2))
+    >>> scipy.fft.rfftn(x)
+    array([[[8.+0.j,  0.+0.j], # may vary
+            [0.+0.j,  0.+0.j]],
+           [[0.+0.j,  0.+0.j],
+            [0.+0.j,  0.+0.j]]])
+
+    >>> scipy.fft.rfftn(x, axes=(2, 0))
+    array([[[4.+0.j,  0.+0.j], # may vary
+            [4.+0.j,  0.+0.j]],
+           [[0.+0.j,  0.+0.j],
+            [0.+0.j,  0.+0.j]]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def rfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the 2-D FFT of a real array.
+
+    Parameters
+    ----------
+    x : array
+        Input array, taken to be real.
+    s : sequence of ints, optional
+        Shape of the FFT.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The result of the real 2-D FFT.
+
+    See Also
+    --------
+    irfft2 : The inverse of the 2-D FFT of real input.
+    rfft : The 1-D FFT of real input.
+    rfftn : Compute the N-D discrete Fourier Transform for real
+            input.
+
+    Notes
+    -----
+    This is really just `rfftn` with different default behavior.
+    For more details see `rfftn`.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.broadcast_to([1, 0, -1, 0], (4, 4))
+    >>> scipy.fft.rfft2(x)
+    array([[0.+0.j, 8.+0.j, 0.+0.j],
+           [0.+0.j, 0.+0.j, 0.+0.j],
+           [0.+0.j, 0.+0.j, 0.+0.j],
+           [0.+0.j, 0.+0.j, 0.+0.j]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def irfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+           plan=None):
+    """
+    Computes the inverse of `rfftn`
+
+    This function computes the inverse of the N-D discrete
+    Fourier Transform for real input over any number of axes in an
+    M-D array by means of the Fast Fourier Transform (FFT). In
+    other words, ``irfftn(rfftn(x), x.shape) == x`` to within numerical
+    accuracy. (The ``a.shape`` is necessary like ``len(a)`` is for `irfft`,
+    and for the same reason.)
+
+    The input should be ordered in the same way as is returned by `rfftn`,
+    i.e., as for `irfft` for the final transformation axis, and as for `ifftn`
+    along all the other axes.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the
+        number of input points used along this axis, except for the last axis,
+        where ``s[-1]//2+1`` points of the input are used.
+        Along any axis, if the shape indicated by `s` is smaller than that of
+        the input, the input is cropped. If it is larger, the input is padded
+        with zeros. If `s` is not given, the shape of the input along the axes
+        specified by axes is used. Except for the last axis which is taken to be
+        ``2*(m-1)``, where ``m`` is the length of the input along that axis.
+    axes : sequence of ints, optional
+        Axes over which to compute the inverse FFT. If not given, the last
+        `len(s)` axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` or `x`,
+        as explained in the parameters section above.
+        The length of each transformed axis is as given by the corresponding
+        element of `s`, or the length of the input in every axis except for the
+        last one if `s` is not given. In the final transformed axis the length
+        of the output when `s` is not given is ``2*(m-1)``, where ``m`` is the
+        length of the final transformed axis of the input. To get an odd
+        number of output points in the final axis, `s` must be specified.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    rfftn : The forward N-D FFT of real input,
+            of which `ifftn` is the inverse.
+    fft : The 1-D FFT, with definitions and conventions used.
+    irfft : The inverse of the 1-D FFT of real input.
+    irfft2 : The inverse of the 2-D FFT of real input.
+
+    Notes
+    -----
+    See `fft` for definitions and conventions used.
+
+    See `rfft` for definitions and conventions used for real input.
+
+    The default value of `s` assumes an even output length in the final
+    transformation axis. When performing the final complex to real
+    transformation, the Hermitian symmetry requires that the last imaginary
+    component along that axis must be 0 and so it is ignored. To avoid losing
+    information, the correct length of the real input *must* be given.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.zeros((3, 2, 2))
+    >>> x[0, 0, 0] = 3 * 2 * 2
+    >>> scipy.fft.irfftn(x)
+    array([[[1.,  1.],
+            [1.,  1.]],
+           [[1.,  1.],
+            [1.,  1.]],
+           [[1.,  1.],
+            [1.,  1.]]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def irfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+           plan=None):
+    """
+    Computes the inverse of `rfft2`
+
+    Parameters
+    ----------
+    x : array_like
+        The input array
+    s : sequence of ints, optional
+        Shape of the real output to the inverse FFT.
+    axes : sequence of ints, optional
+        The axes over which to compute the inverse fft.
+        Default is the last two axes.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The result of the inverse real 2-D FFT.
+
+    See Also
+    --------
+    rfft2 : The 2-D FFT of real input.
+    irfft : The inverse of the 1-D FFT of real input.
+    irfftn : The inverse of the N-D FFT of real input.
+
+    Notes
+    -----
+    This is really `irfftn` with different defaults.
+    For more details see `irfftn`.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def hfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the N-D FFT of Hermitian symmetric complex input, i.e., a
+    signal with a real spectrum.
+
+    This function computes the N-D discrete Fourier Transform for a
+    Hermitian symmetric complex input over any number of axes in an
+    M-D array by means of the Fast Fourier Transform (FFT). In other
+    words, ``ihfftn(hfftn(x, s)) == x`` to within numerical accuracy. (``s``
+    here is ``x.shape`` with ``s[-1] = x.shape[-1] * 2 - 1``, this is necessary
+    for the same reason ``x.shape`` would be necessary for `irfft`.)
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the
+        number of input points used along this axis, except for the last axis,
+        where ``s[-1]//2+1`` points of the input are used.
+        Along any axis, if the shape indicated by `s` is smaller than that of
+        the input, the input is cropped. If it is larger, the input is padded
+        with zeros. If `s` is not given, the shape of the input along the axes
+        specified by axes is used. Except for the last axis which is taken to be
+        ``2*(m-1)`` where ``m`` is the length of the input along that axis.
+    axes : sequence of ints, optional
+        Axes over which to compute the inverse FFT. If not given, the last
+        `len(s)` axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` or `x`,
+        as explained in the parameters section above.
+        The length of each transformed axis is as given by the corresponding
+        element of `s`, or the length of the input in every axis except for the
+        last one if `s` is not given.  In the final transformed axis the length
+        of the output when `s` is not given is ``2*(m-1)`` where ``m`` is the
+        length of the final transformed axis of the input.  To get an odd
+        number of output points in the final axis, `s` must be specified.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    ihfftn : The inverse N-D FFT with real spectrum. Inverse of `hfftn`.
+    fft : The 1-D FFT, with definitions and conventions used.
+    rfft : Forward FFT of real input.
+
+    Notes
+    -----
+    For a 1-D signal ``x`` to have a real spectrum, it must satisfy
+    the Hermitian property::
+
+        x[i] == np.conj(x[-i]) for all i
+
+    This generalizes into higher dimensions by reflecting over each axis in
+    turn::
+
+        x[i, j, k, ...] == np.conj(x[-i, -j, -k, ...]) for all i, j, k, ...
+
+    This should not be confused with a Hermitian matrix, for which the
+    transpose is its own conjugate::
+
+        x[i, j] == np.conj(x[j, i]) for all i, j
+
+
+    The default value of `s` assumes an even output length in the final
+    transformation axis. When performing the final complex to real
+    transformation, the Hermitian symmetry requires that the last imaginary
+    component along that axis must be 0 and so it is ignored. To avoid losing
+    information, the correct length of the real input *must* be given.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.ones((3, 2, 2))
+    >>> scipy.fft.hfftn(x)
+    array([[[12.,  0.],
+            [ 0.,  0.]],
+           [[ 0.,  0.],
+            [ 0.,  0.]],
+           [[ 0.,  0.],
+            [ 0.,  0.]]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def hfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the 2-D FFT of a Hermitian complex array.
+
+    Parameters
+    ----------
+    x : array
+        Input array, taken to be Hermitian complex.
+    s : sequence of ints, optional
+        Shape of the real output.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See `fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The real result of the 2-D Hermitian complex real FFT.
+
+    See Also
+    --------
+    hfftn : Compute the N-D discrete Fourier Transform for Hermitian
+            complex input.
+
+    Notes
+    -----
+    This is really just `hfftn` with different default behavior.
+    For more details see `hfftn`.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.array([[1+0j, 2+0j], [2+0j, 1+0j]])  # Hermitian-symmetric input
+    >>> scipy.fft.hfft2(x, s=(2, 2))
+    array([[ 6.,  0.],
+           [ 0., -2.]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def ihfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+           plan=None):
+    """
+    Compute the N-D inverse discrete Fourier Transform for a real
+    spectrum.
+
+    This function computes the N-D inverse discrete Fourier Transform
+    over any number of axes in an M-D real array by means of the Fast
+    Fourier Transform (FFT). By default, all axes are transformed, with the
+    real transform performed over the last axis, while the remaining transforms
+    are complex.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, taken to be real.
+    s : sequence of ints, optional
+        Shape (length along each transformed axis) to use from the input.
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        Along any axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` and `x`,
+        as explained in the parameters section above.
+        The length of the last axis transformed will be ``s[-1]//2+1``,
+        while the remaining transformed axes will have lengths according to
+        `s`, or unchanged from the input.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    hfftn : The forward N-D FFT of Hermitian input.
+    hfft : The 1-D FFT of Hermitian input.
+    fft : The 1-D FFT, with definitions and conventions used.
+    fftn : The N-D FFT.
+    hfft2 : The 2-D FFT of Hermitian input.
+
+    Notes
+    -----
+    The transform for real input is performed over the last transformation
+    axis, as by `ihfft`, then the transform over the remaining axes is
+    performed as by `ifftn`. The order of the output is the positive part of
+    the Hermitian output signal, in the same format as `rfft`.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.ones((2, 2, 2))
+    >>> scipy.fft.ihfftn(x)
+    array([[[1.+0.j,  0.+0.j], # may vary
+            [0.+0.j,  0.+0.j]],
+           [[0.+0.j,  0.+0.j],
+            [0.+0.j,  0.+0.j]]])
+    >>> scipy.fft.ihfftn(x, axes=(2, 0))
+    array([[[1.+0.j,  0.+0.j], # may vary
+            [1.+0.j,  0.+0.j]],
+           [[0.+0.j,  0.+0.j],
+            [0.+0.j,  0.+0.j]]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def ihfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+           plan=None):
+    """
+    Compute the 2-D inverse FFT of a real spectrum.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array
+    s : sequence of ints, optional
+        Shape of the real input to the inverse FFT.
+    axes : sequence of ints, optional
+        The axes over which to compute the inverse fft.
+        Default is the last two axes.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The result of the inverse real 2-D FFT.
+
+    See Also
+    --------
+    ihfftn : Compute the inverse of the N-D FFT of Hermitian input.
+
+    Notes
+    -----
+    This is really `ihfftn` with different defaults.
+    For more details see `ihfftn`.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_basic_backend.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_basic_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..775b26a8bf5922f7fa3634ad6c8c708a96820931
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_basic_backend.py
@@ -0,0 +1,197 @@
+from scipy._lib._array_api import (
+    array_namespace, is_numpy, xp_unsupported_param_msg, is_complex, xp_float_to_complex
+)
+from . import _pocketfft
+import numpy as np
+
+
+def _validate_fft_args(workers, plan, norm):
+    if workers is not None:
+        raise ValueError(xp_unsupported_param_msg("workers"))
+    if plan is not None:
+        raise ValueError(xp_unsupported_param_msg("plan"))
+    if norm is None:
+        norm = 'backward'
+    return norm
+
+
+# these functions expect complex input in the fft standard extension
+complex_funcs = {'fft', 'ifft', 'fftn', 'ifftn', 'hfft', 'irfft', 'irfftn'}
+
+# pocketfft is used whenever SCIPY_ARRAY_API is not set,
+# or x is a NumPy array or array-like.
+# When SCIPY_ARRAY_API is set, we try to use xp.fft for CuPy arrays,
+# PyTorch arrays and other array API standard supporting objects.
+# If xp.fft does not exist, we attempt to convert to np and back to use pocketfft.
+
+def _execute_1D(func_str, pocketfft_func, x, n, axis, norm, overwrite_x, workers, plan):
+    xp = array_namespace(x)
+
+    if is_numpy(xp):
+        x = np.asarray(x)
+        return pocketfft_func(x, n=n, axis=axis, norm=norm,
+                              overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+    norm = _validate_fft_args(workers, plan, norm)
+    if hasattr(xp, 'fft'):
+        xp_func = getattr(xp.fft, func_str)
+        if func_str in complex_funcs:
+            try:
+                res = xp_func(x, n=n, axis=axis, norm=norm)
+            except: # backends may require complex input  # noqa: E722
+                x = xp_float_to_complex(x, xp)
+                res = xp_func(x, n=n, axis=axis, norm=norm)
+            return res
+        return xp_func(x, n=n, axis=axis, norm=norm)
+
+    x = np.asarray(x)
+    y = pocketfft_func(x, n=n, axis=axis, norm=norm)
+    return xp.asarray(y)
+
+
+def _execute_nD(func_str, pocketfft_func, x, s, axes, norm, overwrite_x, workers, plan):
+    xp = array_namespace(x)
+    
+    if is_numpy(xp):
+        x = np.asarray(x)
+        return pocketfft_func(x, s=s, axes=axes, norm=norm,
+                              overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+    norm = _validate_fft_args(workers, plan, norm)
+    if hasattr(xp, 'fft'):
+        xp_func = getattr(xp.fft, func_str)
+        if func_str in complex_funcs:
+            try:
+                res = xp_func(x, s=s, axes=axes, norm=norm)
+            except: # backends may require complex input  # noqa: E722
+                x = xp_float_to_complex(x, xp)
+                res = xp_func(x, s=s, axes=axes, norm=norm)
+            return res
+        return xp_func(x, s=s, axes=axes, norm=norm)
+
+    x = np.asarray(x)
+    y = pocketfft_func(x, s=s, axes=axes, norm=norm)
+    return xp.asarray(y)
+
+
+def fft(x, n=None, axis=-1, norm=None,
+        overwrite_x=False, workers=None, *, plan=None):
+    return _execute_1D('fft', _pocketfft.fft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def ifft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    return _execute_1D('ifft', _pocketfft.ifft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def rfft(x, n=None, axis=-1, norm=None,
+         overwrite_x=False, workers=None, *, plan=None):
+    return _execute_1D('rfft', _pocketfft.rfft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def irfft(x, n=None, axis=-1, norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return _execute_1D('irfft', _pocketfft.irfft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def hfft(x, n=None, axis=-1, norm=None,
+         overwrite_x=False, workers=None, *, plan=None):
+    return _execute_1D('hfft', _pocketfft.hfft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def ihfft(x, n=None, axis=-1, norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return _execute_1D('ihfft', _pocketfft.ihfft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def fftn(x, s=None, axes=None, norm=None,
+         overwrite_x=False, workers=None, *, plan=None):
+    return _execute_nD('fftn', _pocketfft.fftn, x, s=s, axes=axes, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+
+def ifftn(x, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return _execute_nD('ifftn', _pocketfft.ifftn, x, s=s, axes=axes, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def fft2(x, s=None, axes=(-2, -1), norm=None,
+         overwrite_x=False, workers=None, *, plan=None):
+    return fftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+
+
+def ifft2(x, s=None, axes=(-2, -1), norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return ifftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+
+
+def rfftn(x, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return _execute_nD('rfftn', _pocketfft.rfftn, x, s=s, axes=axes, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def rfft2(x, s=None, axes=(-2, -1), norm=None,
+         overwrite_x=False, workers=None, *, plan=None):
+    return rfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+
+
+def irfftn(x, s=None, axes=None, norm=None,
+           overwrite_x=False, workers=None, *, plan=None):
+    return _execute_nD('irfftn', _pocketfft.irfftn, x, s=s, axes=axes, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def irfft2(x, s=None, axes=(-2, -1), norm=None,
+           overwrite_x=False, workers=None, *, plan=None):
+    return irfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+
+
+def _swap_direction(norm):
+    if norm in (None, 'backward'):
+        norm = 'forward'
+    elif norm == 'forward':
+        norm = 'backward'
+    elif norm != 'ortho':
+        raise ValueError(f'Invalid norm value {norm}; should be "backward", '
+                         '"ortho", or "forward".')
+    return norm
+
+
+def hfftn(x, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    xp = array_namespace(x)
+    if is_numpy(xp):
+        x = np.asarray(x)
+        return _pocketfft.hfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+    if is_complex(x, xp):
+        x = xp.conj(x)
+    return irfftn(x, s, axes, _swap_direction(norm),
+                  overwrite_x, workers, plan=plan)
+
+
+def hfft2(x, s=None, axes=(-2, -1), norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return hfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+
+
+def ihfftn(x, s=None, axes=None, norm=None,
+           overwrite_x=False, workers=None, *, plan=None):
+    xp = array_namespace(x)
+    if is_numpy(xp):
+        x = np.asarray(x)
+        return _pocketfft.ihfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+    return xp.conj(rfftn(x, s, axes, _swap_direction(norm),
+                         overwrite_x, workers, plan=plan))
+
+def ihfft2(x, s=None, axes=(-2, -1), norm=None,
+           overwrite_x=False, workers=None, *, plan=None):
+    return ihfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_debug_backends.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_debug_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9647c5d6ceddc73b97d95f562662ada02c1ae74
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_debug_backends.py
@@ -0,0 +1,22 @@
+import numpy as np
+
+class NumPyBackend:
+    """Backend that uses numpy.fft"""
+    __ua_domain__ = "numpy.scipy.fft"
+
+    @staticmethod
+    def __ua_function__(method, args, kwargs):
+        kwargs.pop("overwrite_x", None)
+
+        fn = getattr(np.fft, method.__name__, None)
+        return (NotImplemented if fn is None
+                else fn(*args, **kwargs))
+
+
+class EchoBackend:
+    """Backend that just prints the __ua_function__ arguments"""
+    __ua_domain__ = "numpy.scipy.fft"
+
+    @staticmethod
+    def __ua_function__(method, args, kwargs):
+        print(method, args, kwargs, sep='\n')
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_fftlog.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_fftlog.py
new file mode 100644
index 0000000000000000000000000000000000000000..61bbe802bbb4a40df8ca3b653c693105b29c6578
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_fftlog.py
@@ -0,0 +1,223 @@
+"""Fast Hankel transforms using the FFTLog algorithm.
+
+The implementation closely follows the Fortran code of Hamilton (2000).
+
+added: 14/11/2020 Nicolas Tessore 
+"""
+
+from ._basic import _dispatch
+from scipy._lib.uarray import Dispatchable
+from ._fftlog_backend import fhtoffset
+import numpy as np
+
+__all__ = ['fht', 'ifht', 'fhtoffset']
+
+
+@_dispatch
+def fht(a, dln, mu, offset=0.0, bias=0.0):
+    r'''Compute the fast Hankel transform.
+
+    Computes the discrete Hankel transform of a logarithmically spaced periodic
+    sequence using the FFTLog algorithm [1]_, [2]_.
+
+    Parameters
+    ----------
+    a : array_like (..., n)
+        Real periodic input array, uniformly logarithmically spaced.  For
+        multidimensional input, the transform is performed over the last axis.
+    dln : float
+        Uniform logarithmic spacing of the input array.
+    mu : float
+        Order of the Hankel transform, any positive or negative real number.
+    offset : float, optional
+        Offset of the uniform logarithmic spacing of the output array.
+    bias : float, optional
+        Exponent of power law bias, any positive or negative real number.
+
+    Returns
+    -------
+    A : array_like (..., n)
+        The transformed output array, which is real, periodic, uniformly
+        logarithmically spaced, and of the same shape as the input array.
+
+    See Also
+    --------
+    ifht : The inverse of `fht`.
+    fhtoffset : Return an optimal offset for `fht`.
+
+    Notes
+    -----
+    This function computes a discrete version of the Hankel transform
+
+    .. math::
+
+        A(k) = \int_{0}^{\infty} \! a(r) \, J_\mu(kr) \, k \, dr \;,
+
+    where :math:`J_\mu` is the Bessel function of order :math:`\mu`.  The index
+    :math:`\mu` may be any real number, positive or negative.  Note that the
+    numerical Hankel transform uses an integrand of :math:`k \, dr`, while the
+    mathematical Hankel transform is commonly defined using :math:`r \, dr`.
+
+    The input array `a` is a periodic sequence of length :math:`n`, uniformly
+    logarithmically spaced with spacing `dln`,
+
+    .. math::
+
+        a_j = a(r_j) \;, \quad
+        r_j = r_c \exp[(j-j_c) \, \mathtt{dln}]
+
+    centred about the point :math:`r_c`.  Note that the central index
+    :math:`j_c = (n-1)/2` is half-integral if :math:`n` is even, so that
+    :math:`r_c` falls between two input elements.  Similarly, the output
+    array `A` is a periodic sequence of length :math:`n`, also uniformly
+    logarithmically spaced with spacing `dln`
+
+    .. math::
+
+       A_j = A(k_j) \;, \quad
+       k_j = k_c \exp[(j-j_c) \, \mathtt{dln}]
+
+    centred about the point :math:`k_c`.
+
+    The centre points :math:`r_c` and :math:`k_c` of the periodic intervals may
+    be chosen arbitrarily, but it would be usual to choose the product
+    :math:`k_c r_c = k_j r_{n-1-j} = k_{n-1-j} r_j` to be unity.  This can be
+    changed using the `offset` parameter, which controls the logarithmic offset
+    :math:`\log(k_c) = \mathtt{offset} - \log(r_c)` of the output array.
+    Choosing an optimal value for `offset` may reduce ringing of the discrete
+    Hankel transform.
+
+    If the `bias` parameter is nonzero, this function computes a discrete
+    version of the biased Hankel transform
+
+    .. math::
+
+        A(k) = \int_{0}^{\infty} \! a_q(r) \, (kr)^q \, J_\mu(kr) \, k \, dr
+
+    where :math:`q` is the value of `bias`, and a power law bias
+    :math:`a_q(r) = a(r) \, (kr)^{-q}` is applied to the input sequence.
+    Biasing the transform can help approximate the continuous transform of
+    :math:`a(r)` if there is a value :math:`q` such that :math:`a_q(r)` is
+    close to a periodic sequence, in which case the resulting :math:`A(k)` will
+    be close to the continuous transform.
+
+    References
+    ----------
+    .. [1] Talman J. D., 1978, J. Comp. Phys., 29, 35
+    .. [2] Hamilton A. J. S., 2000, MNRAS, 312, 257 (astro-ph/9905191)
+
+    Examples
+    --------
+
+    This example is the adapted version of ``fftlogtest.f`` which is provided
+    in [2]_. It evaluates the integral
+
+    .. math::
+
+        \int^\infty_0 r^{\mu+1} \exp(-r^2/2) J_\mu(kr) k dr
+        = k^{\mu+1} \exp(-k^2/2) .
+
+    >>> import numpy as np
+    >>> from scipy import fft
+    >>> import matplotlib.pyplot as plt
+
+    Parameters for the transform.
+
+    >>> mu = 0.0                     # Order mu of Bessel function
+    >>> r = np.logspace(-7, 1, 128)  # Input evaluation points
+    >>> dln = np.log(r[1]/r[0])      # Step size
+    >>> offset = fft.fhtoffset(dln, initial=-6*np.log(10), mu=mu)
+    >>> k = np.exp(offset)/r[::-1]   # Output evaluation points
+
+    Define the analytical function.
+
+    >>> def f(x, mu):
+    ...     """Analytical function: x^(mu+1) exp(-x^2/2)."""
+    ...     return x**(mu + 1)*np.exp(-x**2/2)
+
+    Evaluate the function at ``r`` and compute the corresponding values at
+    ``k`` using FFTLog.
+
+    >>> a_r = f(r, mu)
+    >>> fht = fft.fht(a_r, dln, mu=mu, offset=offset)
+
+    For this example we can actually compute the analytical response (which in
+    this case is the same as the input function) for comparison and compute the
+    relative error.
+
+    >>> a_k = f(k, mu)
+    >>> rel_err = abs((fht-a_k)/a_k)
+
+    Plot the result.
+
+    >>> figargs = {'sharex': True, 'sharey': True, 'constrained_layout': True}
+    >>> fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), **figargs)
+    >>> ax1.set_title(r'$r^{\mu+1}\ \exp(-r^2/2)$')
+    >>> ax1.loglog(r, a_r, 'k', lw=2)
+    >>> ax1.set_xlabel('r')
+    >>> ax2.set_title(r'$k^{\mu+1} \exp(-k^2/2)$')
+    >>> ax2.loglog(k, a_k, 'k', lw=2, label='Analytical')
+    >>> ax2.loglog(k, fht, 'C3--', lw=2, label='FFTLog')
+    >>> ax2.set_xlabel('k')
+    >>> ax2.legend(loc=3, framealpha=1)
+    >>> ax2.set_ylim([1e-10, 1e1])
+    >>> ax2b = ax2.twinx()
+    >>> ax2b.loglog(k, rel_err, 'C0', label='Rel. Error (-)')
+    >>> ax2b.set_ylabel('Rel. Error (-)', color='C0')
+    >>> ax2b.tick_params(axis='y', labelcolor='C0')
+    >>> ax2b.legend(loc=4, framealpha=1)
+    >>> ax2b.set_ylim([1e-9, 1e-3])
+    >>> plt.show()
+
+    '''
+    return (Dispatchable(a, np.ndarray),)
+
+
+@_dispatch
+def ifht(A, dln, mu, offset=0.0, bias=0.0):
+    r"""Compute the inverse fast Hankel transform.
+
+    Computes the discrete inverse Hankel transform of a logarithmically spaced
+    periodic sequence. This is the inverse operation to `fht`.
+
+    Parameters
+    ----------
+    A : array_like (..., n)
+        Real periodic input array, uniformly logarithmically spaced.  For
+        multidimensional input, the transform is performed over the last axis.
+    dln : float
+        Uniform logarithmic spacing of the input array.
+    mu : float
+        Order of the Hankel transform, any positive or negative real number.
+    offset : float, optional
+        Offset of the uniform logarithmic spacing of the output array.
+    bias : float, optional
+        Exponent of power law bias, any positive or negative real number.
+
+    Returns
+    -------
+    a : array_like (..., n)
+        The transformed output array, which is real, periodic, uniformly
+        logarithmically spaced, and of the same shape as the input array.
+
+    See Also
+    --------
+    fht : Definition of the fast Hankel transform.
+    fhtoffset : Return an optimal offset for `ifht`.
+
+    Notes
+    -----
+    This function computes a discrete version of the Hankel transform
+
+    .. math::
+
+        a(r) = \int_{0}^{\infty} \! A(k) \, J_\mu(kr) \, r \, dk \;,
+
+    where :math:`J_\mu` is the Bessel function of order :math:`\mu`.  The index
+    :math:`\mu` may be any real number, positive or negative. Note that the
+    numerical inverse Hankel transform uses an integrand of :math:`r \, dk`, while the
+    mathematical inverse Hankel transform is commonly defined using :math:`k \, dk`.
+
+    See `fht` for further details.
+    """
+    return (Dispatchable(A, np.ndarray),)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_fftlog_backend.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_fftlog_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b38733aaa349c301ba7d5b83691c55204dc8991
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_fftlog_backend.py
@@ -0,0 +1,200 @@
+import numpy as np
+from warnings import warn
+from ._basic import rfft, irfft
+from ..special import loggamma, poch
+
+from scipy._lib._array_api import array_namespace
+
+__all__ = ['fht', 'ifht', 'fhtoffset']
+
+# constants
+LN_2 = np.log(2)
+
+
+def fht(a, dln, mu, offset=0.0, bias=0.0):
+    xp = array_namespace(a)
+    a = xp.asarray(a)
+
+    # size of transform
+    n = a.shape[-1]
+
+    # bias input array
+    if bias != 0:
+        # a_q(r) = a(r) (r/r_c)^{-q}
+        j_c = (n-1)/2
+        j = xp.arange(n, dtype=xp.float64)
+        a = a * xp.exp(-bias*(j - j_c)*dln)
+
+    # compute FHT coefficients
+    u = xp.asarray(fhtcoeff(n, dln, mu, offset=offset, bias=bias))
+
+    # transform
+    A = _fhtq(a, u, xp=xp)
+
+    # bias output array
+    if bias != 0:
+        # A(k) = A_q(k) (k/k_c)^{-q} (k_c r_c)^{-q}
+        A *= xp.exp(-bias*((j - j_c)*dln + offset))
+
+    return A
+
+
+def ifht(A, dln, mu, offset=0.0, bias=0.0):
+    xp = array_namespace(A)
+    A = xp.asarray(A)
+
+    # size of transform
+    n = A.shape[-1]
+
+    # bias input array
+    if bias != 0:
+        # A_q(k) = A(k) (k/k_c)^{q} (k_c r_c)^{q}
+        j_c = (n-1)/2
+        j = xp.arange(n, dtype=xp.float64)
+        A = A * xp.exp(bias*((j - j_c)*dln + offset))
+
+    # compute FHT coefficients
+    u = xp.asarray(fhtcoeff(n, dln, mu, offset=offset, bias=bias, inverse=True))
+
+    # transform
+    a = _fhtq(A, u, inverse=True, xp=xp)
+
+    # bias output array
+    if bias != 0:
+        # a(r) = a_q(r) (r/r_c)^{q}
+        a /= xp.exp(-bias*(j - j_c)*dln)
+
+    return a
+
+
+def fhtcoeff(n, dln, mu, offset=0.0, bias=0.0, inverse=False):
+    """Compute the coefficient array for a fast Hankel transform."""
+    lnkr, q = offset, bias
+
+    # Hankel transform coefficients
+    # u_m = (kr)^{-i 2m pi/(n dlnr)} U_mu(q + i 2m pi/(n dlnr))
+    # with U_mu(x) = 2^x Gamma((mu+1+x)/2)/Gamma((mu+1-x)/2)
+    xp = (mu+1+q)/2
+    xm = (mu+1-q)/2
+    y = np.linspace(0, np.pi*(n//2)/(n*dln), n//2+1)
+    u = np.empty(n//2+1, dtype=complex)
+    v = np.empty(n//2+1, dtype=complex)
+    u.imag[:] = y
+    u.real[:] = xm
+    loggamma(u, out=v)
+    u.real[:] = xp
+    loggamma(u, out=u)
+    y *= 2*(LN_2 - lnkr)
+    u.real -= v.real
+    u.real += LN_2*q
+    u.imag += v.imag
+    u.imag += y
+    np.exp(u, out=u)
+
+    # fix last coefficient to be real
+    if n % 2 == 0:
+        u.imag[-1] = 0
+
+    # deal with special cases
+    if not np.isfinite(u[0]):
+        # write u_0 = 2^q Gamma(xp)/Gamma(xm) = 2^q poch(xm, xp-xm)
+        # poch() handles special cases for negative integers correctly
+        u[0] = 2**q * poch(xm, xp-xm)
+        # the coefficient may be inf or 0, meaning the transform or the
+        # inverse transform, respectively, is singular
+
+    # check for singular transform or singular inverse transform
+    if np.isinf(u[0]) and not inverse:
+        warn('singular transform; consider changing the bias', stacklevel=3)
+        # fix coefficient to obtain (potentially correct) transform anyway
+        u = np.copy(u)
+        u[0] = 0
+    elif u[0] == 0 and inverse:
+        warn('singular inverse transform; consider changing the bias', stacklevel=3)
+        # fix coefficient to obtain (potentially correct) inverse anyway
+        u = np.copy(u)
+        u[0] = np.inf
+
+    return u
+
+
+def fhtoffset(dln, mu, initial=0.0, bias=0.0):
+    """Return optimal offset for a fast Hankel transform.
+
+    Returns an offset close to `initial` that fulfils the low-ringing
+    condition of [1]_ for the fast Hankel transform `fht` with logarithmic
+    spacing `dln`, order `mu` and bias `bias`.
+
+    Parameters
+    ----------
+    dln : float
+        Uniform logarithmic spacing of the transform.
+    mu : float
+        Order of the Hankel transform, any positive or negative real number.
+    initial : float, optional
+        Initial value for the offset. Returns the closest value that fulfils
+        the low-ringing condition.
+    bias : float, optional
+        Exponent of power law bias, any positive or negative real number.
+
+    Returns
+    -------
+    offset : float
+        Optimal offset of the uniform logarithmic spacing of the transform that
+        fulfils a low-ringing condition.
+
+    Examples
+    --------
+    >>> from scipy.fft import fhtoffset
+    >>> dln = 0.1
+    >>> mu = 2.0
+    >>> initial = 0.5
+    >>> bias = 0.0
+    >>> offset = fhtoffset(dln, mu, initial, bias)
+    >>> offset
+    0.5454581477676637
+
+    See Also
+    --------
+    fht : Definition of the fast Hankel transform.
+
+    References
+    ----------
+    .. [1] Hamilton A. J. S., 2000, MNRAS, 312, 257 (astro-ph/9905191)
+
+    """
+
+    lnkr, q = initial, bias
+
+    xp = (mu+1+q)/2
+    xm = (mu+1-q)/2
+    y = np.pi/(2*dln)
+    zp = loggamma(xp + 1j*y)
+    zm = loggamma(xm + 1j*y)
+    arg = (LN_2 - lnkr)/dln + (zp.imag + zm.imag)/np.pi
+    return lnkr + (arg - np.round(arg))*dln
+
+
+def _fhtq(a, u, inverse=False, *, xp=None):
+    """Compute the biased fast Hankel transform.
+
+    This is the basic FFTLog routine.
+    """
+    if xp is None:
+        xp = np
+
+    # size of transform
+    n = a.shape[-1]
+
+    # biased fast Hankel transform via real FFT
+    A = rfft(a, axis=-1)
+    if not inverse:
+        # forward transform
+        A *= u
+    else:
+        # backward transform
+        A /= xp.conj(u)
+    A = irfft(A, n, axis=-1)
+    A = xp.flip(A, axis=-1)
+
+    return A
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_helper.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a0cdaf3cd47559c300d57e27d539dabca84db9c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_helper.py
@@ -0,0 +1,348 @@
+from functools import update_wrapper, lru_cache
+import inspect
+
+from ._pocketfft import helper as _helper
+
+import numpy as np
+from scipy._lib._array_api import array_namespace
+
+
+_init_nd_shape_and_axes = _helper._init_nd_shape_and_axes
+
+
+def next_fast_len(target, real=False):
+    """Find the next fast size of input data to ``fft``, for zero-padding, etc.
+
+    SciPy's FFT algorithms gain their speed by a recursive divide and conquer
+    strategy. This relies on efficient functions for small prime factors of the
+    input length. Thus, the transforms are fastest when using composites of the
+    prime factors handled by the fft implementation. If there are efficient
+    functions for all radices <= `n`, then the result will be a number `x`
+    >= ``target`` with only prime factors < `n`. (Also known as `n`-smooth
+    numbers)
+
+    Parameters
+    ----------
+    target : int
+        Length to start searching from. Must be a positive integer.
+    real : bool, optional
+        True if the FFT involves real input or output (e.g., `rfft` or `hfft`
+        but not `fft`). Defaults to False.
+
+    Returns
+    -------
+    out : int
+        The smallest fast length greater than or equal to ``target``.
+
+    Notes
+    -----
+    The result of this function may change in future as performance
+    considerations change, for example, if new prime factors are added.
+
+    Calling `fft` or `ifft` with real input data performs an ``'R2C'``
+    transform internally.
+
+    Examples
+    --------
+    On a particular machine, an FFT of prime length takes 11.4 ms:
+
+    >>> from scipy import fft
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> min_len = 93059  # prime length is worst case for speed
+    >>> a = rng.standard_normal(min_len)
+    >>> b = fft.fft(a)
+
+    Zero-padding to the next regular length reduces computation time to
+    1.6 ms, a speedup of 7.3 times:
+
+    >>> fft.next_fast_len(min_len, real=True)
+    93312
+    >>> b = fft.fft(a, 93312)
+
+    Rounding up to the next power of 2 is not optimal, taking 3.0 ms to
+    compute; 1.9 times longer than the size given by ``next_fast_len``:
+
+    >>> b = fft.fft(a, 131072)
+
+    """
+    pass
+
+
+# Directly wrap the c-function good_size but take the docstring etc., from the
+# next_fast_len function above
+_sig = inspect.signature(next_fast_len)
+next_fast_len = update_wrapper(lru_cache(_helper.good_size), next_fast_len)
+next_fast_len.__wrapped__ = _helper.good_size
+next_fast_len.__signature__ = _sig
+
+
+def prev_fast_len(target, real=False):
+    """Find the previous fast size of input data to ``fft``.
+    Useful for discarding a minimal number of samples before FFT.
+
+    SciPy's FFT algorithms gain their speed by a recursive divide and conquer
+    strategy. This relies on efficient functions for small prime factors of the
+    input length. Thus, the transforms are fastest when using composites of the
+    prime factors handled by the fft implementation. If there are efficient
+    functions for all radices <= `n`, then the result will be a number `x`
+    <= ``target`` with only prime factors <= `n`. (Also known as `n`-smooth
+    numbers)
+
+    Parameters
+    ----------
+    target : int
+        Maximum length to search until. Must be a positive integer.
+    real : bool, optional
+        True if the FFT involves real input or output (e.g., `rfft` or `hfft`
+        but not `fft`). Defaults to False.
+
+    Returns
+    -------
+    out : int
+        The largest fast length less than or equal to ``target``.
+
+    Notes
+    -----
+    The result of this function may change in future as performance
+    considerations change, for example, if new prime factors are added.
+
+    Calling `fft` or `ifft` with real input data performs an ``'R2C'``
+    transform internally.
+
+    In the current implementation, prev_fast_len assumes radices of
+    2,3,5,7,11 for complex FFT and 2,3,5 for real FFT.
+
+    Examples
+    --------
+    On a particular machine, an FFT of prime length takes 16.2 ms:
+
+    >>> from scipy import fft
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> max_len = 93059  # prime length is worst case for speed
+    >>> a = rng.standard_normal(max_len)
+    >>> b = fft.fft(a)
+
+    Performing FFT on the maximum fast length less than max_len
+    reduces the computation time to 1.5 ms, a speedup of 10.5 times:
+
+    >>> fft.prev_fast_len(max_len, real=True)
+    92160
+    >>> c = fft.fft(a[:92160]) # discard last 899 samples
+
+    """
+    pass
+
+
+# Directly wrap the c-function prev_good_size but take the docstring etc.,
+# from the prev_fast_len function above
+_sig_prev_fast_len = inspect.signature(prev_fast_len)
+prev_fast_len = update_wrapper(lru_cache()(_helper.prev_good_size), prev_fast_len)
+prev_fast_len.__wrapped__ = _helper.prev_good_size
+prev_fast_len.__signature__ = _sig_prev_fast_len
+
+
+def fftfreq(n, d=1.0, *, xp=None, device=None):
+    """Return the Discrete Fourier Transform sample frequencies.
+
+    The returned float array `f` contains the frequency bin centers in cycles
+    per unit of the sample spacing (with zero at the start).  For instance, if
+    the sample spacing is in seconds, then the frequency unit is cycles/second.
+
+    Given a window length `n` and a sample spacing `d`::
+
+      f = [0, 1, ...,   n/2-1,     -n/2, ..., -1] / (d*n)   if n is even
+      f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n)   if n is odd
+
+    Parameters
+    ----------
+    n : int
+        Window length.
+    d : scalar, optional
+        Sample spacing (inverse of the sampling rate). Defaults to 1.
+    xp : array_namespace, optional
+        The namespace for the return array. Default is None, where NumPy is used.
+    device : device, optional
+        The device for the return array.
+        Only valid when `xp.fft.fftfreq` implements the device parameter.
+     
+    Returns
+    -------
+    f : ndarray
+        Array of length `n` containing the sample frequencies.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.fft
+    >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float)
+    >>> fourier = scipy.fft.fft(signal)
+    >>> n = signal.size
+    >>> timestep = 0.1
+    >>> freq = scipy.fft.fftfreq(n, d=timestep)
+    >>> freq
+    array([ 0.  ,  1.25,  2.5 , ..., -3.75, -2.5 , -1.25])
+
+    """
+    xp = np if xp is None else xp
+    # numpy does not yet support the `device` keyword
+    # `xp.__name__ != 'numpy'` should be removed when numpy is compatible
+    if hasattr(xp, 'fft') and xp.__name__ != 'numpy':
+        return xp.fft.fftfreq(n, d=d, device=device)
+    if device is not None:
+        raise ValueError('device parameter is not supported for input array type')
+    return np.fft.fftfreq(n, d=d)
+
+
+def rfftfreq(n, d=1.0, *, xp=None, device=None):
+    """Return the Discrete Fourier Transform sample frequencies
+    (for usage with rfft, irfft).
+
+    The returned float array `f` contains the frequency bin centers in cycles
+    per unit of the sample spacing (with zero at the start).  For instance, if
+    the sample spacing is in seconds, then the frequency unit is cycles/second.
+
+    Given a window length `n` and a sample spacing `d`::
+
+      f = [0, 1, ...,     n/2-1,     n/2] / (d*n)   if n is even
+      f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n)   if n is odd
+
+    Unlike `fftfreq` (but like `scipy.fftpack.rfftfreq`)
+    the Nyquist frequency component is considered to be positive.
+
+    Parameters
+    ----------
+    n : int
+        Window length.
+    d : scalar, optional
+        Sample spacing (inverse of the sampling rate). Defaults to 1.
+    xp : array_namespace, optional
+        The namespace for the return array. Default is None, where NumPy is used.
+    device : device, optional
+        The device for the return array.
+        Only valid when `xp.fft.rfftfreq` implements the device parameter.
+
+    Returns
+    -------
+    f : ndarray
+        Array of length ``n//2 + 1`` containing the sample frequencies.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.fft
+    >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5, -3, 4], dtype=float)
+    >>> fourier = scipy.fft.rfft(signal)
+    >>> n = signal.size
+    >>> sample_rate = 100
+    >>> freq = scipy.fft.fftfreq(n, d=1./sample_rate)
+    >>> freq
+    array([  0.,  10.,  20., ..., -30., -20., -10.])
+    >>> freq = scipy.fft.rfftfreq(n, d=1./sample_rate)
+    >>> freq
+    array([  0.,  10.,  20.,  30.,  40.,  50.])
+
+    """
+    xp = np if xp is None else xp
+    # numpy does not yet support the `device` keyword
+    # `xp.__name__ != 'numpy'` should be removed when numpy is compatible
+    if hasattr(xp, 'fft') and xp.__name__ != 'numpy':
+        return xp.fft.rfftfreq(n, d=d, device=device)
+    if device is not None:
+        raise ValueError('device parameter is not supported for input array type')
+    return np.fft.rfftfreq(n, d=d)
+
+
+def fftshift(x, axes=None):
+    """Shift the zero-frequency component to the center of the spectrum.
+
+    This function swaps half-spaces for all axes listed (defaults to all).
+    Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    axes : int or shape tuple, optional
+        Axes over which to shift.  Default is None, which shifts all axes.
+
+    Returns
+    -------
+    y : ndarray
+        The shifted array.
+
+    See Also
+    --------
+    ifftshift : The inverse of `fftshift`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> freqs = np.fft.fftfreq(10, 0.1)
+    >>> freqs
+    array([ 0.,  1.,  2., ..., -3., -2., -1.])
+    >>> np.fft.fftshift(freqs)
+    array([-5., -4., -3., -2., -1.,  0.,  1.,  2.,  3.,  4.])
+
+    Shift the zero-frequency component only along the second axis:
+
+    >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
+    >>> freqs
+    array([[ 0.,  1.,  2.],
+           [ 3.,  4., -4.],
+           [-3., -2., -1.]])
+    >>> np.fft.fftshift(freqs, axes=(1,))
+    array([[ 2.,  0.,  1.],
+           [-4.,  3.,  4.],
+           [-1., -3., -2.]])
+
+    """
+    xp = array_namespace(x)
+    if hasattr(xp, 'fft'):
+        return xp.fft.fftshift(x, axes=axes)
+    x = np.asarray(x)
+    y = np.fft.fftshift(x, axes=axes)
+    return xp.asarray(y)
+
+
+def ifftshift(x, axes=None):
+    """The inverse of `fftshift`. Although identical for even-length `x`, the
+    functions differ by one sample for odd-length `x`.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    axes : int or shape tuple, optional
+        Axes over which to calculate.  Defaults to None, which shifts all axes.
+
+    Returns
+    -------
+    y : ndarray
+        The shifted array.
+
+    See Also
+    --------
+    fftshift : Shift zero-frequency component to the center of the spectrum.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
+    >>> freqs
+    array([[ 0.,  1.,  2.],
+           [ 3.,  4., -4.],
+           [-3., -2., -1.]])
+    >>> np.fft.ifftshift(np.fft.fftshift(freqs))
+    array([[ 0.,  1.,  2.],
+           [ 3.,  4., -4.],
+           [-3., -2., -1.]])
+
+    """
+    xp = array_namespace(x)
+    if hasattr(xp, 'fft'):
+        return xp.fft.ifftshift(x, axes=axes)
+    x = np.asarray(x)
+    y = np.fft.ifftshift(x, axes=axes)
+    return xp.asarray(y)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_realtransforms.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_realtransforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7324f5d9a81e692eead2df4475c20c4ec0defe5
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_realtransforms.py
@@ -0,0 +1,706 @@
+from ._basic import _dispatch
+from scipy._lib.uarray import Dispatchable
+import numpy as np
+
+__all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn']
+
+
+@_dispatch
+def dctn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
+         workers=None, *, orthogonalize=None):
+    """
+    Return multidimensional Discrete Cosine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    s : int or array_like of ints or None, optional
+        The shape of the result. If both `s` and `axes` (see below) are None,
+        `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is
+        ``numpy.take(x.shape, axes, axis=0)``.
+        If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
+        If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
+        ``s[i]``.
+        If any element of `s` is -1, the size of the corresponding dimension of
+        `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes over which the DCT is computed. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized DCT variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    idctn : Inverse multidimensional DCT
+
+    Notes
+    -----
+    For full details of the DCT types and normalization modes, as well as
+    references, see `dct`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fft import dctn, idctn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idctn(dctn(y)))
+    True
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def idctn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
+          workers=None, orthogonalize=None):
+    """
+    Return multidimensional Inverse Discrete Cosine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    s : int or array_like of ints or None, optional
+        The shape of the result.  If both `s` and `axes` (see below) are
+        None, `s` is ``x.shape``; if `s` is None but `axes` is
+        not None, then `s` is ``numpy.take(x.shape, axes, axis=0)``.
+        If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
+        If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
+        ``s[i]``.
+        If any element of `s` is -1, the size of the corresponding dimension of
+        `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes over which the IDCT is computed. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized IDCT variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dctn : multidimensional DCT
+
+    Notes
+    -----
+    For full details of the IDCT types and normalization modes, as well as
+    references, see `idct`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fft import dctn, idctn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idctn(dctn(y)))
+    True
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def dstn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
+         workers=None, orthogonalize=None):
+    """
+    Return multidimensional Discrete Sine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    s : int or array_like of ints or None, optional
+        The shape of the result.  If both `s` and `axes` (see below) are None,
+        `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is
+        ``numpy.take(x.shape, axes, axis=0)``.
+        If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
+        If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
+        ``s[i]``.
+        If any element of `shape` is -1, the size of the corresponding dimension
+        of `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes over which the DST is computed. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized DST variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    idstn : Inverse multidimensional DST
+
+    Notes
+    -----
+    For full details of the DST types and normalization modes, as well as
+    references, see `dst`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fft import dstn, idstn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idstn(dstn(y)))
+    True
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def idstn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
+          workers=None, orthogonalize=None):
+    """
+    Return multidimensional Inverse Discrete Sine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    s : int or array_like of ints or None, optional
+        The shape of the result.  If both `s` and `axes` (see below) are None,
+        `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is
+        ``numpy.take(x.shape, axes, axis=0)``.
+        If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
+        If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
+        ``s[i]``.
+        If any element of `s` is -1, the size of the corresponding dimension of
+        `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes over which the IDST is computed. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized IDST variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dstn : multidimensional DST
+
+    Notes
+    -----
+    For full details of the IDST types and normalization modes, as well as
+    references, see `idst`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fft import dstn, idstn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idstn(dstn(y)))
+    True
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def dct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False, workers=None,
+        orthogonalize=None):
+    r"""Return the Discrete Cosine Transform of arbitrary type sequence x.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform.  If ``n < x.shape[axis]``, `x` is
+        truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the dct is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized DCT variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    idct : Inverse DCT
+
+    Notes
+    -----
+    For a single dimension array ``x``, ``dct(x, norm='ortho')`` is equal to
+    MATLAB ``dct(x)``.
+
+    .. warning:: For ``type in {1, 2, 3}``, ``norm="ortho"`` breaks the direct
+                 correspondence with the direct Fourier transform. To recover
+                 it you must specify ``orthogonalize=False``.
+
+    For ``norm="ortho"`` both the `dct` and `idct` are scaled by the same
+    overall factor in both directions. By default, the transform is also
+    orthogonalized which for types 1, 2 and 3 means the transform definition is
+    modified to give orthogonality of the DCT matrix (see below).
+
+    For ``norm="backward"``, there is no scaling on `dct` and the `idct` is
+    scaled by ``1/N`` where ``N`` is the "logical" size of the DCT. For
+    ``norm="forward"`` the ``1/N`` normalization is applied to the forward
+    `dct` instead and the `idct` is unnormalized.
+
+    There are, theoretically, 8 types of the DCT, only the first 4 types are
+    implemented in SciPy.'The' DCT generally refers to DCT type 2, and 'the'
+    Inverse DCT generally refers to DCT type 3.
+
+    **Type I**
+
+    There are several definitions of the DCT-I; we use the following
+    (for ``norm="backward"``)
+
+    .. math::
+
+       y_k = x_0 + (-1)^k x_{N-1} + 2 \sum_{n=1}^{N-2} x_n \cos\left(
+       \frac{\pi k n}{N-1} \right)
+
+    If ``orthogonalize=True``, ``x[0]`` and ``x[N-1]`` are multiplied by a
+    scaling factor of :math:`\sqrt{2}`, and ``y[0]`` and ``y[N-1]`` are divided
+    by :math:`\sqrt{2}`. When combined with ``norm="ortho"``, this makes the
+    corresponding matrix of coefficients orthonormal (``O @ O.T = np.eye(N)``).
+
+    .. note::
+       The DCT-I is only supported for input size > 1.
+
+    **Type II**
+
+    There are several definitions of the DCT-II; we use the following
+    (for ``norm="backward"``)
+
+    .. math::
+
+       y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi k(2n+1)}{2N} \right)
+
+    If ``orthogonalize=True``, ``y[0]`` is divided by :math:`\sqrt{2}` which,
+    when combined with ``norm="ortho"``, makes the corresponding matrix of
+    coefficients orthonormal (``O @ O.T = np.eye(N)``).
+
+    **Type III**
+
+    There are several definitions, we use the following (for
+    ``norm="backward"``)
+
+    .. math::
+
+       y_k = x_0 + 2 \sum_{n=1}^{N-1} x_n \cos\left(\frac{\pi(2k+1)n}{2N}\right)
+
+    If ``orthogonalize=True``, ``x[0]`` terms are multiplied by
+    :math:`\sqrt{2}` which, when combined with ``norm="ortho"``, makes the
+    corresponding matrix of coefficients orthonormal (``O @ O.T = np.eye(N)``).
+
+    The (unnormalized) DCT-III is the inverse of the (unnormalized) DCT-II, up
+    to a factor `2N`. The orthonormalized DCT-III is exactly the inverse of
+    the orthonormalized DCT-II.
+
+    **Type IV**
+
+    There are several definitions of the DCT-IV; we use the following
+    (for ``norm="backward"``)
+
+    .. math::
+
+       y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi(2k+1)(2n+1)}{4N} \right)
+
+    ``orthogonalize`` has no effect here, as the DCT-IV matrix is already
+    orthogonal up to a scale factor of ``2N``.
+
+    References
+    ----------
+    .. [1] 'A Fast Cosine Transform in One and Two Dimensions', by J.
+           Makhoul, `IEEE Transactions on acoustics, speech and signal
+           processing` vol. 28(1), pp. 27-34,
+           :doi:`10.1109/TASSP.1980.1163351` (1980).
+    .. [2] Wikipedia, "Discrete cosine transform",
+           https://en.wikipedia.org/wiki/Discrete_cosine_transform
+
+    Examples
+    --------
+    The Type 1 DCT is equivalent to the FFT (though faster) for real,
+    even-symmetrical inputs. The output is also real and even-symmetrical.
+    Half of the FFT input is used to generate half of the FFT output:
+
+    >>> from scipy.fft import fft, dct
+    >>> import numpy as np
+    >>> fft(np.array([4., 3., 5., 10., 5., 3.])).real
+    array([ 30.,  -8.,   6.,  -2.,   6.,  -8.])
+    >>> dct(np.array([4., 3., 5., 10.]), 1)
+    array([ 30.,  -8.,   6.,  -2.])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def idct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False,
+         workers=None, orthogonalize=None):
+    """
+    Return the Inverse Discrete Cosine Transform of an arbitrary type sequence.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform.  If ``n < x.shape[axis]``, `x` is
+        truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the idct is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized IDCT variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    idct : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dct : Forward DCT
+
+    Notes
+    -----
+    For a single dimension array `x`, ``idct(x, norm='ortho')`` is equal to
+    MATLAB ``idct(x)``.
+
+    .. warning:: For ``type in {1, 2, 3}``, ``norm="ortho"`` breaks the direct
+                 correspondence with the inverse direct Fourier transform. To
+                 recover it you must specify ``orthogonalize=False``.
+
+    For ``norm="ortho"`` both the `dct` and `idct` are scaled by the same
+    overall factor in both directions. By default, the transform is also
+    orthogonalized which for types 1, 2 and 3 means the transform definition is
+    modified to give orthogonality of the IDCT matrix (see `dct` for the full
+    definitions).
+
+    'The' IDCT is the IDCT-II, which is the same as the normalized DCT-III.
+
+    The IDCT is equivalent to a normal DCT except for the normalization and
+    type. DCT type 1 and 4 are their own inverse and DCTs 2 and 3 are each
+    other's inverses.
+
+    Examples
+    --------
+    The Type 1 DCT is equivalent to the DFT for real, even-symmetrical
+    inputs. The output is also real and even-symmetrical. Half of the IFFT
+    input is used to generate half of the IFFT output:
+
+    >>> from scipy.fft import ifft, idct
+    >>> import numpy as np
+    >>> ifft(np.array([ 30.,  -8.,   6.,  -2.,   6.,  -8.])).real
+    array([  4.,   3.,   5.,  10.,   5.,   3.])
+    >>> idct(np.array([ 30.,  -8.,   6.,  -2.]), 1)
+    array([  4.,   3.,   5.,  10.])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def dst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False, workers=None,
+        orthogonalize=None):
+    r"""
+    Return the Discrete Sine Transform of arbitrary type sequence x.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform. If ``n < x.shape[axis]``, `x` is
+        truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the dst is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized DST variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    dst : ndarray of reals
+        The transformed input array.
+
+    See Also
+    --------
+    idst : Inverse DST
+
+    Notes
+    -----
+    .. warning:: For ``type in {2, 3}``, ``norm="ortho"`` breaks the direct
+                 correspondence with the direct Fourier transform. To recover
+                 it you must specify ``orthogonalize=False``.
+
+    For ``norm="ortho"`` both the `dst` and `idst` are scaled by the same
+    overall factor in both directions. By default, the transform is also
+    orthogonalized which for types 2 and 3 means the transform definition is
+    modified to give orthogonality of the DST matrix (see below).
+
+    For ``norm="backward"``, there is no scaling on the `dst` and the `idst` is
+    scaled by ``1/N`` where ``N`` is the "logical" size of the DST.
+
+    There are, theoretically, 8 types of the DST for different combinations of
+    even/odd boundary conditions and boundary off sets [1]_, only the first
+    4 types are implemented in SciPy.
+
+    **Type I**
+
+    There are several definitions of the DST-I; we use the following for
+    ``norm="backward"``. DST-I assumes the input is odd around :math:`n=-1` and
+    :math:`n=N`.
+
+    .. math::
+
+        y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(n+1)}{N+1}\right)
+
+    Note that the DST-I is only supported for input size > 1.
+    The (unnormalized) DST-I is its own inverse, up to a factor :math:`2(N+1)`.
+    The orthonormalized DST-I is exactly its own inverse.
+
+    ``orthogonalize`` has no effect here, as the DST-I matrix is already
+    orthogonal up to a scale factor of ``2N``.
+
+    **Type II**
+
+    There are several definitions of the DST-II; we use the following for
+    ``norm="backward"``. DST-II assumes the input is odd around :math:`n=-1/2` and
+    :math:`n=N-1/2`; the output is odd around :math:`k=-1` and even around :math:`k=N-1`
+
+    .. math::
+
+        y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(2n+1)}{2N}\right)
+
+    If ``orthogonalize=True``, ``y[-1]`` is divided :math:`\sqrt{2}` which, when
+    combined with ``norm="ortho"``, makes the corresponding matrix of
+    coefficients orthonormal (``O @ O.T = np.eye(N)``).
+
+    **Type III**
+
+    There are several definitions of the DST-III, we use the following (for
+    ``norm="backward"``). DST-III assumes the input is odd around :math:`n=-1` and
+    even around :math:`n=N-1`
+
+    .. math::
+
+        y_k = (-1)^k x_{N-1} + 2 \sum_{n=0}^{N-2} x_n \sin\left(
+        \frac{\pi(2k+1)(n+1)}{2N}\right)
+
+    If ``orthogonalize=True``, ``x[-1]`` is multiplied by :math:`\sqrt{2}`
+    which, when combined with ``norm="ortho"``, makes the corresponding matrix
+    of coefficients orthonormal (``O @ O.T = np.eye(N)``).
+
+    The (unnormalized) DST-III is the inverse of the (unnormalized) DST-II, up
+    to a factor :math:`2N`. The orthonormalized DST-III is exactly the inverse of the
+    orthonormalized DST-II.
+
+    **Type IV**
+
+    There are several definitions of the DST-IV, we use the following (for
+    ``norm="backward"``). DST-IV assumes the input is odd around :math:`n=-0.5` and
+    even around :math:`n=N-0.5`
+
+    .. math::
+
+        y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(2k+1)(2n+1)}{4N}\right)
+
+    ``orthogonalize`` has no effect here, as the DST-IV matrix is already
+    orthogonal up to a scale factor of ``2N``.
+
+    The (unnormalized) DST-IV is its own inverse, up to a factor :math:`2N`. The
+    orthonormalized DST-IV is exactly its own inverse.
+
+    Examples
+    --------
+    Compute the DST of a simple 1D array:
+
+    >>> import numpy as np
+    >>> from scipy.fft import dst
+    >>> x = np.array([1, -1, 1, -1])
+    >>> dst(x, type=2)
+    array([0., 0., 0., 8.])
+
+    This computes the Discrete Sine Transform (DST) of type-II for the input array. 
+    The output contains the transformed values corresponding to the given input sequence
+
+    References
+    ----------
+    .. [1] Wikipedia, "Discrete sine transform",
+           https://en.wikipedia.org/wiki/Discrete_sine_transform
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def idst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False,
+         workers=None, orthogonalize=None):
+    """
+    Return the Inverse Discrete Sine Transform of an arbitrary type sequence.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform. If ``n < x.shape[axis]``, `x` is
+        truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the idst is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized IDST variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    idst : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dst : Forward DST
+
+    Notes
+    -----
+    .. warning:: For ``type in {2, 3}``, ``norm="ortho"`` breaks the direct
+                 correspondence with the inverse direct Fourier transform.
+
+    For ``norm="ortho"`` both the `dst` and `idst` are scaled by the same
+    overall factor in both directions. By default, the transform is also
+    orthogonalized which for types 2 and 3 means the transform definition is
+    modified to give orthogonality of the DST matrix (see `dst` for the full
+    definitions).
+
+    'The' IDST is the IDST-II, which is the same as the normalized DST-III.
+
+    The IDST is equivalent to a normal DST except for the normalization and
+    type. DST type 1 and 4 are their own inverse and DSTs 2 and 3 are each
+    other's inverses.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_realtransforms_backend.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_realtransforms_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..2042453733bec54860974cc1e20ba908e8c9b94d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/fft/_realtransforms_backend.py
@@ -0,0 +1,63 @@
+from scipy._lib._array_api import array_namespace
+import numpy as np
+from . import _pocketfft
+
+__all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn']
+
+
+def _execute(pocketfft_func, x, type, s, axes, norm, 
+             overwrite_x, workers, orthogonalize):
+    xp = array_namespace(x)
+    x = np.asarray(x)
+    y = pocketfft_func(x, type, s, axes, norm,
+                       overwrite_x=overwrite_x, workers=workers,
+                       orthogonalize=orthogonalize)
+    return xp.asarray(y)
+
+
+def dctn(x, type=2, s=None, axes=None, norm=None,
+         overwrite_x=False, workers=None, *, orthogonalize=None):
+    return _execute(_pocketfft.dctn, x, type, s, axes, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def idctn(x, type=2, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, *, orthogonalize=None):
+    return _execute(_pocketfft.idctn, x, type, s, axes, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def dstn(x, type=2, s=None, axes=None, norm=None,
+         overwrite_x=False, workers=None, orthogonalize=None):
+    return _execute(_pocketfft.dstn, x, type, s, axes, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def idstn(x, type=2, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, *, orthogonalize=None):
+    return _execute(_pocketfft.idstn, x, type, s, axes, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def dct(x, type=2, n=None, axis=-1, norm=None,
+        overwrite_x=False, workers=None, orthogonalize=None):
+    return _execute(_pocketfft.dct, x, type, n, axis, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def idct(x, type=2, n=None, axis=-1, norm=None,
+         overwrite_x=False, workers=None, orthogonalize=None):
+    return _execute(_pocketfft.idct, x, type, n, axis, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def dst(x, type=2, n=None, axis=-1, norm=None,
+        overwrite_x=False, workers=None, orthogonalize=None):
+    return _execute(_pocketfft.dst, x, type, n, axis, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def idst(x, type=2, n=None, axis=-1, norm=None,
+         overwrite_x=False, workers=None, orthogonalize=None):
+    return _execute(_pocketfft.idst, x, type, n, axis, norm, 
+                    overwrite_x, workers, orthogonalize)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..10f4b39e48e2d6c0b042582ca65f572bde6ba575
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/__init__.py
@@ -0,0 +1,103 @@
+"""
+=========================================================
+Legacy discrete Fourier transforms (:mod:`scipy.fftpack`)
+=========================================================
+
+.. legacy::
+
+   New code should use :mod:`scipy.fft`.
+
+Fast Fourier Transforms (FFTs)
+==============================
+
+.. autosummary::
+   :toctree: generated/
+
+   fft - Fast (discrete) Fourier Transform (FFT)
+   ifft - Inverse FFT
+   fft2 - 2-D FFT
+   ifft2 - 2-D inverse FFT
+   fftn - N-D FFT
+   ifftn - N-D inverse FFT
+   rfft - FFT of strictly real-valued sequence
+   irfft - Inverse of rfft
+   dct - Discrete cosine transform
+   idct - Inverse discrete cosine transform
+   dctn - N-D Discrete cosine transform
+   idctn - N-D Inverse discrete cosine transform
+   dst - Discrete sine transform
+   idst - Inverse discrete sine transform
+   dstn - N-D Discrete sine transform
+   idstn - N-D Inverse discrete sine transform
+
+Differential and pseudo-differential operators
+==============================================
+
+.. autosummary::
+   :toctree: generated/
+
+   diff - Differentiation and integration of periodic sequences
+   tilbert - Tilbert transform:         cs_diff(x,h,h)
+   itilbert - Inverse Tilbert transform: sc_diff(x,h,h)
+   hilbert - Hilbert transform:         cs_diff(x,inf,inf)
+   ihilbert - Inverse Hilbert transform: sc_diff(x,inf,inf)
+   cs_diff - cosh/sinh pseudo-derivative of periodic sequences
+   sc_diff - sinh/cosh pseudo-derivative of periodic sequences
+   ss_diff - sinh/sinh pseudo-derivative of periodic sequences
+   cc_diff - cosh/cosh pseudo-derivative of periodic sequences
+   shift - Shift periodic sequences
+
+Helper functions
+================
+
+.. autosummary::
+   :toctree: generated/
+
+   fftshift - Shift the zero-frequency component to the center of the spectrum
+   ifftshift - The inverse of `fftshift`
+   fftfreq - Return the Discrete Fourier Transform sample frequencies
+   rfftfreq - DFT sample frequencies (for usage with rfft, irfft)
+   next_fast_len - Find the optimal length to zero-pad an FFT for speed
+
+Note that ``fftshift``, ``ifftshift`` and ``fftfreq`` are numpy functions
+exposed by ``fftpack``; importing them from ``numpy`` should be preferred.
+
+Convolutions (:mod:`scipy.fftpack.convolve`)
+============================================
+
+.. module:: scipy.fftpack.convolve
+
+.. autosummary::
+   :toctree: generated/
+
+   convolve
+   convolve_z
+   init_convolution_kernel
+   destroy_convolve_cache
+
+"""
+
+
+__all__ = ['fft','ifft','fftn','ifftn','rfft','irfft',
+           'fft2','ifft2',
+           'diff',
+           'tilbert','itilbert','hilbert','ihilbert',
+           'sc_diff','cs_diff','cc_diff','ss_diff',
+           'shift',
+           'fftfreq', 'rfftfreq',
+           'fftshift', 'ifftshift',
+           'next_fast_len',
+           'dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn'
+           ]
+
+from ._basic import *
+from ._pseudo_diffs import *
+from ._helper import *
+from ._realtransforms import *
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import basic, helper, pseudo_diffs, realtransforms
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/_basic.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..59c85ae4b364464a66489ef221f7f7ac45624694
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/_basic.py
@@ -0,0 +1,428 @@
+"""
+Discrete Fourier Transforms - _basic.py
+"""
+# Created by Pearu Peterson, August,September 2002
+__all__ = ['fft','ifft','fftn','ifftn','rfft','irfft',
+           'fft2','ifft2']
+
+from scipy.fft import _pocketfft
+from ._helper import _good_shape
+
+
+def fft(x, n=None, axis=-1, overwrite_x=False):
+    """
+    Return discrete Fourier transform of real or complex sequence.
+
+    The returned complex array contains ``y(0), y(1),..., y(n-1)``, where
+
+    ``y(j) = (x * exp(-2*pi*sqrt(-1)*j*np.arange(n)/n)).sum()``.
+
+    Parameters
+    ----------
+    x : array_like
+        Array to Fourier transform.
+    n : int, optional
+        Length of the Fourier transform. If ``n < x.shape[axis]``, `x` is
+        truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the fft's are computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    z : complex ndarray
+        with the elements::
+
+            [y(0),y(1),..,y(n/2),y(1-n/2),...,y(-1)]        if n is even
+            [y(0),y(1),..,y((n-1)/2),y(-(n-1)/2),...,y(-1)]  if n is odd
+
+        where::
+
+            y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k* 2*pi/n), j = 0..n-1
+
+    See Also
+    --------
+    ifft : Inverse FFT
+    rfft : FFT of a real sequence
+
+    Notes
+    -----
+    The packing of the result is "standard": If ``A = fft(a, n)``, then
+    ``A[0]`` contains the zero-frequency term, ``A[1:n/2]`` contains the
+    positive-frequency terms, and ``A[n/2:]`` contains the negative-frequency
+    terms, in order of decreasingly negative frequency. So ,for an 8-point
+    transform, the frequencies of the result are [0, 1, 2, 3, -4, -3, -2, -1].
+    To rearrange the fft output so that the zero-frequency component is
+    centered, like [-4, -3, -2, -1,  0,  1,  2,  3], use `fftshift`.
+
+    Both single and double precision routines are implemented. Half precision
+    inputs will be converted to single precision. Non-floating-point inputs
+    will be converted to double precision. Long-double precision inputs are
+    not supported.
+
+    This function is most efficient when `n` is a power of two, and least
+    efficient when `n` is prime.
+
+    Note that if ``x`` is real-valued, then ``A[j] == A[n-j].conjugate()``.
+    If ``x`` is real-valued and ``n`` is even, then ``A[n/2]`` is real.
+
+    If the data type of `x` is real, a "real FFT" algorithm is automatically
+    used, which roughly halves the computation time. To increase efficiency
+    a little further, use `rfft`, which does the same calculation, but only
+    outputs half of the symmetrical spectrum. If the data is both real and
+    symmetrical, the `dct` can again double the efficiency by generating
+    half of the spectrum from half of the signal.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import fft, ifft
+    >>> x = np.arange(5)
+    >>> np.allclose(fft(ifft(x)), x, atol=1e-15)  # within numerical accuracy.
+    True
+
+    """
+    return _pocketfft.fft(x, n, axis, None, overwrite_x)
+
+
+def ifft(x, n=None, axis=-1, overwrite_x=False):
+    """
+    Return discrete inverse Fourier transform of real or complex sequence.
+
+    The returned complex array contains ``y(0), y(1),..., y(n-1)``, where
+
+    ``y(j) = (x * exp(2*pi*sqrt(-1)*j*np.arange(n)/n)).mean()``.
+
+    Parameters
+    ----------
+    x : array_like
+        Transformed data to invert.
+    n : int, optional
+        Length of the inverse Fourier transform.  If ``n < x.shape[axis]``,
+        `x` is truncated. If ``n > x.shape[axis]``, `x` is zero-padded.
+        The default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the ifft's are computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    ifft : ndarray of floats
+        The inverse discrete Fourier transform.
+
+    See Also
+    --------
+    fft : Forward FFT
+
+    Notes
+    -----
+    Both single and double precision routines are implemented. Half precision
+    inputs will be converted to single precision. Non-floating-point inputs
+    will be converted to double precision. Long-double precision inputs are
+    not supported.
+
+    This function is most efficient when `n` is a power of two, and least
+    efficient when `n` is prime.
+
+    If the data type of `x` is real, a "real IFFT" algorithm is automatically
+    used, which roughly halves the computation time.
+
+    Examples
+    --------
+    >>> from scipy.fftpack import fft, ifft
+    >>> import numpy as np
+    >>> x = np.arange(5)
+    >>> np.allclose(ifft(fft(x)), x, atol=1e-15)  # within numerical accuracy.
+    True
+
+    """
+    return _pocketfft.ifft(x, n, axis, None, overwrite_x)
+
+
+def rfft(x, n=None, axis=-1, overwrite_x=False):
+    """
+    Discrete Fourier transform of a real sequence.
+
+    Parameters
+    ----------
+    x : array_like, real-valued
+        The data to transform.
+    n : int, optional
+        Defines the length of the Fourier transform. If `n` is not specified
+        (the default) then ``n = x.shape[axis]``. If ``n < x.shape[axis]``,
+        `x` is truncated, if ``n > x.shape[axis]``, `x` is zero-padded.
+    axis : int, optional
+        The axis along which the transform is applied. The default is the
+        last axis.
+    overwrite_x : bool, optional
+        If set to true, the contents of `x` can be overwritten. Default is
+        False.
+
+    Returns
+    -------
+    z : real ndarray
+        The returned real array contains::
+
+          [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2))]              if n is even
+          [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2)),Im(y(n/2))]   if n is odd
+
+        where::
+
+          y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k*2*pi/n)
+          j = 0..n-1
+
+    See Also
+    --------
+    fft, irfft, scipy.fft.rfft
+
+    Notes
+    -----
+    Within numerical accuracy, ``y == rfft(irfft(y))``.
+
+    Both single and double precision routines are implemented. Half precision
+    inputs will be converted to single precision. Non-floating-point inputs
+    will be converted to double precision. Long-double precision inputs are
+    not supported.
+
+    To get an output with a complex datatype, consider using the newer
+    function `scipy.fft.rfft`.
+
+    Examples
+    --------
+    >>> from scipy.fftpack import fft, rfft
+    >>> a = [9, -9, 1, 3]
+    >>> fft(a)
+    array([  4. +0.j,   8.+12.j,  16. +0.j,   8.-12.j])
+    >>> rfft(a)
+    array([  4.,   8.,  12.,  16.])
+
+    """
+    return _pocketfft.rfft_fftpack(x, n, axis, None, overwrite_x)
+
+
+def irfft(x, n=None, axis=-1, overwrite_x=False):
+    """
+    Return inverse discrete Fourier transform of real sequence x.
+
+    The contents of `x` are interpreted as the output of the `rfft`
+    function.
+
+    Parameters
+    ----------
+    x : array_like
+        Transformed data to invert.
+    n : int, optional
+        Length of the inverse Fourier transform.
+        If n < x.shape[axis], x is truncated.
+        If n > x.shape[axis], x is zero-padded.
+        The default results in n = x.shape[axis].
+    axis : int, optional
+        Axis along which the ifft's are computed; the default is over
+        the last axis (i.e., axis=-1).
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    irfft : ndarray of floats
+        The inverse discrete Fourier transform.
+
+    See Also
+    --------
+    rfft, ifft, scipy.fft.irfft
+
+    Notes
+    -----
+    The returned real array contains::
+
+        [y(0),y(1),...,y(n-1)]
+
+    where for n is even::
+
+        y(j) = 1/n (sum[k=1..n/2-1] (x[2*k-1]+sqrt(-1)*x[2*k])
+                                     * exp(sqrt(-1)*j*k* 2*pi/n)
+                    + c.c. + x[0] + (-1)**(j) x[n-1])
+
+    and for n is odd::
+
+        y(j) = 1/n (sum[k=1..(n-1)/2] (x[2*k-1]+sqrt(-1)*x[2*k])
+                                     * exp(sqrt(-1)*j*k* 2*pi/n)
+                    + c.c. + x[0])
+
+    c.c. denotes complex conjugate of preceding expression.
+
+    For details on input parameters, see `rfft`.
+
+    To process (conjugate-symmetric) frequency-domain data with a complex
+    datatype, consider using the newer function `scipy.fft.irfft`.
+
+    Examples
+    --------
+    >>> from scipy.fftpack import rfft, irfft
+    >>> a = [1.0, 2.0, 3.0, 4.0, 5.0]
+    >>> irfft(a)
+    array([ 2.6       , -3.16405192,  1.24398433, -1.14955713,  1.46962473])
+    >>> irfft(rfft(a))
+    array([1., 2., 3., 4., 5.])
+
+    """
+    return _pocketfft.irfft_fftpack(x, n, axis, None, overwrite_x)
+
+
+def fftn(x, shape=None, axes=None, overwrite_x=False):
+    """
+    Return multidimensional discrete Fourier transform.
+
+    The returned array contains::
+
+      y[j_1,..,j_d] = sum[k_1=0..n_1-1, ..., k_d=0..n_d-1]
+         x[k_1,..,k_d] * prod[i=1..d] exp(-sqrt(-1)*2*pi/n_i * j_i * k_i)
+
+    where d = len(x.shape) and n = x.shape.
+
+    Parameters
+    ----------
+    x : array_like
+        The (N-D) array to transform.
+    shape : int or array_like of ints or None, optional
+        The shape of the result. If both `shape` and `axes` (see below) are
+        None, `shape` is ``x.shape``; if `shape` is None but `axes` is
+        not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
+        If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
+        If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
+        length ``shape[i]``.
+        If any element of `shape` is -1, the size of the corresponding
+        dimension of `x` is used.
+    axes : int or array_like of ints or None, optional
+        The axes of `x` (`y` if `shape` is not None) along which the
+        transform is applied.
+        The default is over all axes.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed. Default is False.
+
+    Returns
+    -------
+    y : complex-valued N-D NumPy array
+        The (N-D) DFT of the input array.
+
+    See Also
+    --------
+    ifftn
+
+    Notes
+    -----
+    If ``x`` is real-valued, then
+    ``y[..., j_i, ...] == y[..., n_i-j_i, ...].conjugate()``.
+
+    Both single and double precision routines are implemented. Half precision
+    inputs will be converted to single precision. Non-floating-point inputs
+    will be converted to double precision. Long-double precision inputs are
+    not supported.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import fftn, ifftn
+    >>> y = (-np.arange(16), 8 - np.arange(16), np.arange(16))
+    >>> np.allclose(y, fftn(ifftn(y)))
+    True
+
+    """
+    shape = _good_shape(x, shape, axes)
+    return _pocketfft.fftn(x, shape, axes, None, overwrite_x)
+
+
+def ifftn(x, shape=None, axes=None, overwrite_x=False):
+    """
+    Return inverse multidimensional discrete Fourier transform.
+
+    The sequence can be of an arbitrary type.
+
+    The returned array contains::
+
+      y[j_1,..,j_d] = 1/p * sum[k_1=0..n_1-1, ..., k_d=0..n_d-1]
+         x[k_1,..,k_d] * prod[i=1..d] exp(sqrt(-1)*2*pi/n_i * j_i * k_i)
+
+    where ``d = len(x.shape)``, ``n = x.shape``, and ``p = prod[i=1..d] n_i``.
+
+    For description of parameters see `fftn`.
+
+    See Also
+    --------
+    fftn : for detailed information.
+
+    Examples
+    --------
+    >>> from scipy.fftpack import fftn, ifftn
+    >>> import numpy as np
+    >>> y = (-np.arange(16), 8 - np.arange(16), np.arange(16))
+    >>> np.allclose(y, ifftn(fftn(y)))
+    True
+
+    """
+    shape = _good_shape(x, shape, axes)
+    return _pocketfft.ifftn(x, shape, axes, None, overwrite_x)
+
+
+def fft2(x, shape=None, axes=(-2,-1), overwrite_x=False):
+    """
+    2-D discrete Fourier transform.
+
+    Return the 2-D discrete Fourier transform of the 2-D argument
+    `x`.
+
+    See Also
+    --------
+    fftn : for detailed information.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import fft2, ifft2
+    >>> y = np.mgrid[:5, :5][0]
+    >>> y
+    array([[0, 0, 0, 0, 0],
+           [1, 1, 1, 1, 1],
+           [2, 2, 2, 2, 2],
+           [3, 3, 3, 3, 3],
+           [4, 4, 4, 4, 4]])
+    >>> np.allclose(y, ifft2(fft2(y)))
+    True
+    """
+    return fftn(x,shape,axes,overwrite_x)
+
+
+def ifft2(x, shape=None, axes=(-2,-1), overwrite_x=False):
+    """
+    2-D discrete inverse Fourier transform of real or complex sequence.
+
+    Return inverse 2-D discrete Fourier transform of
+    arbitrary type sequence x.
+
+    See `ifft` for more information.
+
+    See Also
+    --------
+    fft2, ifft
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import fft2, ifft2
+    >>> y = np.mgrid[:5, :5][0]
+    >>> y
+    array([[0, 0, 0, 0, 0],
+           [1, 1, 1, 1, 1],
+           [2, 2, 2, 2, 2],
+           [3, 3, 3, 3, 3],
+           [4, 4, 4, 4, 4]])
+    >>> np.allclose(y, fft2(ifft2(y)))
+    True
+
+    """
+    return ifftn(x,shape,axes,overwrite_x)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/_helper.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..7892543732906dcd86b4c1aa9c1f249af701c137
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/_helper.py
@@ -0,0 +1,115 @@
+import operator
+
+import numpy as np
+from numpy.fft import fftshift, ifftshift, fftfreq
+
+import scipy.fft._pocketfft.helper as _helper
+
+__all__ = ['fftshift', 'ifftshift', 'fftfreq', 'rfftfreq', 'next_fast_len']
+
+
+def rfftfreq(n, d=1.0):
+    """DFT sample frequencies (for usage with rfft, irfft).
+
+    The returned float array contains the frequency bins in
+    cycles/unit (with zero at the start) given a window length `n` and a
+    sample spacing `d`::
+
+      f = [0,1,1,2,2,...,n/2-1,n/2-1,n/2]/(d*n)   if n is even
+      f = [0,1,1,2,2,...,n/2-1,n/2-1,n/2,n/2]/(d*n)   if n is odd
+
+    Parameters
+    ----------
+    n : int
+        Window length.
+    d : scalar, optional
+        Sample spacing. Default is 1.
+
+    Returns
+    -------
+    out : ndarray
+        The array of length `n`, containing the sample frequencies.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import fftpack
+    >>> sig = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float)
+    >>> sig_fft = fftpack.rfft(sig)
+    >>> n = sig_fft.size
+    >>> timestep = 0.1
+    >>> freq = fftpack.rfftfreq(n, d=timestep)
+    >>> freq
+    array([ 0.  ,  1.25,  1.25,  2.5 ,  2.5 ,  3.75,  3.75,  5.  ])
+
+    """
+    n = operator.index(n)
+    if n < 0:
+        raise ValueError(f"n = {n} is not valid. "
+                         "n must be a nonnegative integer.")
+
+    return (np.arange(1, n + 1, dtype=int) // 2) / float(n * d)
+
+
+def next_fast_len(target):
+    """
+    Find the next fast size of input data to `fft`, for zero-padding, etc.
+
+    SciPy's FFTPACK has efficient functions for radix {2, 3, 4, 5}, so this
+    returns the next composite of the prime factors 2, 3, and 5 which is
+    greater than or equal to `target`. (These are also known as 5-smooth
+    numbers, regular numbers, or Hamming numbers.)
+
+    Parameters
+    ----------
+    target : int
+        Length to start searching from. Must be a positive integer.
+
+    Returns
+    -------
+    out : int
+        The first 5-smooth number greater than or equal to `target`.
+
+    Notes
+    -----
+    .. versionadded:: 0.18.0
+
+    Examples
+    --------
+    On a particular machine, an FFT of prime length takes 133 ms:
+
+    >>> from scipy import fftpack
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> min_len = 10007  # prime length is worst case for speed
+    >>> a = rng.standard_normal(min_len)
+    >>> b = fftpack.fft(a)
+
+    Zero-padding to the next 5-smooth length reduces computation time to
+    211 us, a speedup of 630 times:
+
+    >>> fftpack.next_fast_len(min_len)
+    10125
+    >>> b = fftpack.fft(a, 10125)
+
+    Rounding up to the next power of 2 is not optimal, taking 367 us to
+    compute, 1.7 times as long as the 5-smooth size:
+
+    >>> b = fftpack.fft(a, 16384)
+
+    """
+    # Real transforms use regular sizes so this is backwards compatible
+    return _helper.good_size(target, True)
+
+
+def _good_shape(x, shape, axes):
+    """Ensure that shape argument is valid for scipy.fftpack
+
+    scipy.fftpack does not support len(shape) < x.ndim when axes is not given.
+    """
+    if shape is not None and axes is None:
+        shape = _helper._iterable_of_int(shape, 'shape')
+        if len(shape) != np.ndim(x):
+            raise ValueError("when given, axes and shape arguments"
+                             " have to be of the same length")
+    return shape
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/_pseudo_diffs.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/_pseudo_diffs.py
new file mode 100644
index 0000000000000000000000000000000000000000..6dbcc8d3979b35c1497266fea34cf565cd3d11d7
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/_pseudo_diffs.py
@@ -0,0 +1,554 @@
+"""
+Differential and pseudo-differential operators.
+"""
+# Created by Pearu Peterson, September 2002
+
+__all__ = ['diff',
+           'tilbert','itilbert','hilbert','ihilbert',
+           'cs_diff','cc_diff','sc_diff','ss_diff',
+           'shift']
+
+import threading
+
+from numpy import pi, asarray, sin, cos, sinh, cosh, tanh, iscomplexobj
+from . import convolve
+
+from scipy.fft._pocketfft.helper import _datacopied
+
+
+_cache = threading.local()
+
+
+def diff(x,order=1,period=None, _cache=_cache):
+    """
+    Return kth derivative (or integral) of a periodic sequence x.
+
+    If x_j and y_j are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = pow(sqrt(-1)*j*2*pi/period, order) * x_j
+      y_0 = 0 if order is not 0.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    order : int, optional
+        The order of differentiation. Default order is 1. If order is
+        negative, then integration is carried out under the assumption
+        that ``x_0 == 0``.
+    period : float, optional
+        The assumed period of the sequence. Default is ``2*pi``.
+
+    Notes
+    -----
+    If ``sum(x, axis=0) = 0`` then ``diff(diff(x, k), -k) == x`` (within
+    numerical accuracy).
+
+    For odd order and even ``len(x)``, the Nyquist mode is taken zero.
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'diff_cache'):
+            _cache.diff_cache = {}
+        _cache = _cache.diff_cache
+
+    tmp = asarray(x)
+    if order == 0:
+        return tmp
+    if iscomplexobj(tmp):
+        return diff(tmp.real, order, period, _cache)+1j*diff(
+            tmp.imag, order, period, _cache)
+    if period is not None:
+        c = 2*pi/period
+    else:
+        c = 1.0
+    n = len(x)
+    omega = _cache.get((n,order,c))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k,order=order,c=c):
+            if k:
+                return pow(c*k,order)
+            return 0
+        omega = convolve.init_convolution_kernel(n,kernel,d=order,
+                                                 zero_nyquist=1)
+        _cache[(n,order,c)] = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,swap_real_imag=order % 2,
+                             overwrite_x=overwrite_x)
+
+
+def tilbert(x, h, period=None, _cache=_cache):
+    """
+    Return h-Tilbert transform of a periodic sequence x.
+
+    If x_j and y_j are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+        y_j = sqrt(-1)*coth(j*h*2*pi/period) * x_j
+        y_0 = 0
+
+    Parameters
+    ----------
+    x : array_like
+        The input array to transform.
+    h : float
+        Defines the parameter of the Tilbert transform.
+    period : float, optional
+        The assumed period of the sequence. Default period is ``2*pi``.
+
+    Returns
+    -------
+    tilbert : ndarray
+        The result of the transform.
+
+    Notes
+    -----
+    If ``sum(x, axis=0) == 0`` and ``n = len(x)`` is odd, then
+    ``tilbert(itilbert(x)) == x``.
+
+    If ``2 * pi * h / period`` is approximately 10 or larger, then
+    numerically ``tilbert == hilbert``
+    (theoretically oo-Tilbert == Hilbert).
+
+    For even ``len(x)``, the Nyquist mode of ``x`` is taken zero.
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'tilbert_cache'):
+            _cache.tilbert_cache = {}
+        _cache = _cache.tilbert_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return tilbert(tmp.real, h, period, _cache) + \
+               1j * tilbert(tmp.imag, h, period, _cache)
+
+    if period is not None:
+        h = h * 2 * pi / period
+
+    n = len(x)
+    omega = _cache.get((n, h))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k, h=h):
+            if k:
+                return 1.0/tanh(h*k)
+
+            return 0
+
+        omega = convolve.init_convolution_kernel(n, kernel, d=1)
+        _cache[(n,h)] = omega
+
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
+
+
+def itilbert(x,h,period=None, _cache=_cache):
+    """
+    Return inverse h-Tilbert transform of a periodic sequence x.
+
+    If ``x_j`` and ``y_j`` are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = -sqrt(-1)*tanh(j*h*2*pi/period) * x_j
+      y_0 = 0
+
+    For more details, see `tilbert`.
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'itilbert_cache'):
+            _cache.itilbert_cache = {}
+        _cache = _cache.itilbert_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return itilbert(tmp.real, h, period, _cache) + \
+               1j*itilbert(tmp.imag, h, period, _cache)
+    if period is not None:
+        h = h*2*pi/period
+    n = len(x)
+    omega = _cache.get((n,h))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k,h=h):
+            if k:
+                return -tanh(h*k)
+            return 0
+        omega = convolve.init_convolution_kernel(n,kernel,d=1)
+        _cache[(n,h)] = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
+
+
+def hilbert(x, _cache=_cache):
+    """
+    Return Hilbert transform of a periodic sequence x.
+
+    If x_j and y_j are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = sqrt(-1)*sign(j) * x_j
+      y_0 = 0
+
+    Parameters
+    ----------
+    x : array_like
+        The input array, should be periodic.
+    _cache : dict, optional
+        Dictionary that contains the kernel used to do a convolution with.
+
+    Returns
+    -------
+    y : ndarray
+        The transformed input.
+
+    See Also
+    --------
+    scipy.signal.hilbert : Compute the analytic signal, using the Hilbert
+                           transform.
+
+    Notes
+    -----
+    If ``sum(x, axis=0) == 0`` then ``hilbert(ihilbert(x)) == x``.
+
+    For even len(x), the Nyquist mode of x is taken zero.
+
+    The sign of the returned transform does not have a factor -1 that is more
+    often than not found in the definition of the Hilbert transform. Note also
+    that `scipy.signal.hilbert` does have an extra -1 factor compared to this
+    function.
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'hilbert_cache'):
+            _cache.hilbert_cache = {}
+        _cache = _cache.hilbert_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return hilbert(tmp.real, _cache) + 1j * hilbert(tmp.imag, _cache)
+    n = len(x)
+    omega = _cache.get(n)
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k):
+            if k > 0:
+                return 1.0
+            elif k < 0:
+                return -1.0
+            return 0.0
+        omega = convolve.init_convolution_kernel(n,kernel,d=1)
+        _cache[n] = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
+
+
+def ihilbert(x, _cache=_cache):
+    """
+    Return inverse Hilbert transform of a periodic sequence x.
+
+    If ``x_j`` and ``y_j`` are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = -sqrt(-1)*sign(j) * x_j
+      y_0 = 0
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'ihilbert_cache'):
+            _cache.ihilbert_cache = {}
+        _cache = _cache.ihilbert_cache
+    return -hilbert(x, _cache)
+
+
+def cs_diff(x, a, b, period=None, _cache=_cache):
+    """
+    Return (a,b)-cosh/sinh pseudo-derivative of a periodic sequence.
+
+    If ``x_j`` and ``y_j`` are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = -sqrt(-1)*cosh(j*a*2*pi/period)/sinh(j*b*2*pi/period) * x_j
+      y_0 = 0
+
+    Parameters
+    ----------
+    x : array_like
+        The array to take the pseudo-derivative from.
+    a, b : float
+        Defines the parameters of the cosh/sinh pseudo-differential
+        operator.
+    period : float, optional
+        The period of the sequence. Default period is ``2*pi``.
+
+    Returns
+    -------
+    cs_diff : ndarray
+        Pseudo-derivative of periodic sequence `x`.
+
+    Notes
+    -----
+    For even len(`x`), the Nyquist mode of `x` is taken as zero.
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'cs_diff_cache'):
+            _cache.cs_diff_cache = {}
+        _cache = _cache.cs_diff_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return cs_diff(tmp.real, a, b, period, _cache) + \
+               1j*cs_diff(tmp.imag, a, b, period, _cache)
+    if period is not None:
+        a = a*2*pi/period
+        b = b*2*pi/period
+    n = len(x)
+    omega = _cache.get((n,a,b))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k,a=a,b=b):
+            if k:
+                return -cosh(a*k)/sinh(b*k)
+            return 0
+        omega = convolve.init_convolution_kernel(n,kernel,d=1)
+        _cache[(n,a,b)] = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
+
+
+def sc_diff(x, a, b, period=None, _cache=_cache):
+    """
+    Return (a,b)-sinh/cosh pseudo-derivative of a periodic sequence x.
+
+    If x_j and y_j are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = sqrt(-1)*sinh(j*a*2*pi/period)/cosh(j*b*2*pi/period) * x_j
+      y_0 = 0
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    a,b : float
+        Defines the parameters of the sinh/cosh pseudo-differential
+        operator.
+    period : float, optional
+        The period of the sequence x. Default is 2*pi.
+
+    Notes
+    -----
+    ``sc_diff(cs_diff(x,a,b),b,a) == x``
+    For even ``len(x)``, the Nyquist mode of x is taken as zero.
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'sc_diff_cache'):
+            _cache.sc_diff_cache = {}
+        _cache = _cache.sc_diff_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return sc_diff(tmp.real, a, b, period, _cache) + \
+               1j * sc_diff(tmp.imag, a, b, period, _cache)
+    if period is not None:
+        a = a*2*pi/period
+        b = b*2*pi/period
+    n = len(x)
+    omega = _cache.get((n,a,b))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k,a=a,b=b):
+            if k:
+                return sinh(a*k)/cosh(b*k)
+            return 0
+        omega = convolve.init_convolution_kernel(n,kernel,d=1)
+        _cache[(n,a,b)] = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
+
+
+def ss_diff(x, a, b, period=None, _cache=_cache):
+    """
+    Return (a,b)-sinh/sinh pseudo-derivative of a periodic sequence x.
+
+    If x_j and y_j are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = sinh(j*a*2*pi/period)/sinh(j*b*2*pi/period) * x_j
+      y_0 = a/b * x_0
+
+    Parameters
+    ----------
+    x : array_like
+        The array to take the pseudo-derivative from.
+    a,b
+        Defines the parameters of the sinh/sinh pseudo-differential
+        operator.
+    period : float, optional
+        The period of the sequence x. Default is ``2*pi``.
+
+    Notes
+    -----
+    ``ss_diff(ss_diff(x,a,b),b,a) == x``
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'ss_diff_cache'):
+            _cache.ss_diff_cache = {}
+        _cache = _cache.ss_diff_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return ss_diff(tmp.real, a, b, period, _cache) + \
+               1j*ss_diff(tmp.imag, a, b, period, _cache)
+    if period is not None:
+        a = a*2*pi/period
+        b = b*2*pi/period
+    n = len(x)
+    omega = _cache.get((n,a,b))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k,a=a,b=b):
+            if k:
+                return sinh(a*k)/sinh(b*k)
+            return float(a)/b
+        omega = convolve.init_convolution_kernel(n,kernel)
+        _cache[(n,a,b)] = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,overwrite_x=overwrite_x)
+
+
+def cc_diff(x, a, b, period=None, _cache=_cache):
+    """
+    Return (a,b)-cosh/cosh pseudo-derivative of a periodic sequence.
+
+    If x_j and y_j are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+      y_j = cosh(j*a*2*pi/period)/cosh(j*b*2*pi/period) * x_j
+
+    Parameters
+    ----------
+    x : array_like
+        The array to take the pseudo-derivative from.
+    a,b : float
+        Defines the parameters of the sinh/sinh pseudo-differential
+        operator.
+    period : float, optional
+        The period of the sequence x. Default is ``2*pi``.
+
+    Returns
+    -------
+    cc_diff : ndarray
+        Pseudo-derivative of periodic sequence `x`.
+
+    Notes
+    -----
+    ``cc_diff(cc_diff(x,a,b),b,a) == x``
+
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'cc_diff_cache'):
+            _cache.cc_diff_cache = {}
+        _cache = _cache.cc_diff_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return cc_diff(tmp.real, a, b, period, _cache) + \
+               1j * cc_diff(tmp.imag, a, b, period, _cache)
+    if period is not None:
+        a = a*2*pi/period
+        b = b*2*pi/period
+    n = len(x)
+    omega = _cache.get((n,a,b))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel(k,a=a,b=b):
+            return cosh(a*k)/cosh(b*k)
+        omega = convolve.init_convolution_kernel(n,kernel)
+        _cache[(n,a,b)] = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve(tmp,omega,overwrite_x=overwrite_x)
+
+
+def shift(x, a, period=None, _cache=_cache):
+    """
+    Shift periodic sequence x by a: y(u) = x(u+a).
+
+    If x_j and y_j are Fourier coefficients of periodic functions x
+    and y, respectively, then::
+
+          y_j = exp(j*a*2*pi/period*sqrt(-1)) * x_f
+
+    Parameters
+    ----------
+    x : array_like
+        The array to take the pseudo-derivative from.
+    a : float
+        Defines the parameters of the sinh/sinh pseudo-differential
+    period : float, optional
+        The period of the sequences x and y. Default period is ``2*pi``.
+    """
+    if isinstance(_cache, threading.local):
+        if not hasattr(_cache, 'shift_cache'):
+            _cache.shift_cache = {}
+        _cache = _cache.shift_cache
+
+    tmp = asarray(x)
+    if iscomplexobj(tmp):
+        return shift(tmp.real, a, period, _cache) + 1j * shift(
+            tmp.imag, a, period, _cache)
+    if period is not None:
+        a = a*2*pi/period
+    n = len(x)
+    omega = _cache.get((n,a))
+    if omega is None:
+        if len(_cache) > 20:
+            while _cache:
+                _cache.popitem()
+
+        def kernel_real(k,a=a):
+            return cos(a*k)
+
+        def kernel_imag(k,a=a):
+            return sin(a*k)
+        omega_real = convolve.init_convolution_kernel(n,kernel_real,d=0,
+                                                      zero_nyquist=0)
+        omega_imag = convolve.init_convolution_kernel(n,kernel_imag,d=1,
+                                                      zero_nyquist=0)
+        _cache[(n,a)] = omega_real,omega_imag
+    else:
+        omega_real,omega_imag = omega
+    overwrite_x = _datacopied(tmp, x)
+    return convolve.convolve_z(tmp,omega_real,omega_imag,
+                               overwrite_x=overwrite_x)
+
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/_realtransforms.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/_realtransforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad71d517b0ac829ab71850bf67f7dc38636161f2
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/_realtransforms.py
@@ -0,0 +1,598 @@
+"""
+Real spectrum transforms (DCT, DST, MDCT)
+"""
+
+__all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn']
+
+from scipy.fft import _pocketfft
+from ._helper import _good_shape
+
+_inverse_typemap = {1: 1, 2: 3, 3: 2, 4: 4}
+
+
+def dctn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
+    """
+    Return multidimensional Discrete Cosine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    shape : int or array_like of ints or None, optional
+        The shape of the result. If both `shape` and `axes` (see below) are
+        None, `shape` is ``x.shape``; if `shape` is None but `axes` is
+        not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
+        If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
+        If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
+        length ``shape[i]``.
+        If any element of `shape` is -1, the size of the corresponding
+        dimension of `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes along which the DCT is computed.
+        The default is over all axes.
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    idctn : Inverse multidimensional DCT
+
+    Notes
+    -----
+    For full details of the DCT types and normalization modes, as well as
+    references, see `dct`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import dctn, idctn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idctn(dctn(y, norm='ortho'), norm='ortho'))
+    True
+
+    """
+    shape = _good_shape(x, shape, axes)
+    return _pocketfft.dctn(x, type, shape, axes, norm, overwrite_x)
+
+
+def idctn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
+    """
+    Return multidimensional Discrete Cosine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    shape : int or array_like of ints or None, optional
+        The shape of the result.  If both `shape` and `axes` (see below) are
+        None, `shape` is ``x.shape``; if `shape` is None but `axes` is
+        not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
+        If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
+        If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
+        length ``shape[i]``.
+        If any element of `shape` is -1, the size of the corresponding
+        dimension of `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes along which the IDCT is computed.
+        The default is over all axes.
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dctn : multidimensional DCT
+
+    Notes
+    -----
+    For full details of the IDCT types and normalization modes, as well as
+    references, see `idct`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import dctn, idctn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idctn(dctn(y, norm='ortho'), norm='ortho'))
+    True
+
+    """
+    type = _inverse_typemap[type]
+    shape = _good_shape(x, shape, axes)
+    return _pocketfft.dctn(x, type, shape, axes, norm, overwrite_x)
+
+
+def dstn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
+    """
+    Return multidimensional Discrete Sine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    shape : int or array_like of ints or None, optional
+        The shape of the result.  If both `shape` and `axes` (see below) are
+        None, `shape` is ``x.shape``; if `shape` is None but `axes` is
+        not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
+        If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
+        If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
+        length ``shape[i]``.
+        If any element of `shape` is -1, the size of the corresponding
+        dimension of `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes along which the DCT is computed.
+        The default is over all axes.
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    idstn : Inverse multidimensional DST
+
+    Notes
+    -----
+    For full details of the DST types and normalization modes, as well as
+    references, see `dst`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import dstn, idstn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idstn(dstn(y, norm='ortho'), norm='ortho'))
+    True
+
+    """
+    shape = _good_shape(x, shape, axes)
+    return _pocketfft.dstn(x, type, shape, axes, norm, overwrite_x)
+
+
+def idstn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
+    """
+    Return multidimensional Discrete Sine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    shape : int or array_like of ints or None, optional
+        The shape of the result.  If both `shape` and `axes` (see below) are
+        None, `shape` is ``x.shape``; if `shape` is None but `axes` is
+        not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
+        If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
+        If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
+        length ``shape[i]``.
+        If any element of `shape` is -1, the size of the corresponding
+        dimension of `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes along which the IDST is computed.
+        The default is over all axes.
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dstn : multidimensional DST
+
+    Notes
+    -----
+    For full details of the IDST types and normalization modes, as well as
+    references, see `idst`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fftpack import dstn, idstn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idstn(dstn(y, norm='ortho'), norm='ortho'))
+    True
+
+    """
+    type = _inverse_typemap[type]
+    shape = _good_shape(x, shape, axes)
+    return _pocketfft.dstn(x, type, shape, axes, norm, overwrite_x)
+
+
+def dct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
+    r"""
+    Return the Discrete Cosine Transform of arbitrary type sequence x.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform.  If ``n < x.shape[axis]``, `x` is
+        truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the dct is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    idct : Inverse DCT
+
+    Notes
+    -----
+    For a single dimension array ``x``, ``dct(x, norm='ortho')`` is equal to
+    MATLAB ``dct(x)``.
+
+    There are, theoretically, 8 types of the DCT, only the first 4 types are
+    implemented in scipy. 'The' DCT generally refers to DCT type 2, and 'the'
+    Inverse DCT generally refers to DCT type 3.
+
+    **Type I**
+
+    There are several definitions of the DCT-I; we use the following
+    (for ``norm=None``)
+
+    .. math::
+
+       y_k = x_0 + (-1)^k x_{N-1} + 2 \sum_{n=1}^{N-2} x_n \cos\left(
+       \frac{\pi k n}{N-1} \right)
+
+    If ``norm='ortho'``, ``x[0]`` and ``x[N-1]`` are multiplied by a scaling
+    factor of :math:`\sqrt{2}`, and ``y[k]`` is multiplied by a scaling factor
+    ``f``
+
+    .. math::
+
+        f = \begin{cases}
+         \frac{1}{2}\sqrt{\frac{1}{N-1}} & \text{if }k=0\text{ or }N-1, \\
+         \frac{1}{2}\sqrt{\frac{2}{N-1}} & \text{otherwise} \end{cases}
+
+    .. versionadded:: 1.2.0
+       Orthonormalization in DCT-I.
+
+    .. note::
+       The DCT-I is only supported for input size > 1.
+
+    **Type II**
+
+    There are several definitions of the DCT-II; we use the following
+    (for ``norm=None``)
+
+    .. math::
+
+       y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi k(2n+1)}{2N} \right)
+
+    If ``norm='ortho'``, ``y[k]`` is multiplied by a scaling factor ``f``
+
+    .. math::
+       f = \begin{cases}
+       \sqrt{\frac{1}{4N}} & \text{if }k=0, \\
+       \sqrt{\frac{1}{2N}} & \text{otherwise} \end{cases}
+
+    which makes the corresponding matrix of coefficients orthonormal
+    (``O @ O.T = np.eye(N)``).
+
+    **Type III**
+
+    There are several definitions, we use the following (for ``norm=None``)
+
+    .. math::
+
+       y_k = x_0 + 2 \sum_{n=1}^{N-1} x_n \cos\left(\frac{\pi(2k+1)n}{2N}\right)
+
+    or, for ``norm='ortho'``
+
+    .. math::
+
+       y_k = \frac{x_0}{\sqrt{N}} + \sqrt{\frac{2}{N}} \sum_{n=1}^{N-1} x_n
+       \cos\left(\frac{\pi(2k+1)n}{2N}\right)
+
+    The (unnormalized) DCT-III is the inverse of the (unnormalized) DCT-II, up
+    to a factor ``2N``. The orthonormalized DCT-III is exactly the inverse of
+    the orthonormalized DCT-II.
+
+    **Type IV**
+
+    There are several definitions of the DCT-IV; we use the following
+    (for ``norm=None``)
+
+    .. math::
+
+       y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi(2k+1)(2n+1)}{4N} \right)
+
+    If ``norm='ortho'``, ``y[k]`` is multiplied by a scaling factor ``f``
+
+    .. math::
+
+        f = \frac{1}{\sqrt{2N}}
+
+    .. versionadded:: 1.2.0
+       Support for DCT-IV.
+
+    References
+    ----------
+    .. [1] 'A Fast Cosine Transform in One and Two Dimensions', by J.
+           Makhoul, `IEEE Transactions on acoustics, speech and signal
+           processing` vol. 28(1), pp. 27-34,
+           :doi:`10.1109/TASSP.1980.1163351` (1980).
+    .. [2] Wikipedia, "Discrete cosine transform",
+           https://en.wikipedia.org/wiki/Discrete_cosine_transform
+
+    Examples
+    --------
+    The Type 1 DCT is equivalent to the FFT (though faster) for real,
+    even-symmetrical inputs. The output is also real and even-symmetrical.
+    Half of the FFT input is used to generate half of the FFT output:
+
+    >>> from scipy.fftpack import fft, dct
+    >>> import numpy as np
+    >>> fft(np.array([4., 3., 5., 10., 5., 3.])).real
+    array([ 30.,  -8.,   6.,  -2.,   6.,  -8.])
+    >>> dct(np.array([4., 3., 5., 10.]), 1)
+    array([ 30.,  -8.,   6.,  -2.])
+
+    """
+    return _pocketfft.dct(x, type, n, axis, norm, overwrite_x)
+
+
+def idct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
+    """
+    Return the Inverse Discrete Cosine Transform of an arbitrary type sequence.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform.  If ``n < x.shape[axis]``, `x` is
+        truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the idct is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    idct : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dct : Forward DCT
+
+    Notes
+    -----
+    For a single dimension array `x`, ``idct(x, norm='ortho')`` is equal to
+    MATLAB ``idct(x)``.
+
+    'The' IDCT is the IDCT of type 2, which is the same as DCT of type 3.
+
+    IDCT of type 1 is the DCT of type 1, IDCT of type 2 is the DCT of type
+    3, and IDCT of type 3 is the DCT of type 2. IDCT of type 4 is the DCT
+    of type 4. For the definition of these types, see `dct`.
+
+    Examples
+    --------
+    The Type 1 DCT is equivalent to the DFT for real, even-symmetrical
+    inputs. The output is also real and even-symmetrical. Half of the IFFT
+    input is used to generate half of the IFFT output:
+
+    >>> from scipy.fftpack import ifft, idct
+    >>> import numpy as np
+    >>> ifft(np.array([ 30.,  -8.,   6.,  -2.,   6.,  -8.])).real
+    array([  4.,   3.,   5.,  10.,   5.,   3.])
+    >>> idct(np.array([ 30.,  -8.,   6.,  -2.]), 1) / 6
+    array([  4.,   3.,   5.,  10.])
+
+    """
+    type = _inverse_typemap[type]
+    return _pocketfft.dct(x, type, n, axis, norm, overwrite_x)
+
+
+def dst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
+    r"""
+    Return the Discrete Sine Transform of arbitrary type sequence x.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform.  If ``n < x.shape[axis]``, `x` is
+        truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the dst is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    dst : ndarray of reals
+        The transformed input array.
+
+    See Also
+    --------
+    idst : Inverse DST
+
+    Notes
+    -----
+    For a single dimension array ``x``.
+
+    There are, theoretically, 8 types of the DST for different combinations of
+    even/odd boundary conditions and boundary off sets [1]_, only the first
+    4 types are implemented in scipy.
+
+    **Type I**
+
+    There are several definitions of the DST-I; we use the following
+    for ``norm=None``. DST-I assumes the input is odd around `n=-1` and `n=N`.
+
+    .. math::
+
+        y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(n+1)}{N+1}\right)
+
+    Note that the DST-I is only supported for input size > 1.
+    The (unnormalized) DST-I is its own inverse, up to a factor ``2(N+1)``.
+    The orthonormalized DST-I is exactly its own inverse.
+
+    **Type II**
+
+    There are several definitions of the DST-II; we use the following for
+    ``norm=None``. DST-II assumes the input is odd around `n=-1/2` and
+    `n=N-1/2`; the output is odd around :math:`k=-1` and even around `k=N-1`
+
+    .. math::
+
+        y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(2n+1)}{2N}\right)
+
+    if ``norm='ortho'``, ``y[k]`` is multiplied by a scaling factor ``f``
+
+    .. math::
+
+        f = \begin{cases}
+        \sqrt{\frac{1}{4N}} & \text{if }k = 0, \\
+        \sqrt{\frac{1}{2N}} & \text{otherwise} \end{cases}
+
+    **Type III**
+
+    There are several definitions of the DST-III, we use the following (for
+    ``norm=None``). DST-III assumes the input is odd around `n=-1` and even
+    around `n=N-1`
+
+    .. math::
+
+        y_k = (-1)^k x_{N-1} + 2 \sum_{n=0}^{N-2} x_n \sin\left(
+        \frac{\pi(2k+1)(n+1)}{2N}\right)
+
+    The (unnormalized) DST-III is the inverse of the (unnormalized) DST-II, up
+    to a factor ``2N``. The orthonormalized DST-III is exactly the inverse of the
+    orthonormalized DST-II.
+
+    .. versionadded:: 0.11.0
+
+    **Type IV**
+
+    There are several definitions of the DST-IV, we use the following (for
+    ``norm=None``). DST-IV assumes the input is odd around `n=-0.5` and even
+    around `n=N-0.5`
+
+    .. math::
+
+        y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(2k+1)(2n+1)}{4N}\right)
+
+    The (unnormalized) DST-IV is its own inverse, up to a factor ``2N``. The
+    orthonormalized DST-IV is exactly its own inverse.
+
+    .. versionadded:: 1.2.0
+       Support for DST-IV.
+
+    References
+    ----------
+    .. [1] Wikipedia, "Discrete sine transform",
+           https://en.wikipedia.org/wiki/Discrete_sine_transform
+
+    """
+    return _pocketfft.dst(x, type, n, axis, norm, overwrite_x)
+
+
+def idst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
+    """
+    Return the Inverse Discrete Sine Transform of an arbitrary type sequence.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform.  If ``n < x.shape[axis]``, `x` is
+        truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the idst is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {None, 'ortho'}, optional
+        Normalization mode (see Notes). Default is None.
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+
+    Returns
+    -------
+    idst : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dst : Forward DST
+
+    Notes
+    -----
+    'The' IDST is the IDST of type 2, which is the same as DST of type 3.
+
+    IDST of type 1 is the DST of type 1, IDST of type 2 is the DST of type
+    3, and IDST of type 3 is the DST of type 2. For the definition of these
+    types, see `dst`.
+
+    .. versionadded:: 0.11.0
+
+    """
+    type = _inverse_typemap[type]
+    return _pocketfft.dst(x, type, n, axis, norm, overwrite_x)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/basic.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..553f456fe1561c28928ecc4ebe2238459cc60443
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/basic.py
@@ -0,0 +1,20 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.fftpack` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'fft','ifft','fftn','ifftn','rfft','irfft',
+    'fft2','ifft2'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="fftpack", module="basic",
+                                   private_modules=["_basic"], all=__all__,
+                                   attribute=name)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/convolve.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/convolve.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..bb567271d7ed412d8f28244d165c139639054495
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/convolve.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:f4080933209e3ec1fc2f3c77e2f4d14edada022bbff0e9e002a00281ce4c6139
+size 128784
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/helper.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..fcc7000c215f8a7605a2a59b5767b27b2fcd969d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/helper.py
@@ -0,0 +1,19 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.fftpack` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'fftshift', 'ifftshift', 'fftfreq', 'rfftfreq', 'next_fast_len'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="fftpack", module="helper",
+                                   private_modules=["_helper"], all=__all__,
+                                   attribute=name)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/pseudo_diffs.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/pseudo_diffs.py
new file mode 100644
index 0000000000000000000000000000000000000000..ecf71ad3256d48d2131c8058072da724cb001af9
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/pseudo_diffs.py
@@ -0,0 +1,22 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.fftpack` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'diff',
+    'tilbert', 'itilbert', 'hilbert', 'ihilbert',
+    'cs_diff', 'cc_diff', 'sc_diff', 'ss_diff',
+    'shift', 'convolve'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="fftpack", module="pseudo_diffs",
+                                   private_modules=["_pseudo_diffs"], all=__all__,
+                                   attribute=name)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/realtransforms.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/realtransforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a392198fccf213bc988a79058bd69515e39f510
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/fftpack/realtransforms.py
@@ -0,0 +1,19 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.fftpack` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="fftpack", module="realtransforms",
+                                   private_modules=["_realtransforms"], all=__all__,
+                                   attribute=name)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1533b5c60b695fce0abf08e2163dfba3bdd4fb17
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/__init__.py
@@ -0,0 +1,122 @@
+"""
+=============================================
+Integration and ODEs (:mod:`scipy.integrate`)
+=============================================
+
+.. currentmodule:: scipy.integrate
+
+Integrating functions, given function object
+============================================
+
+.. autosummary::
+   :toctree: generated/
+
+   quad          -- General purpose integration
+   quad_vec      -- General purpose integration of vector-valued functions
+   cubature      -- General purpose multi-dimensional integration of array-valued functions
+   dblquad       -- General purpose double integration
+   tplquad       -- General purpose triple integration
+   nquad         -- General purpose N-D integration
+   tanhsinh      -- General purpose elementwise integration
+   fixed_quad    -- Integrate func(x) using Gaussian quadrature of order n
+   newton_cotes  -- Weights and error coefficient for Newton-Cotes integration
+   lebedev_rule
+   qmc_quad      -- N-D integration using Quasi-Monte Carlo quadrature
+   IntegrationWarning -- Warning on issues during integration
+
+
+Integrating functions, given fixed samples
+==========================================
+
+.. autosummary::
+   :toctree: generated/
+
+   trapezoid            -- Use trapezoidal rule to compute integral.
+   cumulative_trapezoid -- Use trapezoidal rule to cumulatively compute integral.
+   simpson              -- Use Simpson's rule to compute integral from samples.
+   cumulative_simpson   -- Use Simpson's rule to cumulatively compute integral from samples.
+   romb                 -- Use Romberg Integration to compute integral from
+                        -- (2**k + 1) evenly-spaced samples.
+
+.. seealso::
+
+   :mod:`scipy.special` for orthogonal polynomials (special) for Gaussian
+   quadrature roots and weights for other weighting factors and regions.
+
+Summation
+=========
+
+.. autosummary::
+   :toctree: generated/
+
+   nsum
+
+Solving initial value problems for ODE systems
+==============================================
+
+The solvers are implemented as individual classes, which can be used directly
+(low-level usage) or through a convenience function.
+
+.. autosummary::
+   :toctree: generated/
+
+   solve_ivp     -- Convenient function for ODE integration.
+   RK23          -- Explicit Runge-Kutta solver of order 3(2).
+   RK45          -- Explicit Runge-Kutta solver of order 5(4).
+   DOP853        -- Explicit Runge-Kutta solver of order 8.
+   Radau         -- Implicit Runge-Kutta solver of order 5.
+   BDF           -- Implicit multi-step variable order (1 to 5) solver.
+   LSODA         -- LSODA solver from ODEPACK Fortran package.
+   OdeSolver     -- Base class for ODE solvers.
+   DenseOutput   -- Local interpolant for computing a dense output.
+   OdeSolution   -- Class which represents a continuous ODE solution.
+
+
+Old API
+-------
+
+These are the routines developed earlier for SciPy. They wrap older solvers
+implemented in Fortran (mostly ODEPACK). While the interface to them is not
+particularly convenient and certain features are missing compared to the new
+API, the solvers themselves are of good quality and work fast as compiled
+Fortran code. In some cases, it might be worth using this old API.
+
+.. autosummary::
+   :toctree: generated/
+
+   odeint        -- General integration of ordinary differential equations.
+   ode           -- Integrate ODE using VODE and ZVODE routines.
+   complex_ode   -- Convert a complex-valued ODE to real-valued and integrate.
+   ODEintWarning -- Warning raised during the execution of `odeint`.
+
+
+Solving boundary value problems for ODE systems
+===============================================
+
+.. autosummary::
+   :toctree: generated/
+
+   solve_bvp     -- Solve a boundary value problem for a system of ODEs.
+"""  # noqa: E501
+
+
+from ._quadrature import *
+from ._odepack_py import *
+from ._quadpack_py import *
+from ._ode import *
+from ._bvp import solve_bvp
+from ._ivp import (solve_ivp, OdeSolution, DenseOutput,
+                   OdeSolver, RK23, RK45, DOP853, Radau, BDF, LSODA)
+from ._quad_vec import quad_vec
+from ._tanhsinh import nsum, tanhsinh
+from ._cubature import cubature
+from ._lebedev import lebedev_rule
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import dop, lsoda, vode, odepack, quadpack
+
+__all__ = [s for s in dir() if not s.startswith('_')]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_bvp.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_bvp.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe2e0ae50b25a746c3f0fbe59ea463cd452b5938
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_bvp.py
@@ -0,0 +1,1160 @@
+"""Boundary value problem solver."""
+from warnings import warn
+
+import numpy as np
+from numpy.linalg import pinv
+
+from scipy.sparse import coo_matrix, csc_matrix
+from scipy.sparse.linalg import splu
+from scipy.optimize import OptimizeResult
+
+
+EPS = np.finfo(float).eps
+
+
+def estimate_fun_jac(fun, x, y, p, f0=None):
+    """Estimate derivatives of an ODE system rhs with forward differences.
+
+    Returns
+    -------
+    df_dy : ndarray, shape (n, n, m)
+        Derivatives with respect to y. An element (i, j, q) corresponds to
+        d f_i(x_q, y_q) / d (y_q)_j.
+    df_dp : ndarray with shape (n, k, m) or None
+        Derivatives with respect to p. An element (i, j, q) corresponds to
+        d f_i(x_q, y_q, p) / d p_j. If `p` is empty, None is returned.
+    """
+    n, m = y.shape
+    if f0 is None:
+        f0 = fun(x, y, p)
+
+    dtype = y.dtype
+
+    df_dy = np.empty((n, n, m), dtype=dtype)
+    h = EPS**0.5 * (1 + np.abs(y))
+    for i in range(n):
+        y_new = y.copy()
+        y_new[i] += h[i]
+        hi = y_new[i] - y[i]
+        f_new = fun(x, y_new, p)
+        df_dy[:, i, :] = (f_new - f0) / hi
+
+    k = p.shape[0]
+    if k == 0:
+        df_dp = None
+    else:
+        df_dp = np.empty((n, k, m), dtype=dtype)
+        h = EPS**0.5 * (1 + np.abs(p))
+        for i in range(k):
+            p_new = p.copy()
+            p_new[i] += h[i]
+            hi = p_new[i] - p[i]
+            f_new = fun(x, y, p_new)
+            df_dp[:, i, :] = (f_new - f0) / hi
+
+    return df_dy, df_dp
+
+
+def estimate_bc_jac(bc, ya, yb, p, bc0=None):
+    """Estimate derivatives of boundary conditions with forward differences.
+
+    Returns
+    -------
+    dbc_dya : ndarray, shape (n + k, n)
+        Derivatives with respect to ya. An element (i, j) corresponds to
+        d bc_i / d ya_j.
+    dbc_dyb : ndarray, shape (n + k, n)
+        Derivatives with respect to yb. An element (i, j) corresponds to
+        d bc_i / d ya_j.
+    dbc_dp : ndarray with shape (n + k, k) or None
+        Derivatives with respect to p. An element (i, j) corresponds to
+        d bc_i / d p_j. If `p` is empty, None is returned.
+    """
+    n = ya.shape[0]
+    k = p.shape[0]
+
+    if bc0 is None:
+        bc0 = bc(ya, yb, p)
+
+    dtype = ya.dtype
+
+    dbc_dya = np.empty((n, n + k), dtype=dtype)
+    h = EPS**0.5 * (1 + np.abs(ya))
+    for i in range(n):
+        ya_new = ya.copy()
+        ya_new[i] += h[i]
+        hi = ya_new[i] - ya[i]
+        bc_new = bc(ya_new, yb, p)
+        dbc_dya[i] = (bc_new - bc0) / hi
+    dbc_dya = dbc_dya.T
+
+    h = EPS**0.5 * (1 + np.abs(yb))
+    dbc_dyb = np.empty((n, n + k), dtype=dtype)
+    for i in range(n):
+        yb_new = yb.copy()
+        yb_new[i] += h[i]
+        hi = yb_new[i] - yb[i]
+        bc_new = bc(ya, yb_new, p)
+        dbc_dyb[i] = (bc_new - bc0) / hi
+    dbc_dyb = dbc_dyb.T
+
+    if k == 0:
+        dbc_dp = None
+    else:
+        h = EPS**0.5 * (1 + np.abs(p))
+        dbc_dp = np.empty((k, n + k), dtype=dtype)
+        for i in range(k):
+            p_new = p.copy()
+            p_new[i] += h[i]
+            hi = p_new[i] - p[i]
+            bc_new = bc(ya, yb, p_new)
+            dbc_dp[i] = (bc_new - bc0) / hi
+        dbc_dp = dbc_dp.T
+
+    return dbc_dya, dbc_dyb, dbc_dp
+
+
+def compute_jac_indices(n, m, k):
+    """Compute indices for the collocation system Jacobian construction.
+
+    See `construct_global_jac` for the explanation.
+    """
+    i_col = np.repeat(np.arange((m - 1) * n), n)
+    j_col = (np.tile(np.arange(n), n * (m - 1)) +
+             np.repeat(np.arange(m - 1) * n, n**2))
+
+    i_bc = np.repeat(np.arange((m - 1) * n, m * n + k), n)
+    j_bc = np.tile(np.arange(n), n + k)
+
+    i_p_col = np.repeat(np.arange((m - 1) * n), k)
+    j_p_col = np.tile(np.arange(m * n, m * n + k), (m - 1) * n)
+
+    i_p_bc = np.repeat(np.arange((m - 1) * n, m * n + k), k)
+    j_p_bc = np.tile(np.arange(m * n, m * n + k), n + k)
+
+    i = np.hstack((i_col, i_col, i_bc, i_bc, i_p_col, i_p_bc))
+    j = np.hstack((j_col, j_col + n,
+                   j_bc, j_bc + (m - 1) * n,
+                   j_p_col, j_p_bc))
+
+    return i, j
+
+
+def stacked_matmul(a, b):
+    """Stacked matrix multiply: out[i,:,:] = np.dot(a[i,:,:], b[i,:,:]).
+
+    Empirical optimization. Use outer Python loop and BLAS for large
+    matrices, otherwise use a single einsum call.
+    """
+    if a.shape[1] > 50:
+        out = np.empty((a.shape[0], a.shape[1], b.shape[2]))
+        for i in range(a.shape[0]):
+            out[i] = np.dot(a[i], b[i])
+        return out
+    else:
+        return np.einsum('...ij,...jk->...ik', a, b)
+
+
+def construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy, df_dy_middle, df_dp,
+                         df_dp_middle, dbc_dya, dbc_dyb, dbc_dp):
+    """Construct the Jacobian of the collocation system.
+
+    There are n * m + k functions: m - 1 collocations residuals, each
+    containing n components, followed by n + k boundary condition residuals.
+
+    There are n * m + k variables: m vectors of y, each containing n
+    components, followed by k values of vector p.
+
+    For example, let m = 4, n = 2 and k = 1, then the Jacobian will have
+    the following sparsity structure:
+
+        1 1 2 2 0 0 0 0  5
+        1 1 2 2 0 0 0 0  5
+        0 0 1 1 2 2 0 0  5
+        0 0 1 1 2 2 0 0  5
+        0 0 0 0 1 1 2 2  5
+        0 0 0 0 1 1 2 2  5
+
+        3 3 0 0 0 0 4 4  6
+        3 3 0 0 0 0 4 4  6
+        3 3 0 0 0 0 4 4  6
+
+    Zeros denote identically zero values, other values denote different kinds
+    of blocks in the matrix (see below). The blank row indicates the separation
+    of collocation residuals from boundary conditions. And the blank column
+    indicates the separation of y values from p values.
+
+    Refer to [1]_  (p. 306) for the formula of n x n blocks for derivatives
+    of collocation residuals with respect to y.
+
+    Parameters
+    ----------
+    n : int
+        Number of equations in the ODE system.
+    m : int
+        Number of nodes in the mesh.
+    k : int
+        Number of the unknown parameters.
+    i_jac, j_jac : ndarray
+        Row and column indices returned by `compute_jac_indices`. They
+        represent different blocks in the Jacobian matrix in the following
+        order (see the scheme above):
+
+            * 1: m - 1 diagonal n x n blocks for the collocation residuals.
+            * 2: m - 1 off-diagonal n x n blocks for the collocation residuals.
+            * 3 : (n + k) x n block for the dependency of the boundary
+              conditions on ya.
+            * 4: (n + k) x n block for the dependency of the boundary
+              conditions on yb.
+            * 5: (m - 1) * n x k block for the dependency of the collocation
+              residuals on p.
+            * 6: (n + k) x k block for the dependency of the boundary
+              conditions on p.
+
+    df_dy : ndarray, shape (n, n, m)
+        Jacobian of f with respect to y computed at the mesh nodes.
+    df_dy_middle : ndarray, shape (n, n, m - 1)
+        Jacobian of f with respect to y computed at the middle between the
+        mesh nodes.
+    df_dp : ndarray with shape (n, k, m) or None
+        Jacobian of f with respect to p computed at the mesh nodes.
+    df_dp_middle : ndarray with shape (n, k, m - 1) or None
+        Jacobian of f with respect to p computed at the middle between the
+        mesh nodes.
+    dbc_dya, dbc_dyb : ndarray, shape (n, n)
+        Jacobian of bc with respect to ya and yb.
+    dbc_dp : ndarray with shape (n, k) or None
+        Jacobian of bc with respect to p.
+
+    Returns
+    -------
+    J : csc_matrix, shape (n * m + k, n * m + k)
+        Jacobian of the collocation system in a sparse form.
+
+    References
+    ----------
+    .. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
+       Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
+       Number 3, pp. 299-316, 2001.
+    """
+    df_dy = np.transpose(df_dy, (2, 0, 1))
+    df_dy_middle = np.transpose(df_dy_middle, (2, 0, 1))
+
+    h = h[:, np.newaxis, np.newaxis]
+
+    dtype = df_dy.dtype
+
+    # Computing diagonal n x n blocks.
+    dPhi_dy_0 = np.empty((m - 1, n, n), dtype=dtype)
+    dPhi_dy_0[:] = -np.identity(n)
+    dPhi_dy_0 -= h / 6 * (df_dy[:-1] + 2 * df_dy_middle)
+    T = stacked_matmul(df_dy_middle, df_dy[:-1])
+    dPhi_dy_0 -= h**2 / 12 * T
+
+    # Computing off-diagonal n x n blocks.
+    dPhi_dy_1 = np.empty((m - 1, n, n), dtype=dtype)
+    dPhi_dy_1[:] = np.identity(n)
+    dPhi_dy_1 -= h / 6 * (df_dy[1:] + 2 * df_dy_middle)
+    T = stacked_matmul(df_dy_middle, df_dy[1:])
+    dPhi_dy_1 += h**2 / 12 * T
+
+    values = np.hstack((dPhi_dy_0.ravel(), dPhi_dy_1.ravel(), dbc_dya.ravel(),
+                        dbc_dyb.ravel()))
+
+    if k > 0:
+        df_dp = np.transpose(df_dp, (2, 0, 1))
+        df_dp_middle = np.transpose(df_dp_middle, (2, 0, 1))
+        T = stacked_matmul(df_dy_middle, df_dp[:-1] - df_dp[1:])
+        df_dp_middle += 0.125 * h * T
+        dPhi_dp = -h/6 * (df_dp[:-1] + df_dp[1:] + 4 * df_dp_middle)
+        values = np.hstack((values, dPhi_dp.ravel(), dbc_dp.ravel()))
+
+    J = coo_matrix((values, (i_jac, j_jac)))
+    return csc_matrix(J)
+
+
+def collocation_fun(fun, y, p, x, h):
+    """Evaluate collocation residuals.
+
+    This function lies in the core of the method. The solution is sought
+    as a cubic C1 continuous spline with derivatives matching the ODE rhs
+    at given nodes `x`. Collocation conditions are formed from the equality
+    of the spline derivatives and rhs of the ODE system in the middle points
+    between nodes.
+
+    Such method is classified to Lobbato IIIA family in ODE literature.
+    Refer to [1]_ for the formula and some discussion.
+
+    Returns
+    -------
+    col_res : ndarray, shape (n, m - 1)
+        Collocation residuals at the middle points of the mesh intervals.
+    y_middle : ndarray, shape (n, m - 1)
+        Values of the cubic spline evaluated at the middle points of the mesh
+        intervals.
+    f : ndarray, shape (n, m)
+        RHS of the ODE system evaluated at the mesh nodes.
+    f_middle : ndarray, shape (n, m - 1)
+        RHS of the ODE system evaluated at the middle points of the mesh
+        intervals (and using `y_middle`).
+
+    References
+    ----------
+    .. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
+           Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
+           Number 3, pp. 299-316, 2001.
+    """
+    f = fun(x, y, p)
+    y_middle = (0.5 * (y[:, 1:] + y[:, :-1]) -
+                0.125 * h * (f[:, 1:] - f[:, :-1]))
+    f_middle = fun(x[:-1] + 0.5 * h, y_middle, p)
+    col_res = y[:, 1:] - y[:, :-1] - h / 6 * (f[:, :-1] + f[:, 1:] +
+                                              4 * f_middle)
+
+    return col_res, y_middle, f, f_middle
+
+
+def prepare_sys(n, m, k, fun, bc, fun_jac, bc_jac, x, h):
+    """Create the function and the Jacobian for the collocation system."""
+    x_middle = x[:-1] + 0.5 * h
+    i_jac, j_jac = compute_jac_indices(n, m, k)
+
+    def col_fun(y, p):
+        return collocation_fun(fun, y, p, x, h)
+
+    def sys_jac(y, p, y_middle, f, f_middle, bc0):
+        if fun_jac is None:
+            df_dy, df_dp = estimate_fun_jac(fun, x, y, p, f)
+            df_dy_middle, df_dp_middle = estimate_fun_jac(
+                fun, x_middle, y_middle, p, f_middle)
+        else:
+            df_dy, df_dp = fun_jac(x, y, p)
+            df_dy_middle, df_dp_middle = fun_jac(x_middle, y_middle, p)
+
+        if bc_jac is None:
+            dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(bc, y[:, 0], y[:, -1],
+                                                       p, bc0)
+        else:
+            dbc_dya, dbc_dyb, dbc_dp = bc_jac(y[:, 0], y[:, -1], p)
+
+        return construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy,
+                                    df_dy_middle, df_dp, df_dp_middle, dbc_dya,
+                                    dbc_dyb, dbc_dp)
+
+    return col_fun, sys_jac
+
+
+def solve_newton(n, m, h, col_fun, bc, jac, y, p, B, bvp_tol, bc_tol):
+    """Solve the nonlinear collocation system by a Newton method.
+
+    This is a simple Newton method with a backtracking line search. As
+    advised in [1]_, an affine-invariant criterion function F = ||J^-1 r||^2
+    is used, where J is the Jacobian matrix at the current iteration and r is
+    the vector or collocation residuals (values of the system lhs).
+
+    The method alters between full Newton iterations and the fixed-Jacobian
+    iterations based
+
+    There are other tricks proposed in [1]_, but they are not used as they
+    don't seem to improve anything significantly, and even break the
+    convergence on some test problems I tried.
+
+    All important parameters of the algorithm are defined inside the function.
+
+    Parameters
+    ----------
+    n : int
+        Number of equations in the ODE system.
+    m : int
+        Number of nodes in the mesh.
+    h : ndarray, shape (m-1,)
+        Mesh intervals.
+    col_fun : callable
+        Function computing collocation residuals.
+    bc : callable
+        Function computing boundary condition residuals.
+    jac : callable
+        Function computing the Jacobian of the whole system (including
+        collocation and boundary condition residuals). It is supposed to
+        return csc_matrix.
+    y : ndarray, shape (n, m)
+        Initial guess for the function values at the mesh nodes.
+    p : ndarray, shape (k,)
+        Initial guess for the unknown parameters.
+    B : ndarray with shape (n, n) or None
+        Matrix to force the S y(a) = 0 condition for a problems with the
+        singular term. If None, the singular term is assumed to be absent.
+    bvp_tol : float
+        Tolerance to which we want to solve a BVP.
+    bc_tol : float
+        Tolerance to which we want to satisfy the boundary conditions.
+
+    Returns
+    -------
+    y : ndarray, shape (n, m)
+        Final iterate for the function values at the mesh nodes.
+    p : ndarray, shape (k,)
+        Final iterate for the unknown parameters.
+    singular : bool
+        True, if the LU decomposition failed because Jacobian turned out
+        to be singular.
+
+    References
+    ----------
+    .. [1]  U. Ascher, R. Mattheij and R. Russell "Numerical Solution of
+       Boundary Value Problems for Ordinary Differential Equations",
+       Philidelphia, PA: Society for Industrial and Applied Mathematics,
+       1995.
+    """
+    # We know that the solution residuals at the middle points of the mesh
+    # are connected with collocation residuals  r_middle = 1.5 * col_res / h.
+    # As our BVP solver tries to decrease relative residuals below a certain
+    # tolerance, it seems reasonable to terminated Newton iterations by
+    # comparison of r_middle / (1 + np.abs(f_middle)) with a certain threshold,
+    # which we choose to be 1.5 orders lower than the BVP tolerance. We rewrite
+    # the condition as col_res < tol_r * (1 + np.abs(f_middle)), then tol_r
+    # should be computed as follows:
+    tol_r = 2/3 * h * 5e-2 * bvp_tol
+
+    # Maximum allowed number of Jacobian evaluation and factorization, in
+    # other words, the maximum number of full Newton iterations. A small value
+    # is recommended in the literature.
+    max_njev = 4
+
+    # Maximum number of iterations, considering that some of them can be
+    # performed with the fixed Jacobian. In theory, such iterations are cheap,
+    # but it's not that simple in Python.
+    max_iter = 8
+
+    # Minimum relative improvement of the criterion function to accept the
+    # step (Armijo constant).
+    sigma = 0.2
+
+    # Step size decrease factor for backtracking.
+    tau = 0.5
+
+    # Maximum number of backtracking steps, the minimum step is then
+    # tau ** n_trial.
+    n_trial = 4
+
+    col_res, y_middle, f, f_middle = col_fun(y, p)
+    bc_res = bc(y[:, 0], y[:, -1], p)
+    res = np.hstack((col_res.ravel(order='F'), bc_res))
+
+    njev = 0
+    singular = False
+    recompute_jac = True
+    for iteration in range(max_iter):
+        if recompute_jac:
+            J = jac(y, p, y_middle, f, f_middle, bc_res)
+            njev += 1
+            try:
+                LU = splu(J)
+            except RuntimeError:
+                singular = True
+                break
+
+            step = LU.solve(res)
+            cost = np.dot(step, step)
+
+        y_step = step[:m * n].reshape((n, m), order='F')
+        p_step = step[m * n:]
+
+        alpha = 1
+        for trial in range(n_trial + 1):
+            y_new = y - alpha * y_step
+            if B is not None:
+                y_new[:, 0] = np.dot(B, y_new[:, 0])
+            p_new = p - alpha * p_step
+
+            col_res, y_middle, f, f_middle = col_fun(y_new, p_new)
+            bc_res = bc(y_new[:, 0], y_new[:, -1], p_new)
+            res = np.hstack((col_res.ravel(order='F'), bc_res))
+
+            step_new = LU.solve(res)
+            cost_new = np.dot(step_new, step_new)
+            if cost_new < (1 - 2 * alpha * sigma) * cost:
+                break
+
+            if trial < n_trial:
+                alpha *= tau
+
+        y = y_new
+        p = p_new
+
+        if njev == max_njev:
+            break
+
+        if (np.all(np.abs(col_res) < tol_r * (1 + np.abs(f_middle))) and
+                np.all(np.abs(bc_res) < bc_tol)):
+            break
+
+        # If the full step was taken, then we are going to continue with
+        # the same Jacobian. This is the approach of BVP_SOLVER.
+        if alpha == 1:
+            step = step_new
+            cost = cost_new
+            recompute_jac = False
+        else:
+            recompute_jac = True
+
+    return y, p, singular
+
+
+def print_iteration_header():
+    print(f"{'Iteration':^15}{'Max residual':^15}{'Max BC residual':^15}"
+          f"{'Total nodes':^15}{'Nodes added':^15}")
+
+
+def print_iteration_progress(iteration, residual, bc_residual, total_nodes,
+                             nodes_added):
+    print(f"{iteration:^15}{residual:^15.2e}{bc_residual:^15.2e}"
+          f"{total_nodes:^15}{nodes_added:^15}")
+
+
+class BVPResult(OptimizeResult):
+    pass
+
+
+TERMINATION_MESSAGES = {
+    0: "The algorithm converged to the desired accuracy.",
+    1: "The maximum number of mesh nodes is exceeded.",
+    2: "A singular Jacobian encountered when solving the collocation system.",
+    3: "The solver was unable to satisfy boundary conditions tolerance on iteration 10."
+}
+
+
+def estimate_rms_residuals(fun, sol, x, h, p, r_middle, f_middle):
+    """Estimate rms values of collocation residuals using Lobatto quadrature.
+
+    The residuals are defined as the difference between the derivatives of
+    our solution and rhs of the ODE system. We use relative residuals, i.e.,
+    normalized by 1 + np.abs(f). RMS values are computed as sqrt from the
+    normalized integrals of the squared relative residuals over each interval.
+    Integrals are estimated using 5-point Lobatto quadrature [1]_, we use the
+    fact that residuals at the mesh nodes are identically zero.
+
+    In [2] they don't normalize integrals by interval lengths, which gives
+    a higher rate of convergence of the residuals by the factor of h**0.5.
+    I chose to do such normalization for an ease of interpretation of return
+    values as RMS estimates.
+
+    Returns
+    -------
+    rms_res : ndarray, shape (m - 1,)
+        Estimated rms values of the relative residuals over each interval.
+
+    References
+    ----------
+    .. [1] http://mathworld.wolfram.com/LobattoQuadrature.html
+    .. [2] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
+       Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
+       Number 3, pp. 299-316, 2001.
+    """
+    x_middle = x[:-1] + 0.5 * h
+    s = 0.5 * h * (3/7)**0.5
+    x1 = x_middle + s
+    x2 = x_middle - s
+    y1 = sol(x1)
+    y2 = sol(x2)
+    y1_prime = sol(x1, 1)
+    y2_prime = sol(x2, 1)
+    f1 = fun(x1, y1, p)
+    f2 = fun(x2, y2, p)
+    r1 = y1_prime - f1
+    r2 = y2_prime - f2
+
+    r_middle /= 1 + np.abs(f_middle)
+    r1 /= 1 + np.abs(f1)
+    r2 /= 1 + np.abs(f2)
+
+    r1 = np.sum(np.real(r1 * np.conj(r1)), axis=0)
+    r2 = np.sum(np.real(r2 * np.conj(r2)), axis=0)
+    r_middle = np.sum(np.real(r_middle * np.conj(r_middle)), axis=0)
+
+    return (0.5 * (32 / 45 * r_middle + 49 / 90 * (r1 + r2))) ** 0.5
+
+
+def create_spline(y, yp, x, h):
+    """Create a cubic spline given values and derivatives.
+
+    Formulas for the coefficients are taken from interpolate.CubicSpline.
+
+    Returns
+    -------
+    sol : PPoly
+        Constructed spline as a PPoly instance.
+    """
+    from scipy.interpolate import PPoly
+
+    n, m = y.shape
+    c = np.empty((4, n, m - 1), dtype=y.dtype)
+    slope = (y[:, 1:] - y[:, :-1]) / h
+    t = (yp[:, :-1] + yp[:, 1:] - 2 * slope) / h
+    c[0] = t / h
+    c[1] = (slope - yp[:, :-1]) / h - t
+    c[2] = yp[:, :-1]
+    c[3] = y[:, :-1]
+    c = np.moveaxis(c, 1, 0)
+
+    return PPoly(c, x, extrapolate=True, axis=1)
+
+
+def modify_mesh(x, insert_1, insert_2):
+    """Insert nodes into a mesh.
+
+    Nodes removal logic is not established, its impact on the solver is
+    presumably negligible. So, only insertion is done in this function.
+
+    Parameters
+    ----------
+    x : ndarray, shape (m,)
+        Mesh nodes.
+    insert_1 : ndarray
+        Intervals to each insert 1 new node in the middle.
+    insert_2 : ndarray
+        Intervals to each insert 2 new nodes, such that divide an interval
+        into 3 equal parts.
+
+    Returns
+    -------
+    x_new : ndarray
+        New mesh nodes.
+
+    Notes
+    -----
+    `insert_1` and `insert_2` should not have common values.
+    """
+    # Because np.insert implementation apparently varies with a version of
+    # NumPy, we use a simple and reliable approach with sorting.
+    return np.sort(np.hstack((
+        x,
+        0.5 * (x[insert_1] + x[insert_1 + 1]),
+        (2 * x[insert_2] + x[insert_2 + 1]) / 3,
+        (x[insert_2] + 2 * x[insert_2 + 1]) / 3
+    )))
+
+
+def wrap_functions(fun, bc, fun_jac, bc_jac, k, a, S, D, dtype):
+    """Wrap functions for unified usage in the solver."""
+    if fun_jac is None:
+        fun_jac_wrapped = None
+
+    if bc_jac is None:
+        bc_jac_wrapped = None
+
+    if k == 0:
+        def fun_p(x, y, _):
+            return np.asarray(fun(x, y), dtype)
+
+        def bc_wrapped(ya, yb, _):
+            return np.asarray(bc(ya, yb), dtype)
+
+        if fun_jac is not None:
+            def fun_jac_p(x, y, _):
+                return np.asarray(fun_jac(x, y), dtype), None
+
+        if bc_jac is not None:
+            def bc_jac_wrapped(ya, yb, _):
+                dbc_dya, dbc_dyb = bc_jac(ya, yb)
+                return (np.asarray(dbc_dya, dtype),
+                        np.asarray(dbc_dyb, dtype), None)
+    else:
+        def fun_p(x, y, p):
+            return np.asarray(fun(x, y, p), dtype)
+
+        def bc_wrapped(x, y, p):
+            return np.asarray(bc(x, y, p), dtype)
+
+        if fun_jac is not None:
+            def fun_jac_p(x, y, p):
+                df_dy, df_dp = fun_jac(x, y, p)
+                return np.asarray(df_dy, dtype), np.asarray(df_dp, dtype)
+
+        if bc_jac is not None:
+            def bc_jac_wrapped(ya, yb, p):
+                dbc_dya, dbc_dyb, dbc_dp = bc_jac(ya, yb, p)
+                return (np.asarray(dbc_dya, dtype), np.asarray(dbc_dyb, dtype),
+                        np.asarray(dbc_dp, dtype))
+
+    if S is None:
+        fun_wrapped = fun_p
+    else:
+        def fun_wrapped(x, y, p):
+            f = fun_p(x, y, p)
+            if x[0] == a:
+                f[:, 0] = np.dot(D, f[:, 0])
+                f[:, 1:] += np.dot(S, y[:, 1:]) / (x[1:] - a)
+            else:
+                f += np.dot(S, y) / (x - a)
+            return f
+
+    if fun_jac is not None:
+        if S is None:
+            fun_jac_wrapped = fun_jac_p
+        else:
+            Sr = S[:, :, np.newaxis]
+
+            def fun_jac_wrapped(x, y, p):
+                df_dy, df_dp = fun_jac_p(x, y, p)
+                if x[0] == a:
+                    df_dy[:, :, 0] = np.dot(D, df_dy[:, :, 0])
+                    df_dy[:, :, 1:] += Sr / (x[1:] - a)
+                else:
+                    df_dy += Sr / (x - a)
+
+                return df_dy, df_dp
+
+    return fun_wrapped, bc_wrapped, fun_jac_wrapped, bc_jac_wrapped
+
+
+def solve_bvp(fun, bc, x, y, p=None, S=None, fun_jac=None, bc_jac=None,
+              tol=1e-3, max_nodes=1000, verbose=0, bc_tol=None):
+    """Solve a boundary value problem for a system of ODEs.
+
+    This function numerically solves a first order system of ODEs subject to
+    two-point boundary conditions::
+
+        dy / dx = f(x, y, p) + S * y / (x - a), a <= x <= b
+        bc(y(a), y(b), p) = 0
+
+    Here x is a 1-D independent variable, y(x) is an n-D
+    vector-valued function and p is a k-D vector of unknown
+    parameters which is to be found along with y(x). For the problem to be
+    determined, there must be n + k boundary conditions, i.e., bc must be an
+    (n + k)-D function.
+
+    The last singular term on the right-hand side of the system is optional.
+    It is defined by an n-by-n matrix S, such that the solution must satisfy
+    S y(a) = 0. This condition will be forced during iterations, so it must not
+    contradict boundary conditions. See [2]_ for the explanation how this term
+    is handled when solving BVPs numerically.
+
+    Problems in a complex domain can be solved as well. In this case, y and p
+    are considered to be complex, and f and bc are assumed to be complex-valued
+    functions, but x stays real. Note that f and bc must be complex
+    differentiable (satisfy Cauchy-Riemann equations [4]_), otherwise you
+    should rewrite your problem for real and imaginary parts separately. To
+    solve a problem in a complex domain, pass an initial guess for y with a
+    complex data type (see below).
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system. The calling signature is ``fun(x, y)``,
+        or ``fun(x, y, p)`` if parameters are present. All arguments are
+        ndarray: ``x`` with shape (m,), ``y`` with shape (n, m), meaning that
+        ``y[:, i]`` corresponds to ``x[i]``, and ``p`` with shape (k,). The
+        return value must be an array with shape (n, m) and with the same
+        layout as ``y``.
+    bc : callable
+        Function evaluating residuals of the boundary conditions. The calling
+        signature is ``bc(ya, yb)``, or ``bc(ya, yb, p)`` if parameters are
+        present. All arguments are ndarray: ``ya`` and ``yb`` with shape (n,),
+        and ``p`` with shape (k,). The return value must be an array with
+        shape (n + k,).
+    x : array_like, shape (m,)
+        Initial mesh. Must be a strictly increasing sequence of real numbers
+        with ``x[0]=a`` and ``x[-1]=b``.
+    y : array_like, shape (n, m)
+        Initial guess for the function values at the mesh nodes, ith column
+        corresponds to ``x[i]``. For problems in a complex domain pass `y`
+        with a complex data type (even if the initial guess is purely real).
+    p : array_like with shape (k,) or None, optional
+        Initial guess for the unknown parameters. If None (default), it is
+        assumed that the problem doesn't depend on any parameters.
+    S : array_like with shape (n, n) or None
+        Matrix defining the singular term. If None (default), the problem is
+        solved without the singular term.
+    fun_jac : callable or None, optional
+        Function computing derivatives of f with respect to y and p. The
+        calling signature is ``fun_jac(x, y)``, or ``fun_jac(x, y, p)`` if
+        parameters are present. The return must contain 1 or 2 elements in the
+        following order:
+
+            * df_dy : array_like with shape (n, n, m), where an element
+              (i, j, q) equals to d f_i(x_q, y_q, p) / d (y_q)_j.
+            * df_dp : array_like with shape (n, k, m), where an element
+              (i, j, q) equals to d f_i(x_q, y_q, p) / d p_j.
+
+        Here q numbers nodes at which x and y are defined, whereas i and j
+        number vector components. If the problem is solved without unknown
+        parameters, df_dp should not be returned.
+
+        If `fun_jac` is None (default), the derivatives will be estimated
+        by the forward finite differences.
+    bc_jac : callable or None, optional
+        Function computing derivatives of bc with respect to ya, yb, and p.
+        The calling signature is ``bc_jac(ya, yb)``, or ``bc_jac(ya, yb, p)``
+        if parameters are present. The return must contain 2 or 3 elements in
+        the following order:
+
+            * dbc_dya : array_like with shape (n, n), where an element (i, j)
+              equals to d bc_i(ya, yb, p) / d ya_j.
+            * dbc_dyb : array_like with shape (n, n), where an element (i, j)
+              equals to d bc_i(ya, yb, p) / d yb_j.
+            * dbc_dp : array_like with shape (n, k), where an element (i, j)
+              equals to d bc_i(ya, yb, p) / d p_j.
+
+        If the problem is solved without unknown parameters, dbc_dp should not
+        be returned.
+
+        If `bc_jac` is None (default), the derivatives will be estimated by
+        the forward finite differences.
+    tol : float, optional
+        Desired tolerance of the solution. If we define ``r = y' - f(x, y)``,
+        where y is the found solution, then the solver tries to achieve on each
+        mesh interval ``norm(r / (1 + abs(f)) < tol``, where ``norm`` is
+        estimated in a root mean squared sense (using a numerical quadrature
+        formula). Default is 1e-3.
+    max_nodes : int, optional
+        Maximum allowed number of the mesh nodes. If exceeded, the algorithm
+        terminates. Default is 1000.
+    verbose : {0, 1, 2}, optional
+        Level of algorithm's verbosity:
+
+            * 0 (default) : work silently.
+            * 1 : display a termination report.
+            * 2 : display progress during iterations.
+    bc_tol : float, optional
+        Desired absolute tolerance for the boundary condition residuals: `bc`
+        value should satisfy ``abs(bc) < bc_tol`` component-wise.
+        Equals to `tol` by default. Up to 10 iterations are allowed to achieve this
+        tolerance.
+
+    Returns
+    -------
+    Bunch object with the following fields defined:
+    sol : PPoly
+        Found solution for y as `scipy.interpolate.PPoly` instance, a C1
+        continuous cubic spline.
+    p : ndarray or None, shape (k,)
+        Found parameters. None, if the parameters were not present in the
+        problem.
+    x : ndarray, shape (m,)
+        Nodes of the final mesh.
+    y : ndarray, shape (n, m)
+        Solution values at the mesh nodes.
+    yp : ndarray, shape (n, m)
+        Solution derivatives at the mesh nodes.
+    rms_residuals : ndarray, shape (m - 1,)
+        RMS values of the relative residuals over each mesh interval (see the
+        description of `tol` parameter).
+    niter : int
+        Number of completed iterations.
+    status : int
+        Reason for algorithm termination:
+
+            * 0: The algorithm converged to the desired accuracy.
+            * 1: The maximum number of mesh nodes is exceeded.
+            * 2: A singular Jacobian encountered when solving the collocation
+              system.
+
+    message : string
+        Verbal description of the termination reason.
+    success : bool
+        True if the algorithm converged to the desired accuracy (``status=0``).
+
+    Notes
+    -----
+    This function implements a 4th order collocation algorithm with the
+    control of residuals similar to [1]_. A collocation system is solved
+    by a damped Newton method with an affine-invariant criterion function as
+    described in [3]_.
+
+    Note that in [1]_  integral residuals are defined without normalization
+    by interval lengths. So, their definition is different by a multiplier of
+    h**0.5 (h is an interval length) from the definition used here.
+
+    .. versionadded:: 0.18.0
+
+    References
+    ----------
+    .. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
+           Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
+           Number 3, pp. 299-316, 2001.
+    .. [2] L.F. Shampine, P. H. Muir and H. Xu, "A User-Friendly Fortran BVP
+           Solver", J. Numer. Anal., Ind. Appl. Math. (JNAIAM), Vol. 1, 
+           Number 2, pp. 201-217, 2006.
+    .. [3] U. Ascher, R. Mattheij and R. Russell "Numerical Solution of
+           Boundary Value Problems for Ordinary Differential Equations",
+           Philidelphia, PA: Society for Industrial and Applied Mathematics,
+           1995.
+           :doi:`10.1137/1.9781611971231`
+    .. [4] `Cauchy-Riemann equations
+            `_ on
+            Wikipedia.
+
+    Examples
+    --------
+    In the first example, we solve Bratu's problem::
+
+        y'' + k * exp(y) = 0
+        y(0) = y(1) = 0
+
+    for k = 1.
+
+    We rewrite the equation as a first-order system and implement its
+    right-hand side evaluation::
+
+        y1' = y2
+        y2' = -exp(y1)
+
+    >>> import numpy as np
+    >>> def fun(x, y):
+    ...     return np.vstack((y[1], -np.exp(y[0])))
+
+    Implement evaluation of the boundary condition residuals:
+
+    >>> def bc(ya, yb):
+    ...     return np.array([ya[0], yb[0]])
+
+    Define the initial mesh with 5 nodes:
+
+    >>> x = np.linspace(0, 1, 5)
+
+    This problem is known to have two solutions. To obtain both of them, we
+    use two different initial guesses for y. We denote them by subscripts
+    a and b.
+
+    >>> y_a = np.zeros((2, x.size))
+    >>> y_b = np.zeros((2, x.size))
+    >>> y_b[0] = 3
+
+    Now we are ready to run the solver.
+
+    >>> from scipy.integrate import solve_bvp
+    >>> res_a = solve_bvp(fun, bc, x, y_a)
+    >>> res_b = solve_bvp(fun, bc, x, y_b)
+
+    Let's plot the two found solutions. We take an advantage of having the
+    solution in a spline form to produce a smooth plot.
+
+    >>> x_plot = np.linspace(0, 1, 100)
+    >>> y_plot_a = res_a.sol(x_plot)[0]
+    >>> y_plot_b = res_b.sol(x_plot)[0]
+    >>> import matplotlib.pyplot as plt
+    >>> plt.plot(x_plot, y_plot_a, label='y_a')
+    >>> plt.plot(x_plot, y_plot_b, label='y_b')
+    >>> plt.legend()
+    >>> plt.xlabel("x")
+    >>> plt.ylabel("y")
+    >>> plt.show()
+
+    We see that the two solutions have similar shape, but differ in scale
+    significantly.
+
+    In the second example, we solve a simple Sturm-Liouville problem::
+
+        y'' + k**2 * y = 0
+        y(0) = y(1) = 0
+
+    It is known that a non-trivial solution y = A * sin(k * x) is possible for
+    k = pi * n, where n is an integer. To establish the normalization constant
+    A = 1 we add a boundary condition::
+
+        y'(0) = k
+
+    Again, we rewrite our equation as a first-order system and implement its
+    right-hand side evaluation::
+
+        y1' = y2
+        y2' = -k**2 * y1
+
+    >>> def fun(x, y, p):
+    ...     k = p[0]
+    ...     return np.vstack((y[1], -k**2 * y[0]))
+
+    Note that parameters p are passed as a vector (with one element in our
+    case).
+
+    Implement the boundary conditions:
+
+    >>> def bc(ya, yb, p):
+    ...     k = p[0]
+    ...     return np.array([ya[0], yb[0], ya[1] - k])
+
+    Set up the initial mesh and guess for y. We aim to find the solution for
+    k = 2 * pi, to achieve that we set values of y to approximately follow
+    sin(2 * pi * x):
+
+    >>> x = np.linspace(0, 1, 5)
+    >>> y = np.zeros((2, x.size))
+    >>> y[0, 1] = 1
+    >>> y[0, 3] = -1
+
+    Run the solver with 6 as an initial guess for k.
+
+    >>> sol = solve_bvp(fun, bc, x, y, p=[6])
+
+    We see that the found k is approximately correct:
+
+    >>> sol.p[0]
+    6.28329460046
+
+    And, finally, plot the solution to see the anticipated sinusoid:
+
+    >>> x_plot = np.linspace(0, 1, 100)
+    >>> y_plot = sol.sol(x_plot)[0]
+    >>> plt.plot(x_plot, y_plot)
+    >>> plt.xlabel("x")
+    >>> plt.ylabel("y")
+    >>> plt.show()
+    """
+    x = np.asarray(x, dtype=float)
+    if x.ndim != 1:
+        raise ValueError("`x` must be 1 dimensional.")
+    h = np.diff(x)
+    if np.any(h <= 0):
+        raise ValueError("`x` must be strictly increasing.")
+    a = x[0]
+
+    y = np.asarray(y)
+    if np.issubdtype(y.dtype, np.complexfloating):
+        dtype = complex
+    else:
+        dtype = float
+    y = y.astype(dtype, copy=False)
+
+    if y.ndim != 2:
+        raise ValueError("`y` must be 2 dimensional.")
+    if y.shape[1] != x.shape[0]:
+        raise ValueError(f"`y` is expected to have {x.shape[0]} columns, but actually "
+                         f"has {y.shape[1]}.")
+
+    if p is None:
+        p = np.array([])
+    else:
+        p = np.asarray(p, dtype=dtype)
+    if p.ndim != 1:
+        raise ValueError("`p` must be 1 dimensional.")
+
+    if tol < 100 * EPS:
+        warn(f"`tol` is too low, setting to {100 * EPS:.2e}", stacklevel=2)
+        tol = 100 * EPS
+
+    if verbose not in [0, 1, 2]:
+        raise ValueError("`verbose` must be in [0, 1, 2].")
+
+    n = y.shape[0]
+    k = p.shape[0]
+
+    if S is not None:
+        S = np.asarray(S, dtype=dtype)
+        if S.shape != (n, n):
+            raise ValueError(f"`S` is expected to have shape {(n, n)}, "
+                             f"but actually has {S.shape}")
+
+        # Compute I - S^+ S to impose necessary boundary conditions.
+        B = np.identity(n) - np.dot(pinv(S), S)
+
+        y[:, 0] = np.dot(B, y[:, 0])
+
+        # Compute (I - S)^+ to correct derivatives at x=a.
+        D = pinv(np.identity(n) - S)
+    else:
+        B = None
+        D = None
+
+    if bc_tol is None:
+        bc_tol = tol
+
+    # Maximum number of iterations
+    max_iteration = 10
+
+    fun_wrapped, bc_wrapped, fun_jac_wrapped, bc_jac_wrapped = wrap_functions(
+        fun, bc, fun_jac, bc_jac, k, a, S, D, dtype)
+
+    f = fun_wrapped(x, y, p)
+    if f.shape != y.shape:
+        raise ValueError(f"`fun` return is expected to have shape {y.shape}, "
+                         f"but actually has {f.shape}.")
+
+    bc_res = bc_wrapped(y[:, 0], y[:, -1], p)
+    if bc_res.shape != (n + k,):
+        raise ValueError(f"`bc` return is expected to have shape {(n + k,)}, "
+                         f"but actually has {bc_res.shape}.")
+
+    status = 0
+    iteration = 0
+    if verbose == 2:
+        print_iteration_header()
+
+    while True:
+        m = x.shape[0]
+
+        col_fun, jac_sys = prepare_sys(n, m, k, fun_wrapped, bc_wrapped,
+                                       fun_jac_wrapped, bc_jac_wrapped, x, h)
+        y, p, singular = solve_newton(n, m, h, col_fun, bc_wrapped, jac_sys,
+                                      y, p, B, tol, bc_tol)
+        iteration += 1
+
+        col_res, y_middle, f, f_middle = collocation_fun(fun_wrapped, y,
+                                                         p, x, h)
+        bc_res = bc_wrapped(y[:, 0], y[:, -1], p)
+        max_bc_res = np.max(abs(bc_res))
+
+        # This relation is not trivial, but can be verified.
+        r_middle = 1.5 * col_res / h
+        sol = create_spline(y, f, x, h)
+        rms_res = estimate_rms_residuals(fun_wrapped, sol, x, h, p,
+                                         r_middle, f_middle)
+        max_rms_res = np.max(rms_res)
+
+        if singular:
+            status = 2
+            break
+
+        insert_1, = np.nonzero((rms_res > tol) & (rms_res < 100 * tol))
+        insert_2, = np.nonzero(rms_res >= 100 * tol)
+        nodes_added = insert_1.shape[0] + 2 * insert_2.shape[0]
+
+        if m + nodes_added > max_nodes:
+            status = 1
+            if verbose == 2:
+                nodes_added = f"({nodes_added})"
+                print_iteration_progress(iteration, max_rms_res, max_bc_res,
+                                         m, nodes_added)
+            break
+
+        if verbose == 2:
+            print_iteration_progress(iteration, max_rms_res, max_bc_res, m,
+                                     nodes_added)
+
+        if nodes_added > 0:
+            x = modify_mesh(x, insert_1, insert_2)
+            h = np.diff(x)
+            y = sol(x)
+        elif max_bc_res <= bc_tol:
+            status = 0
+            break
+        elif iteration >= max_iteration:
+            status = 3
+            break
+
+    if verbose > 0:
+        if status == 0:
+            print(f"Solved in {iteration} iterations, number of nodes {x.shape[0]}. \n"
+                  f"Maximum relative residual: {max_rms_res:.2e} \n"
+                  f"Maximum boundary residual: {max_bc_res:.2e}")
+        elif status == 1:
+            print(f"Number of nodes is exceeded after iteration {iteration}. \n"
+                  f"Maximum relative residual: {max_rms_res:.2e} \n"
+                  f"Maximum boundary residual: {max_bc_res:.2e}")
+        elif status == 2:
+            print("Singular Jacobian encountered when solving the collocation "
+                  f"system on iteration {iteration}. \n"
+                  f"Maximum relative residual: {max_rms_res:.2e} \n"
+                  f"Maximum boundary residual: {max_bc_res:.2e}")
+        elif status == 3:
+            print("The solver was unable to satisfy boundary conditions "
+                  f"tolerance on iteration {iteration}. \n"
+                  f"Maximum relative residual: {max_rms_res:.2e} \n"
+                  f"Maximum boundary residual: {max_bc_res:.2e}")
+
+    if p.size == 0:
+        p = None
+
+    return BVPResult(sol=sol, p=p, x=x, y=y, yp=f, rms_residuals=rms_res,
+                     niter=iteration, status=status,
+                     message=TERMINATION_MESSAGES[status], success=status == 0)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_cubature.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_cubature.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad806d6c23738df6b2daa92b9e72b12b70933299
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_cubature.py
@@ -0,0 +1,729 @@
+import math
+import heapq
+import itertools
+
+from dataclasses import dataclass, field
+from types import ModuleType
+from typing import Any, TypeAlias
+
+from scipy._lib._array_api import (
+    array_namespace,
+    xp_size,
+    xp_copy,
+    xp_promote
+)
+from scipy._lib._util import MapWrapper
+
+from scipy.integrate._rules import (
+    ProductNestedFixed,
+    GaussKronrodQuadrature,
+    GenzMalikCubature,
+)
+from scipy.integrate._rules._base import _split_subregion
+
+__all__ = ['cubature']
+
+Array: TypeAlias = Any  # To be changed to an array-api-typing Protocol later
+
+
+@dataclass
+class CubatureRegion:
+    estimate: Array
+    error: Array
+    a: Array
+    b: Array
+    _xp: ModuleType = field(repr=False)
+
+    def __lt__(self, other):
+        # Consider regions with higher error estimates as being "less than" regions with
+        # lower order estimates, so that regions with high error estimates are placed at
+        # the top of the heap.
+
+        this_err = self._xp.max(self._xp.abs(self.error))
+        other_err = self._xp.max(self._xp.abs(other.error))
+
+        return this_err > other_err
+
+
+@dataclass
+class CubatureResult:
+    estimate: Array
+    error: Array
+    status: str
+    regions: list[CubatureRegion]
+    subdivisions: int
+    atol: float
+    rtol: float
+
+
+def cubature(f, a, b, *, rule="gk21", rtol=1e-8, atol=0, max_subdivisions=10000,
+             args=(), workers=1, points=None):
+    r"""
+    Adaptive cubature of multidimensional array-valued function.
+
+    Given an arbitrary integration rule, this function returns an estimate of the
+    integral to the requested tolerance over the region defined by the arrays `a` and
+    `b` specifying the corners of a hypercube.
+
+    Convergence is not guaranteed for all integrals.
+
+    Parameters
+    ----------
+    f : callable
+        Function to integrate. `f` must have the signature::
+
+            f(x : ndarray, *args) -> ndarray
+
+        `f` should accept arrays ``x`` of shape::
+
+            (npoints, ndim)
+
+        and output arrays of shape::
+
+            (npoints, output_dim_1, ..., output_dim_n)
+
+        In this case, `cubature` will return arrays of shape::
+
+            (output_dim_1, ..., output_dim_n)
+    a, b : array_like
+        Lower and upper limits of integration as 1D arrays specifying the left and right
+        endpoints of the intervals being integrated over. Limits can be infinite.
+    rule : str, optional
+        Rule used to estimate the integral. If passing a string, the options are
+        "gauss-kronrod" (21 node), or "genz-malik" (degree 7). If a rule like
+        "gauss-kronrod" is specified for an ``n``-dim integrand, the corresponding
+        Cartesian product rule is used. "gk21", "gk15" are also supported for
+        compatibility with `quad_vec`. See Notes.
+    rtol, atol : float, optional
+        Relative and absolute tolerances. Iterations are performed until the error is
+        estimated to be less than ``atol + rtol * abs(est)``. Here `rtol` controls
+        relative accuracy (number of correct digits), while `atol` controls absolute
+        accuracy (number of correct decimal places). To achieve the desired `rtol`, set
+        `atol` to be smaller than the smallest value that can be expected from
+        ``rtol * abs(y)`` so that `rtol` dominates the allowable error. If `atol` is
+        larger than ``rtol * abs(y)`` the number of correct digits is not guaranteed.
+        Conversely, to achieve the desired `atol`, set `rtol` such that
+        ``rtol * abs(y)`` is always smaller than `atol`. Default values are 1e-8 for
+        `rtol` and 0 for `atol`.
+    max_subdivisions : int, optional
+        Upper bound on the number of subdivisions to perform. Default is 10,000.
+    args : tuple, optional
+        Additional positional args passed to `f`, if any.
+    workers : int or map-like callable, optional
+        If `workers` is an integer, part of the computation is done in parallel
+        subdivided to this many tasks (using :class:`python:multiprocessing.pool.Pool`).
+        Supply `-1` to use all cores available to the Process. Alternatively, supply a
+        map-like callable, such as :meth:`python:multiprocessing.pool.Pool.map` for
+        evaluating the population in parallel. This evaluation is carried out as
+        ``workers(func, iterable)``.
+    points : list of array_like, optional
+        List of points to avoid evaluating `f` at, under the condition that the rule
+        being used does not evaluate `f` on the boundary of a region (which is the
+        case for all Genz-Malik and Gauss-Kronrod rules). This can be useful if `f` has
+        a singularity at the specified point. This should be a list of array-likes where
+        each element has length ``ndim``. Default is empty. See Examples.
+
+    Returns
+    -------
+    res : object
+        Object containing the results of the estimation. It has the following
+        attributes:
+
+        estimate : ndarray
+            Estimate of the value of the integral over the overall region specified.
+        error : ndarray
+            Estimate of the error of the approximation over the overall region
+            specified.
+        status : str
+            Whether the estimation was successful. Can be either: "converged",
+            "not_converged".
+        subdivisions : int
+            Number of subdivisions performed.
+        atol, rtol : float
+            Requested tolerances for the approximation.
+        regions: list of object
+            List of objects containing the estimates of the integral over smaller
+            regions of the domain.
+
+        Each object in ``regions`` has the following attributes:
+
+        a, b : ndarray
+            Points describing the corners of the region. If the original integral
+            contained infinite limits or was over a region described by `region`,
+            then `a` and `b` are in the transformed coordinates.
+        estimate : ndarray
+            Estimate of the value of the integral over this region.
+        error : ndarray
+            Estimate of the error of the approximation over this region.
+
+    Notes
+    -----
+    The algorithm uses a similar algorithm to `quad_vec`, which itself is based on the
+    implementation of QUADPACK's DQAG* algorithms, implementing global error control and
+    adaptive subdivision.
+
+    The source of the nodes and weights used for Gauss-Kronrod quadrature can be found
+    in [1]_, and the algorithm for calculating the nodes and weights in Genz-Malik
+    cubature can be found in [2]_.
+
+    The rules currently supported via the `rule` argument are:
+
+    - ``"gauss-kronrod"``, 21-node Gauss-Kronrod
+    - ``"genz-malik"``, n-node Genz-Malik
+
+    If using Gauss-Kronrod for an ``n``-dim integrand where ``n > 2``, then the
+    corresponding Cartesian product rule will be found by taking the Cartesian product
+    of the nodes in the 1D case. This means that the number of nodes scales
+    exponentially as ``21^n`` in the Gauss-Kronrod case, which may be problematic in a
+    moderate number of dimensions.
+
+    Genz-Malik is typically less accurate than Gauss-Kronrod but has much fewer nodes,
+    so in this situation using "genz-malik" might be preferable.
+
+    Infinite limits are handled with an appropriate variable transformation. Assuming
+    ``a = [a_1, ..., a_n]`` and ``b = [b_1, ..., b_n]``:
+
+    If :math:`a_i = -\infty` and :math:`b_i = \infty`, the i-th integration variable
+    will use the transformation :math:`x = \frac{1-|t|}{t}` and :math:`t \in (-1, 1)`.
+
+    If :math:`a_i \ne \pm\infty` and :math:`b_i = \infty`, the i-th integration variable
+    will use the transformation :math:`x = a_i + \frac{1-t}{t}` and
+    :math:`t \in (0, 1)`.
+
+    If :math:`a_i = -\infty` and :math:`b_i \ne \pm\infty`, the i-th integration
+    variable will use the transformation :math:`x = b_i - \frac{1-t}{t}` and
+    :math:`t \in (0, 1)`.
+
+    References
+    ----------
+    .. [1] R. Piessens, E. de Doncker, Quadpack: A Subroutine Package for Automatic
+        Integration, files: dqk21.f, dqk15.f (1983).
+
+    .. [2] A.C. Genz, A.A. Malik, Remarks on algorithm 006: An adaptive algorithm for
+        numerical integration over an N-dimensional rectangular region, Journal of
+        Computational and Applied Mathematics, Volume 6, Issue 4, 1980, Pages 295-302,
+        ISSN 0377-0427
+        :doi:`10.1016/0771-050X(80)90039-X`
+
+    Examples
+    --------
+    **1D integral with vector output**:
+
+    .. math::
+
+        \int^1_0 \mathbf f(x) \text dx
+
+    Where ``f(x) = x^n`` and ``n = np.arange(10)`` is a vector. Since no rule is
+    specified, the default "gk21" is used, which corresponds to Gauss-Kronrod
+    integration with 21 nodes.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import cubature
+    >>> def f(x, n):
+    ...    # Make sure x and n are broadcastable
+    ...    return x[:, np.newaxis]**n[np.newaxis, :]
+    >>> res = cubature(
+    ...     f,
+    ...     a=[0],
+    ...     b=[1],
+    ...     args=(np.arange(10),),
+    ... )
+    >>> res.estimate
+     array([1.        , 0.5       , 0.33333333, 0.25      , 0.2       ,
+            0.16666667, 0.14285714, 0.125     , 0.11111111, 0.1       ])
+
+    **7D integral with arbitrary-shaped array output**::
+
+        f(x) = cos(2*pi*r + alphas @ x)
+
+    for some ``r`` and ``alphas``, and the integral is performed over the unit
+    hybercube, :math:`[0, 1]^7`. Since the integral is in a moderate number of
+    dimensions, "genz-malik" is used rather than the default "gauss-kronrod" to
+    avoid constructing a product rule with :math:`21^7 \approx 2 \times 10^9` nodes.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import cubature
+    >>> def f(x, r, alphas):
+    ...     # f(x) = cos(2*pi*r + alphas @ x)
+    ...     # Need to allow r and alphas to be arbitrary shape
+    ...     npoints, ndim = x.shape[0], x.shape[-1]
+    ...     alphas = alphas[np.newaxis, ...]
+    ...     x = x.reshape(npoints, *([1]*(len(alphas.shape) - 1)), ndim)
+    ...     return np.cos(2*np.pi*r + np.sum(alphas * x, axis=-1))
+    >>> rng = np.random.default_rng()
+    >>> r, alphas = rng.random((2, 3)), rng.random((2, 3, 7))
+    >>> res = cubature(
+    ...     f=f,
+    ...     a=np.array([0, 0, 0, 0, 0, 0, 0]),
+    ...     b=np.array([1, 1, 1, 1, 1, 1, 1]),
+    ...     rtol=1e-5,
+    ...     rule="genz-malik",
+    ...     args=(r, alphas),
+    ... )
+    >>> res.estimate
+     array([[-0.79812452,  0.35246913, -0.52273628],
+            [ 0.88392779,  0.59139899,  0.41895111]])
+
+    **Parallel computation with** `workers`:
+
+    >>> from concurrent.futures import ThreadPoolExecutor
+    >>> with ThreadPoolExecutor() as executor:
+    ...     res = cubature(
+    ...         f=f,
+    ...         a=np.array([0, 0, 0, 0, 0, 0, 0]),
+    ...         b=np.array([1, 1, 1, 1, 1, 1, 1]),
+    ...         rtol=1e-5,
+    ...         rule="genz-malik",
+    ...         args=(r, alphas),
+    ...         workers=executor.map,
+    ...      )
+    >>> res.estimate
+     array([[-0.79812452,  0.35246913, -0.52273628],
+            [ 0.88392779,  0.59139899,  0.41895111]])
+
+    **2D integral with infinite limits**:
+
+    .. math::
+
+        \int^{ \infty }_{ -\infty }
+        \int^{ \infty }_{ -\infty }
+            e^{-x^2-y^2}
+        \text dy
+        \text dx
+
+    >>> def gaussian(x):
+    ...     return np.exp(-np.sum(x**2, axis=-1))
+    >>> res = cubature(gaussian, [-np.inf, -np.inf], [np.inf, np.inf])
+    >>> res.estimate
+     3.1415926
+
+    **1D integral with singularities avoided using** `points`:
+
+    .. math::
+
+        \int^{ 1 }_{ -1 }
+          \frac{\sin(x)}{x}
+        \text dx
+
+    It is necessary to use the `points` parameter to avoid evaluating `f` at the origin.
+
+    >>> def sinc(x):
+    ...     return np.sin(x)/x
+    >>> res = cubature(sinc, [-1], [1], points=[[0]])
+    >>> res.estimate
+     1.8921661
+    """
+
+    # It is also possible to use a custom rule, but this is not yet part of the public
+    # API. An example of this can be found in the class scipy.integrate._rules.Rule.
+
+    xp = array_namespace(a, b)
+    max_subdivisions = float("inf") if max_subdivisions is None else max_subdivisions
+    points = [] if points is None else points
+
+    # Convert a and b to arrays and convert each point in points to an array, promoting
+    # each to a common floating dtype.
+    a, b, *points = xp_promote(a, b, *points, broadcast=True, force_floating=True,
+                               xp=xp)
+    result_dtype = a.dtype
+
+    if xp_size(a) == 0 or xp_size(b) == 0:
+        raise ValueError("`a` and `b` must be nonempty")
+
+    if a.ndim != 1 or b.ndim != 1:
+        raise ValueError("`a` and `b` must be 1D arrays")
+
+    # If the rule is a string, convert to a corresponding product rule
+    if isinstance(rule, str):
+        ndim = xp_size(a)
+
+        if rule == "genz-malik":
+            rule = GenzMalikCubature(ndim, xp=xp)
+        else:
+            quadratues = {
+                "gauss-kronrod": GaussKronrodQuadrature(21, xp=xp),
+
+                # Also allow names quad_vec uses:
+                "gk21": GaussKronrodQuadrature(21, xp=xp),
+                "gk15": GaussKronrodQuadrature(15, xp=xp),
+            }
+
+            base_rule = quadratues.get(rule)
+
+            if base_rule is None:
+                raise ValueError(f"unknown rule {rule}")
+
+            rule = ProductNestedFixed([base_rule] * ndim)
+
+    # If any of limits are the wrong way around (a > b), flip them and keep track of
+    # the sign.
+    sign = (-1) ** xp.sum(xp.astype(a > b, xp.int8), dtype=result_dtype)
+
+    a_flipped = xp.min(xp.stack([a, b]), axis=0)
+    b_flipped = xp.max(xp.stack([a, b]), axis=0)
+
+    a, b = a_flipped, b_flipped
+
+    # If any of the limits are infinite, apply a transformation
+    if xp.any(xp.isinf(a)) or xp.any(xp.isinf(b)):
+        f = _InfiniteLimitsTransform(f, a, b, xp=xp)
+        a, b = f.transformed_limits
+
+        # Map points from the original coordinates to the new transformed coordinates.
+        #
+        # `points` is a list of arrays of shape (ndim,), but transformations are applied
+        # to arrays of shape (npoints, ndim).
+        #
+        # It is not possible to combine all the points into one array and then apply
+        # f.inv to all of them at once since `points` needs to remain iterable.
+        # Instead, each point is reshaped to an array of shape (1, ndim), `f.inv` is
+        # applied, and then each is reshaped back to (ndim,).
+        points = [xp.reshape(point, (1, -1)) for point in points]
+        points = [f.inv(point) for point in points]
+        points = [xp.reshape(point, (-1,)) for point in points]
+
+        # Include any problematic points introduced by the transformation
+        points.extend(f.points)
+
+    # If any problematic points are specified, divide the initial region so that these
+    # points lie on the edge of a subregion.
+    #
+    # This means ``f`` won't be evaluated there if the rule being used has no evaluation
+    # points on the boundary.
+    if len(points) == 0:
+        initial_regions = [(a, b)]
+    else:
+        initial_regions = _split_region_at_points(a, b, points, xp)
+
+    regions = []
+    est = 0.0
+    err = 0.0
+
+    for a_k, b_k in initial_regions:
+        est_k = rule.estimate(f, a_k, b_k, args)
+        err_k = rule.estimate_error(f, a_k, b_k, args)
+        regions.append(CubatureRegion(est_k, err_k, a_k, b_k, xp))
+
+        est += est_k
+        err += err_k
+
+    subdivisions = 0
+    success = True
+
+    with MapWrapper(workers) as mapwrapper:
+        while xp.any(err > atol + rtol * xp.abs(est)):
+            # region_k is the region with highest estimated error
+            region_k = heapq.heappop(regions)
+
+            est_k = region_k.estimate
+            err_k = region_k.error
+
+            a_k, b_k = region_k.a, region_k.b
+
+            # Subtract the estimate of the integral and its error over this region from
+            # the current global estimates, since these will be refined in the loop over
+            # all subregions.
+            est -= est_k
+            err -= err_k
+
+            # Find all 2^ndim subregions formed by splitting region_k along each axis,
+            # e.g. for 1D integrals this splits an estimate over an interval into an
+            # estimate over two subintervals, for 3D integrals this splits an estimate
+            # over a cube into 8 subcubes.
+            #
+            # For each of the new subregions, calculate an estimate for the integral and
+            # the error there, and push these regions onto the heap for potential
+            # further subdividing.
+
+            executor_args = zip(
+                itertools.repeat(f),
+                itertools.repeat(rule),
+                itertools.repeat(args),
+                _split_subregion(a_k, b_k, xp),
+            )
+
+            for subdivision_result in mapwrapper(_process_subregion, executor_args):
+                a_k_sub, b_k_sub, est_sub, err_sub = subdivision_result
+
+                est += est_sub
+                err += err_sub
+
+                new_region = CubatureRegion(est_sub, err_sub, a_k_sub, b_k_sub, xp)
+
+                heapq.heappush(regions, new_region)
+
+            subdivisions += 1
+
+            if subdivisions >= max_subdivisions:
+                success = False
+                break
+
+        status = "converged" if success else "not_converged"
+
+        # Apply sign change to handle any limits which were initially flipped.
+        est = sign * est
+
+        return CubatureResult(
+            estimate=est,
+            error=err,
+            status=status,
+            subdivisions=subdivisions,
+            regions=regions,
+            atol=atol,
+            rtol=rtol,
+        )
+
+
+def _process_subregion(data):
+    f, rule, args, coord = data
+    a_k_sub, b_k_sub = coord
+
+    est_sub = rule.estimate(f, a_k_sub, b_k_sub, args)
+    err_sub = rule.estimate_error(f, a_k_sub, b_k_sub, args)
+
+    return a_k_sub, b_k_sub, est_sub, err_sub
+
+
+def _is_strictly_in_region(a, b, point, xp):
+    if xp.all(point == a) or xp.all(point == b):
+        return False
+
+    return xp.all(a <= point) and xp.all(point <= b)
+
+
+def _split_region_at_points(a, b, points, xp):
+    """
+    Given the integration limits `a` and `b` describing a rectangular region and a list
+    of `points`, find the list of ``[(a_1, b_1), ..., (a_l, b_l)]`` which breaks up the
+    initial region into smaller subregion such that no `points` lie strictly inside
+    any of the subregions.
+    """
+
+    regions = [(a, b)]
+
+    for point in points:
+        if xp.any(xp.isinf(point)):
+            # If a point is specified at infinity, ignore.
+            #
+            # This case occurs when points are given by the user to avoid, but after
+            # applying a transformation, they are removed.
+            continue
+
+        new_subregions = []
+
+        for a_k, b_k in regions:
+            if _is_strictly_in_region(a_k, b_k, point, xp):
+                subregions = _split_subregion(a_k, b_k, xp, point)
+
+                for left, right in subregions:
+                    # Skip any zero-width regions.
+                    if xp.any(left == right):
+                        continue
+                    else:
+                        new_subregions.append((left, right))
+
+                new_subregions.extend(subregions)
+
+            else:
+                new_subregions.append((a_k, b_k))
+
+        regions = new_subregions
+
+    return regions
+
+
+class _VariableTransform:
+    """
+    A transformation that can be applied to an integral.
+    """
+
+    @property
+    def transformed_limits(self):
+        """
+        New limits of integration after applying the transformation.
+        """
+
+        raise NotImplementedError
+
+    @property
+    def points(self):
+        """
+        Any problematic points introduced by the transformation.
+
+        These should be specified as points where ``_VariableTransform(f)(self, point)``
+        would be problematic.
+
+        For example, if the transformation ``x = 1/((1-t)(1+t))`` is applied to a
+        univariate integral, then points should return ``[ [1], [-1] ]``.
+        """
+
+        return []
+
+    def inv(self, x):
+        """
+        Map points ``x`` to ``t`` such that if ``f`` is the original function and ``g``
+        is the function after the transformation is applied, then::
+
+            f(x) = g(self.inv(x))
+        """
+
+        raise NotImplementedError
+
+    def __call__(self, t, *args, **kwargs):
+        """
+        Apply the transformation to ``f`` and multiply by the Jacobian determinant.
+        This should be the new integrand after the transformation has been applied so
+        that the following is satisfied::
+
+            f_transformed = _VariableTransform(f)
+
+            cubature(f, a, b) == cubature(
+                f_transformed,
+                *f_transformed.transformed_limits(a, b),
+            )
+        """
+
+        raise NotImplementedError
+
+
+class _InfiniteLimitsTransform(_VariableTransform):
+    r"""
+    Transformation for handling infinite limits.
+
+    Assuming ``a = [a_1, ..., a_n]`` and ``b = [b_1, ..., b_n]``:
+
+    If :math:`a_i = -\infty` and :math:`b_i = \infty`, the i-th integration variable
+    will use the transformation :math:`x = \frac{1-|t|}{t}` and :math:`t \in (-1, 1)`.
+
+    If :math:`a_i \ne \pm\infty` and :math:`b_i = \infty`, the i-th integration variable
+    will use the transformation :math:`x = a_i + \frac{1-t}{t}` and
+    :math:`t \in (0, 1)`.
+
+    If :math:`a_i = -\infty` and :math:`b_i \ne \pm\infty`, the i-th integration
+    variable will use the transformation :math:`x = b_i - \frac{1-t}{t}` and
+    :math:`t \in (0, 1)`.
+    """
+
+    def __init__(self, f, a, b, xp):
+        self._xp = xp
+
+        self._f = f
+        self._orig_a = a
+        self._orig_b = b
+
+        # (-oo, oo) will be mapped to (-1, 1).
+        self._double_inf_pos = (a == -math.inf) & (b == math.inf)
+
+        # (start, oo) will be mapped to (0, 1).
+        start_inf_mask = (a != -math.inf) & (b == math.inf)
+
+        # (-oo, end) will be mapped to (0, 1).
+        inf_end_mask = (a == -math.inf) & (b != math.inf)
+
+        # This is handled by making the transformation t = -x and reducing it to
+        # the other semi-infinite case.
+        self._semi_inf_pos = start_inf_mask | inf_end_mask
+
+        # Since we flip the limits, we don't need to separately multiply the
+        # integrand by -1.
+        self._orig_a[inf_end_mask] = -b[inf_end_mask]
+        self._orig_b[inf_end_mask] = -a[inf_end_mask]
+
+        self._num_inf = self._xp.sum(
+            self._xp.astype(self._double_inf_pos | self._semi_inf_pos, self._xp.int64),
+        ).__int__()
+
+    @property
+    def transformed_limits(self):
+        a = xp_copy(self._orig_a)
+        b = xp_copy(self._orig_b)
+
+        a[self._double_inf_pos] = -1
+        b[self._double_inf_pos] = 1
+
+        a[self._semi_inf_pos] = 0
+        b[self._semi_inf_pos] = 1
+
+        return a, b
+
+    @property
+    def points(self):
+        # If there are infinite limits, then the origin becomes a problematic point
+        # due to a division by zero there.
+
+        # If the function using this class only wraps f when a and b contain infinite
+        # limits, this condition will always be met (as is the case with cubature).
+        #
+        # If a and b do not contain infinite limits but f is still wrapped with this
+        # class, then without this condition the initial region of integration will
+        # be split around the origin unnecessarily.
+        if self._num_inf != 0:
+            return [self._xp.zeros(self._orig_a.shape)]
+        else:
+            return []
+
+    def inv(self, x):
+        t = xp_copy(x)
+        npoints = x.shape[0]
+
+        double_inf_mask = self._xp.tile(
+            self._double_inf_pos[self._xp.newaxis, :],
+            (npoints, 1),
+        )
+
+        semi_inf_mask = self._xp.tile(
+            self._semi_inf_pos[self._xp.newaxis, :],
+            (npoints, 1),
+        )
+
+        # If any components of x are 0, then this component will be mapped to infinity
+        # under the transformation used for doubly-infinite limits.
+        #
+        # Handle the zero values and non-zero values separately to avoid division by
+        # zero.
+        zero_mask = x[double_inf_mask] == 0
+        non_zero_mask = double_inf_mask & ~zero_mask
+        t[zero_mask] = math.inf
+        t[non_zero_mask] = 1/(x[non_zero_mask] + self._xp.sign(x[non_zero_mask]))
+
+        start = self._xp.tile(self._orig_a[self._semi_inf_pos], (npoints,))
+        t[semi_inf_mask] = 1/(x[semi_inf_mask] - start + 1)
+
+        return t
+
+    def __call__(self, t, *args, **kwargs):
+        x = xp_copy(t)
+        npoints = t.shape[0]
+
+        double_inf_mask = self._xp.tile(
+            self._double_inf_pos[self._xp.newaxis, :],
+            (npoints, 1),
+        )
+
+        semi_inf_mask = self._xp.tile(
+            self._semi_inf_pos[self._xp.newaxis, :],
+            (npoints, 1),
+        )
+
+        # For (-oo, oo) -> (-1, 1), use the transformation x = (1-|t|)/t.
+        x[double_inf_mask] = (
+            (1 - self._xp.abs(t[double_inf_mask])) / t[double_inf_mask]
+        )
+
+        start = self._xp.tile(self._orig_a[self._semi_inf_pos], (npoints,))
+
+        # For (start, oo) -> (0, 1), use the transformation x = start + (1-t)/t.
+        x[semi_inf_mask] = start + (1 - t[semi_inf_mask]) / t[semi_inf_mask]
+
+        jacobian_det = 1/self._xp.prod(
+            self._xp.reshape(
+                t[semi_inf_mask | double_inf_mask]**2,
+                (-1, self._num_inf),
+            ),
+            axis=-1,
+        )
+
+        f_x = self._f(x, *args, **kwargs)
+        jacobian_det = self._xp.reshape(jacobian_det, (-1, *([1]*(len(f_x.shape) - 1))))
+
+        return f_x * jacobian_det
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_dop.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_dop.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..a4ae999cc97cc5d4e52d8ea00b85b8cf6cf68b1c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_dop.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:32eaad3e41964ee69acfbf75c53ba1d7fa187b7f32f66db846d9130d677d29a9
+size 121089
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_lebedev.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_lebedev.py
new file mode 100644
index 0000000000000000000000000000000000000000..da200972f9d475162f84294ed335149dc86fe94b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_lebedev.py
@@ -0,0 +1,5450 @@
+# getLebedevSphere
+# Copyright (c) 2010, Robert Parrish
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+#     * Redistributions of source code must retain the above copyright
+#       notice, this list of conditions and the following disclaimer.
+#     * Redistributions in binary form must reproduce the above copyright
+#       notice, this list of conditions and the following disclaimer in
+#       the documentation and/or other materials provided with the distribution
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+# Brainlessly translated to Python
+
+import numpy as np
+from numpy import pi, zeros, sqrt
+
+
+__all__ = ['lebedev_rule']
+
+
+def get_lebedev_sphere(degree):
+    # getLebedevSphere
+    # @author Rob Parrish, The Sherrill Group, CCMST Georgia Tech
+    # @email robparrish@gmail.com
+    # @date 03/24/2010
+    #
+    # @description - function to compute normalized points and weights
+    # for Lebedev quadratures on the surface of the unit sphere at double precision.
+    # **********Relative error is generally expected to be ~2.0E-14 [1]********
+    # Lebedev quadratures are superbly accurate and efficient quadrature rules for
+    # approximating integrals of the form $v = \iint_{4\pi}  f(\Omega) \ \ud
+    # \Omega$, where $\Omega is the solid angle on the surface of the unit
+    # sphere. Lebedev quadratures integrate all spherical harmonics up to $l =
+    # order$, where $degree \approx order(order+1)/3$. These grids may be easily
+    # combined with radial quadratures to provide robust cubature formulae. For
+    # example, see 'A. Becke, 1988c, J. Chem. Phys., 88(4), pp. 2547' (The first
+    # paper on tractable molecular Density Functional Theory methods, of which
+    # Lebedev grids and numerical cubature are an intrinsic part).
+    #
+    # @param degree - positive integer specifying number of points in the
+    # requested quadrature. Allowed values are (degree -> order):
+    # degree: { 6, 14, 26, 38, 50, 74, 86, 110, 146, 170, 194, 230, 266, 302,
+    #   350, 434, 590, 770, 974, 1202, 1454, 1730, 2030, 2354, 2702, 3074,
+    #   3470, 3890, 4334, 4802, 5294, 5810 }
+    # order: {3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,35,41,47,53,59,65,71,77,
+    #   83,89,95,101,107,113,119,125,131}
+    #
+    #
+    # @return leb_tmp - struct containing fields:
+    #   x - x values of quadrature, constrained to unit sphere
+    #   y - y values of quadrature, constrained to unit sphere
+    #   z - z values of quadrature, constrained to unit sphere
+    #   w - quadrature weights, normalized to $4\pi$.
+    #
+    # @example: $\int_S x^2+y^2-z^2 \ud \Omega = 4.188790204786399$
+    #   f = @(x,y,z) x.^2+y.^2-z.^2
+    #   leb = getLebedevSphere(590)
+    #   v = f(leb.x,leb.y,leb.z)
+    #   int = sum(v.*leb.w)
+    #
+    # @citation - Translated from a Fortran code kindly provided by Christoph van
+    # Wuellen (Ruhr-Universitaet, Bochum, Germany), which in turn came from the
+    # original C routines coded by Dmitri Laikov (Moscow State University,
+    # Moscow, Russia). The MATLAB implementation of this code is designed for
+    # benchmarking of new DFT integration techniques to be implemented in the
+    # open source Psi4 ab initio quantum chemistry program.
+    #
+    # As per Professor Wuellen's request, any papers published using this code
+    # or its derivatives are requested to include the following citation:
+    #
+    # [1] V.I. Lebedev, and D.N. Laikov
+    #    "A quadrature formula for the sphere of the 131st
+    #     algebraic order of accuracy"
+    #    Doklady Mathematics, Vol. 59, No. 3, 1999, pp. 477-481.
+
+    class Leb:
+        x, y, z, w = None, None, None, None
+
+    leb_tmp = Leb()
+
+    leb_tmp.x = zeros(degree)
+    leb_tmp.y = zeros(degree)
+    leb_tmp.z = zeros(degree)
+    leb_tmp.w = zeros(degree)
+
+    start = 0
+    a = 0.0
+    b = 0.0
+
+    match degree:
+
+        case 6:
+
+            v = 0.1666666666666667E+0
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+
+        case 14:
+
+            v = 0.6666666666666667E-1
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.7500000000000000E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+
+        case 26:
+
+            v = 0.4761904761904762E-1
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3809523809523810E-1
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.3214285714285714E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+
+        case 38:
+
+            v = 0.9523809523809524E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3214285714285714E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.4597008433809831E+0
+            v = 0.2857142857142857E-1
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+
+        case 50:
+
+            v = 0.1269841269841270E-1
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2257495590828924E-1
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.2109375000000000E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.3015113445777636E+0
+            v = 0.2017333553791887E-1
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+
+        case 74:
+
+            v = 0.5130671797338464E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1660406956574204E-1
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = -0.2958603896103896E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.4803844614152614E+0
+            v = 0.2657620708215946E-1
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3207726489807764E+0
+            v = 0.1652217099371571E-1
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+
+        case 86:
+
+            v = 0.1154401154401154E-1
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1194390908585628E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.3696028464541502E+0
+            v = 0.1111055571060340E-1
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6943540066026664E+0
+            v = 0.1187650129453714E-1
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3742430390903412E+0
+            v = 0.1181230374690448E-1
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+
+        case 110:
+
+            v = 0.3828270494937162E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.9793737512487512E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1851156353447362E+0
+            v = 0.8211737283191111E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6904210483822922E+0
+            v = 0.9942814891178103E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3956894730559419E+0
+            v = 0.9595471336070963E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4783690288121502E+0
+            v = 0.9694996361663028E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+
+        case 146:
+
+            v = 0.5996313688621381E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.7372999718620756E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.7210515360144488E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.6764410400114264E+0
+            v = 0.7116355493117555E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4174961227965453E+0
+            v = 0.6753829486314477E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1574676672039082E+0
+            v = 0.7574394159054034E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1403553811713183E+0
+            b = 0.4493328323269557E+0
+            v = 0.6991087353303262E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 170:
+
+            v = 0.5544842902037365E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.6071332770670752E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.6383674773515093E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2551252621114134E+0
+            v = 0.5183387587747790E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6743601460362766E+0
+            v = 0.6317929009813725E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4318910696719410E+0
+            v = 0.6201670006589077E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2613931360335988E+0
+            v = 0.5477143385137348E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4990453161796037E+0
+            b = 0.1446630744325115E+0
+            v = 0.5968383987681156E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 194:
+
+            v = 0.1782340447244611E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.5716905949977102E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.5573383178848738E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.6712973442695226E+0
+            v = 0.5608704082587997E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2892465627575439E+0
+            v = 0.5158237711805383E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4446933178717437E+0
+            v = 0.5518771467273614E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1299335447650067E+0
+            v = 0.4106777028169394E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3457702197611283E+0
+            v = 0.5051846064614808E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1590417105383530E+0
+            b = 0.8360360154824589E+0
+            v = 0.5530248916233094E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 230:
+
+            v = -0.5522639919727325E-1
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.4450274607445226E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.4492044687397611E+0
+            v = 0.4496841067921404E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2520419490210201E+0
+            v = 0.5049153450478750E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6981906658447242E+0
+            v = 0.3976408018051883E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6587405243460960E+0
+            v = 0.4401400650381014E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4038544050097660E-1
+            v = 0.1724544350544401E-1
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5823842309715585E+0
+            v = 0.4231083095357343E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3545877390518688E+0
+            v = 0.5198069864064399E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2272181808998187E+0
+            b = 0.4864661535886647E+0
+            v = 0.4695720972568883E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 266:
+
+            v = -0.1313769127326952E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = -0.2522728704859336E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.4186853881700583E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.7039373391585475E+0
+            v = 0.5315167977810885E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1012526248572414E+0
+            v = 0.4047142377086219E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4647448726420539E+0
+            v = 0.4112482394406990E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3277420654971629E+0
+            v = 0.3595584899758782E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6620338663699974E+0
+            v = 0.4256131351428158E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8506508083520399E+0
+            v = 0.4229582700647240E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3233484542692899E+0
+            b = 0.1153112011009701E+0
+            v = 0.4080914225780505E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2314790158712601E+0
+            b = 0.5244939240922365E+0
+            v = 0.4071467593830964E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 302:
+
+            v = 0.8545911725128148E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3599119285025571E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.3515640345570105E+0
+            v = 0.3449788424305883E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6566329410219612E+0
+            v = 0.3604822601419882E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4729054132581005E+0
+            v = 0.3576729661743367E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9618308522614784E-1
+            v = 0.2352101413689164E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2219645236294178E+0
+            v = 0.3108953122413675E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7011766416089545E+0
+            v = 0.3650045807677255E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2644152887060663E+0
+            v = 0.2982344963171804E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5718955891878961E+0
+            v = 0.3600820932216460E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2510034751770465E+0
+            b = 0.8000727494073952E+0
+            v = 0.3571540554273387E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1233548532583327E+0
+            b = 0.4127724083168531E+0
+            v = 0.3392312205006170E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 350:
+
+            v = 0.3006796749453936E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3050627745650771E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.7068965463912316E+0
+            v = 0.1621104600288991E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4794682625712025E+0
+            v = 0.3005701484901752E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1927533154878019E+0
+            v = 0.2990992529653774E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6930357961327123E+0
+            v = 0.2982170644107595E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3608302115520091E+0
+            v = 0.2721564237310992E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6498486161496169E+0
+            v = 0.3033513795811141E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1932945013230339E+0
+            v = 0.3007949555218533E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3800494919899303E+0
+            v = 0.2881964603055307E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2899558825499574E+0
+            b = 0.7934537856582316E+0
+            v = 0.2958357626535696E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9684121455103957E-1
+            b = 0.8280801506686862E+0
+            v = 0.3036020026407088E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1833434647041659E+0
+            b = 0.9074658265305127E+0
+            v = 0.2832187403926303E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 434:
+
+            v = 0.5265897968224436E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2548219972002607E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.2512317418927307E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.6909346307509111E+0
+            v = 0.2530403801186355E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1774836054609158E+0
+            v = 0.2014279020918528E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4914342637784746E+0
+            v = 0.2501725168402936E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6456664707424256E+0
+            v = 0.2513267174597564E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2861289010307638E+0
+            v = 0.2302694782227416E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7568084367178018E-1
+            v = 0.1462495621594614E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3927259763368002E+0
+            v = 0.2445373437312980E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8818132877794288E+0
+            v = 0.2417442375638981E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9776428111182649E+0
+            v = 0.1910951282179532E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2054823696403044E+0
+            b = 0.8689460322872412E+0
+            v = 0.2416930044324775E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5905157048925271E+0
+            b = 0.7999278543857286E+0
+            v = 0.2512236854563495E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5550152361076807E+0
+            b = 0.7717462626915901E+0
+            v = 0.2496644054553086E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9371809858553722E+0
+            b = 0.3344363145343455E+0
+            v = 0.2236607760437849E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 590:
+
+            v = 0.3095121295306187E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1852379698597489E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.7040954938227469E+0
+            v = 0.1871790639277744E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6807744066455243E+0
+            v = 0.1858812585438317E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6372546939258752E+0
+            v = 0.1852028828296213E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5044419707800358E+0
+            v = 0.1846715956151242E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4215761784010967E+0
+            v = 0.1818471778162769E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3317920736472123E+0
+            v = 0.1749564657281154E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2384736701421887E+0
+            v = 0.1617210647254411E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1459036449157763E+0
+            v = 0.1384737234851692E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6095034115507196E-1
+            v = 0.9764331165051050E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6116843442009876E+0
+            v = 0.1857161196774078E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3964755348199858E+0
+            v = 0.1705153996395864E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1724782009907724E+0
+            v = 0.1300321685886048E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5610263808622060E+0
+            b = 0.3518280927733519E+0
+            v = 0.1842866472905286E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4742392842551980E+0
+            b = 0.2634716655937950E+0
+            v = 0.1802658934377451E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5984126497885380E+0
+            b = 0.1816640840360209E+0
+            v = 0.1849830560443660E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3791035407695563E+0
+            b = 0.1720795225656878E+0
+            v = 0.1713904507106709E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2778673190586244E+0
+            b = 0.8213021581932511E-1
+            v = 0.1555213603396808E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5033564271075117E+0
+            b = 0.8999205842074875E-1
+            v = 0.1802239128008525E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 770:
+
+            v = 0.2192942088181184E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1436433617319080E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.1421940344335877E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.5087204410502360E-1
+            v = 0.6798123511050502E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1228198790178831E+0
+            v = 0.9913184235294912E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2026890814408786E+0
+            v = 0.1180207833238949E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2847745156464294E+0
+            v = 0.1296599602080921E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3656719078978026E+0
+            v = 0.1365871427428316E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4428264886713469E+0
+            v = 0.1402988604775325E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5140619627249735E+0
+            v = 0.1418645563595609E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6306401219166803E+0
+            v = 0.1421376741851662E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6716883332022612E+0
+            v = 0.1423996475490962E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6979792685336881E+0
+            v = 0.1431554042178567E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1446865674195309E+0
+            v = 0.9254401499865368E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3390263475411216E+0
+            v = 0.1250239995053509E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5335804651263506E+0
+            v = 0.1394365843329230E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6944024393349413E-1
+            b = 0.2355187894242326E+0
+            v = 0.1127089094671749E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2269004109529460E+0
+            b = 0.4102182474045730E+0
+            v = 0.1345753760910670E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8025574607775339E-1
+            b = 0.6214302417481605E+0
+            v = 0.1424957283316783E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1467999527896572E+0
+            b = 0.3245284345717394E+0
+            v = 0.1261523341237750E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1571507769824727E+0
+            b = 0.5224482189696630E+0
+            v = 0.1392547106052696E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2365702993157246E+0
+            b = 0.6017546634089558E+0
+            v = 0.1418761677877656E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7714815866765732E-1
+            b = 0.4346575516141163E+0
+            v = 0.1338366684479554E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3062936666210730E+0
+            b = 0.4908826589037616E+0
+            v = 0.1393700862676131E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3822477379524787E+0
+            b = 0.5648768149099500E+0
+            v = 0.1415914757466932E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 974:
+
+            v = 0.1438294190527431E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1125772288287004E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.4292963545341347E-1
+            v = 0.4948029341949241E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1051426854086404E+0
+            v = 0.7357990109125470E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1750024867623087E+0
+            v = 0.8889132771304384E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2477653379650257E+0
+            v = 0.9888347838921435E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3206567123955957E+0
+            v = 0.1053299681709471E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3916520749849983E+0
+            v = 0.1092778807014578E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4590825874187624E+0
+            v = 0.1114389394063227E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5214563888415861E+0
+            v = 0.1123724788051555E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6253170244654199E+0
+            v = 0.1125239325243814E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6637926744523170E+0
+            v = 0.1126153271815905E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6910410398498301E+0
+            v = 0.1130286931123841E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7052907007457760E+0
+            v = 0.1134986534363955E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1236686762657990E+0
+            v = 0.6823367927109931E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2940777114468387E+0
+            v = 0.9454158160447096E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4697753849207649E+0
+            v = 0.1074429975385679E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6334563241139567E+0
+            v = 0.1129300086569132E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5974048614181342E-1
+            b = 0.2029128752777523E+0
+            v = 0.8436884500901954E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1375760408473636E+0
+            b = 0.4602621942484054E+0
+            v = 0.1075255720448885E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3391016526336286E+0
+            b = 0.5030673999662036E+0
+            v = 0.1108577236864462E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1271675191439820E+0
+            b = 0.2817606422442134E+0
+            v = 0.9566475323783357E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2693120740413512E+0
+            b = 0.4331561291720157E+0
+            v = 0.1080663250717391E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1419786452601918E+0
+            b = 0.6256167358580814E+0
+            v = 0.1126797131196295E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6709284600738255E-1
+            b = 0.3798395216859157E+0
+            v = 0.1022568715358061E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7057738183256172E-1
+            b = 0.5517505421423520E+0
+            v = 0.1108960267713108E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2783888477882155E+0
+            b = 0.6029619156159187E+0
+            v = 0.1122790653435766E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1979578938917407E+0
+            b = 0.3589606329589096E+0
+            v = 0.1032401847117460E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2087307061103274E+0
+            b = 0.5348666438135476E+0
+            v = 0.1107249382283854E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4055122137872836E+0
+            b = 0.5674997546074373E+0
+            v = 0.1121780048519972E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 1202:
+
+            v = 0.1105189233267572E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.9205232738090741E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.9133159786443561E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.3712636449657089E-1
+            v = 0.3690421898017899E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9140060412262223E-1
+            v = 0.5603990928680660E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1531077852469906E+0
+            v = 0.6865297629282609E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2180928891660612E+0
+            v = 0.7720338551145630E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2839874532200175E+0
+            v = 0.8301545958894795E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3491177600963764E+0
+            v = 0.8686692550179628E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4121431461444309E+0
+            v = 0.8927076285846890E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4718993627149127E+0
+            v = 0.9060820238568219E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5273145452842337E+0
+            v = 0.9119777254940867E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6209475332444019E+0
+            v = 0.9128720138604181E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6569722711857291E+0
+            v = 0.9130714935691735E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6841788309070143E+0
+            v = 0.9152873784554116E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7012604330123631E+0
+            v = 0.9187436274321654E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1072382215478166E+0
+            v = 0.5176977312965694E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2582068959496968E+0
+            v = 0.7331143682101417E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4172752955306717E+0
+            v = 0.8463232836379928E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5700366911792503E+0
+            v = 0.9031122694253992E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9827986018263947E+0
+            b = 0.1771774022615325E+0
+            v = 0.6485778453163257E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9624249230326228E+0
+            b = 0.2475716463426288E+0
+            v = 0.7435030910982369E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9402007994128811E+0
+            b = 0.3354616289066489E+0
+            v = 0.7998527891839054E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9320822040143202E+0
+            b = 0.3173615246611977E+0
+            v = 0.8101731497468018E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9043674199393299E+0
+            b = 0.4090268427085357E+0
+            v = 0.8483389574594331E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8912407560074747E+0
+            b = 0.3854291150669224E+0
+            v = 0.8556299257311812E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8676435628462708E+0
+            b = 0.4932221184851285E+0
+            v = 0.8803208679738260E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8581979986041619E+0
+            b = 0.4785320675922435E+0
+            v = 0.8811048182425720E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8396753624049856E+0
+            b = 0.4507422593157064E+0
+            v = 0.8850282341265444E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8165288564022188E+0
+            b = 0.5632123020762100E+0
+            v = 0.9021342299040653E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8015469370783529E+0
+            b = 0.5434303569693900E+0
+            v = 0.9010091677105086E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7773563069070351E+0
+            b = 0.5123518486419871E+0
+            v = 0.9022692938426915E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7661621213900394E+0
+            b = 0.6394279634749102E+0
+            v = 0.9158016174693465E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7553584143533510E+0
+            b = 0.6269805509024392E+0
+            v = 0.9131578003189435E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7344305757559503E+0
+            b = 0.6031161693096310E+0
+            v = 0.9107813579482705E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7043837184021765E+0
+            b = 0.5693702498468441E+0
+            v = 0.9105760258970126E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 1454:
+
+            v = 0.7777160743261247E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.7557646413004701E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.3229290663413854E-1
+            v = 0.2841633806090617E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8036733271462222E-1
+            v = 0.4374419127053555E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1354289960531653E+0
+            v = 0.5417174740872172E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1938963861114426E+0
+            v = 0.6148000891358593E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2537343715011275E+0
+            v = 0.6664394485800705E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3135251434752570E+0
+            v = 0.7025039356923220E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3721558339375338E+0
+            v = 0.7268511789249627E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4286809575195696E+0
+            v = 0.7422637534208629E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4822510128282994E+0
+            v = 0.7509545035841214E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5320679333566263E+0
+            v = 0.7548535057718401E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6172998195394274E+0
+            v = 0.7554088969774001E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6510679849127481E+0
+            v = 0.7553147174442808E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6777315251687360E+0
+            v = 0.7564767653292297E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6963109410648741E+0
+            v = 0.7587991808518730E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7058935009831749E+0
+            v = 0.7608261832033027E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9955546194091857E+0
+            v = 0.4021680447874916E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9734115901794209E+0
+            v = 0.5804871793945964E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9275693732388626E+0
+            v = 0.6792151955945159E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.8568022422795103E+0
+            v = 0.7336741211286294E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.7623495553719372E+0
+            v = 0.7581866300989608E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5707522908892223E+0
+            b = 0.4387028039889501E+0
+            v = 0.7538257859800743E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5196463388403083E+0
+            b = 0.3858908414762617E+0
+            v = 0.7483517247053123E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4646337531215351E+0
+            b = 0.3301937372343854E+0
+            v = 0.7371763661112059E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4063901697557691E+0
+            b = 0.2725423573563777E+0
+            v = 0.7183448895756934E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3456329466643087E+0
+            b = 0.2139510237495250E+0
+            v = 0.6895815529822191E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2831395121050332E+0
+            b = 0.1555922309786647E+0
+            v = 0.6480105801792886E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2197682022925330E+0
+            b = 0.9892878979686097E-1
+            v = 0.5897558896594636E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1564696098650355E+0
+            b = 0.4598642910675510E-1
+            v = 0.5095708849247346E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6027356673721295E+0
+            b = 0.3376625140173426E+0
+            v = 0.7536906428909755E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5496032320255096E+0
+            b = 0.2822301309727988E+0
+            v = 0.7472505965575118E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4921707755234567E+0
+            b = 0.2248632342592540E+0
+            v = 0.7343017132279698E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4309422998598483E+0
+            b = 0.1666224723456479E+0
+            v = 0.7130871582177445E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3664108182313672E+0
+            b = 0.1086964901822169E+0
+            v = 0.6817022032112776E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2990189057758436E+0
+            b = 0.5251989784120085E-1
+            v = 0.6380941145604121E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6268724013144998E+0
+            b = 0.2297523657550023E+0
+            v = 0.7550381377920310E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5707324144834607E+0
+            b = 0.1723080607093800E+0
+            v = 0.7478646640144802E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5096360901960365E+0
+            b = 0.1140238465390513E+0
+            v = 0.7335918720601220E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4438729938312456E+0
+            b = 0.5611522095882537E-1
+            v = 0.7110120527658118E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6419978471082389E+0
+            b = 0.1164174423140873E+0
+            v = 0.7571363978689501E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5817218061802611E+0
+            b = 0.5797589531445219E-1
+            v = 0.7489908329079234E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 1730:
+
+            v = 0.6309049437420976E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.6398287705571748E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.6357185073530720E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2860923126194662E-1
+            v = 0.2221207162188168E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7142556767711522E-1
+            v = 0.3475784022286848E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1209199540995559E+0
+            v = 0.4350742443589804E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1738673106594379E+0
+            v = 0.4978569136522127E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2284645438467734E+0
+            v = 0.5435036221998053E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2834807671701512E+0
+            v = 0.5765913388219542E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3379680145467339E+0
+            v = 0.6001200359226003E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3911355454819537E+0
+            v = 0.6162178172717512E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4422860353001403E+0
+            v = 0.6265218152438485E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4907781568726057E+0
+            v = 0.6323987160974212E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5360006153211468E+0
+            v = 0.6350767851540569E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6142105973596603E+0
+            v = 0.6354362775297107E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6459300387977504E+0
+            v = 0.6352302462706235E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6718056125089225E+0
+            v = 0.6358117881417972E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6910888533186254E+0
+            v = 0.6373101590310117E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7030467416823252E+0
+            v = 0.6390428961368665E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8354951166354646E-1
+            v = 0.3186913449946576E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2050143009099486E+0
+            v = 0.4678028558591711E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3370208290706637E+0
+            v = 0.5538829697598626E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4689051484233963E+0
+            v = 0.6044475907190476E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5939400424557334E+0
+            v = 0.6313575103509012E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1394983311832261E+0
+            b = 0.4097581162050343E-1
+            v = 0.4078626431855630E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1967999180485014E+0
+            b = 0.8851987391293348E-1
+            v = 0.4759933057812725E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2546183732548967E+0
+            b = 0.1397680182969819E+0
+            v = 0.5268151186413440E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3121281074713875E+0
+            b = 0.1929452542226526E+0
+            v = 0.5643048560507316E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3685981078502492E+0
+            b = 0.2467898337061562E+0
+            v = 0.5914501076613073E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4233760321547856E+0
+            b = 0.3003104124785409E+0
+            v = 0.6104561257874195E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4758671236059246E+0
+            b = 0.3526684328175033E+0
+            v = 0.6230252860707806E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5255178579796463E+0
+            b = 0.4031134861145713E+0
+            v = 0.6305618761760796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5718025633734589E+0
+            b = 0.4509426448342351E+0
+            v = 0.6343092767597889E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2686927772723415E+0
+            b = 0.4711322502423248E-1
+            v = 0.5176268945737826E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3306006819904809E+0
+            b = 0.9784487303942695E-1
+            v = 0.5564840313313692E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3904906850594983E+0
+            b = 0.1505395810025273E+0
+            v = 0.5856426671038980E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4479957951904390E+0
+            b = 0.2039728156296050E+0
+            v = 0.6066386925777091E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5027076848919780E+0
+            b = 0.2571529941121107E+0
+            v = 0.6208824962234458E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5542087392260217E+0
+            b = 0.3092191375815670E+0
+            v = 0.6296314297822907E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6020850887375187E+0
+            b = 0.3593807506130276E+0
+            v = 0.6340423756791859E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4019851409179594E+0
+            b = 0.5063389934378671E-1
+            v = 0.5829627677107342E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4635614567449800E+0
+            b = 0.1032422269160612E+0
+            v = 0.6048693376081110E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5215860931591575E+0
+            b = 0.1566322094006254E+0
+            v = 0.6202362317732461E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5758202499099271E+0
+            b = 0.2098082827491099E+0
+            v = 0.6299005328403779E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6259893683876795E+0
+            b = 0.2618824114553391E+0
+            v = 0.6347722390609353E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5313795124811891E+0
+            b = 0.5263245019338556E-1
+            v = 0.6203778981238834E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5893317955931995E+0
+            b = 0.1061059730982005E+0
+            v = 0.6308414671239979E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6426246321215801E+0
+            b = 0.1594171564034221E+0
+            v = 0.6362706466959498E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6511904367376113E+0
+            b = 0.5354789536565540E-1
+            v = 0.6375414170333233E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 2030:
+
+            v = 0.4656031899197431E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.5421549195295507E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2540835336814348E-1
+            v = 0.1778522133346553E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6399322800504915E-1
+            v = 0.2811325405682796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1088269469804125E+0
+            v = 0.3548896312631459E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1570670798818287E+0
+            v = 0.4090310897173364E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2071163932282514E+0
+            v = 0.4493286134169965E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2578914044450844E+0
+            v = 0.4793728447962723E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3085687558169623E+0
+            v = 0.5015415319164265E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3584719706267024E+0
+            v = 0.5175127372677937E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4070135594428709E+0
+            v = 0.5285522262081019E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4536618626222638E+0
+            v = 0.5356832703713962E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4979195686463577E+0
+            v = 0.5397914736175170E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5393075111126999E+0
+            v = 0.5416899441599930E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6115617676843916E+0
+            v = 0.5419308476889938E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6414308435160159E+0
+            v = 0.5416936902030596E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6664099412721607E+0
+            v = 0.5419544338703164E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6859161771214913E+0
+            v = 0.5428983656630975E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6993625593503890E+0
+            v = 0.5442286500098193E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7062393387719380E+0
+            v = 0.5452250345057301E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7479028168349763E-1
+            v = 0.2568002497728530E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1848951153969366E+0
+            v = 0.3827211700292145E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3059529066581305E+0
+            v = 0.4579491561917824E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4285556101021362E+0
+            v = 0.5042003969083574E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5468758653496526E+0
+            v = 0.5312708889976025E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6565821978343439E+0
+            v = 0.5438401790747117E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1253901572367117E+0
+            b = 0.3681917226439641E-1
+            v = 0.3316041873197344E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1775721510383941E+0
+            b = 0.7982487607213301E-1
+            v = 0.3899113567153771E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2305693358216114E+0
+            b = 0.1264640966592335E+0
+            v = 0.4343343327201309E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2836502845992063E+0
+            b = 0.1751585683418957E+0
+            v = 0.4679415262318919E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3361794746232590E+0
+            b = 0.2247995907632670E+0
+            v = 0.4930847981631031E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3875979172264824E+0
+            b = 0.2745299257422246E+0
+            v = 0.5115031867540091E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4374019316999074E+0
+            b = 0.3236373482441118E+0
+            v = 0.5245217148457367E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4851275843340022E+0
+            b = 0.3714967859436741E+0
+            v = 0.5332041499895321E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5303391803806868E+0
+            b = 0.4175353646321745E+0
+            v = 0.5384583126021542E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5726197380596287E+0
+            b = 0.4612084406355461E+0
+            v = 0.5411067210798852E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2431520732564863E+0
+            b = 0.4258040133043952E-1
+            v = 0.4259797391468714E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3002096800895869E+0
+            b = 0.8869424306722721E-1
+            v = 0.4604931368460021E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3558554457457432E+0
+            b = 0.1368811706510655E+0
+            v = 0.4871814878255202E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4097782537048887E+0
+            b = 0.1860739985015033E+0
+            v = 0.5072242910074885E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4616337666067458E+0
+            b = 0.2354235077395853E+0
+            v = 0.5217069845235350E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5110707008417874E+0
+            b = 0.2842074921347011E+0
+            v = 0.5315785966280310E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5577415286163795E+0
+            b = 0.3317784414984102E+0
+            v = 0.5376833708758905E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6013060431366950E+0
+            b = 0.3775299002040700E+0
+            v = 0.5408032092069521E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3661596767261781E+0
+            b = 0.4599367887164592E-1
+            v = 0.4842744917904866E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4237633153506581E+0
+            b = 0.9404893773654421E-1
+            v = 0.5048926076188130E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4786328454658452E+0
+            b = 0.1431377109091971E+0
+            v = 0.5202607980478373E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5305702076789774E+0
+            b = 0.1924186388843570E+0
+            v = 0.5309932388325743E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5793436224231788E+0
+            b = 0.2411590944775190E+0
+            v = 0.5377419770895208E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6247069017094747E+0
+            b = 0.2886871491583605E+0
+            v = 0.5411696331677717E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4874315552535204E+0
+            b = 0.4804978774953206E-1
+            v = 0.5197996293282420E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5427337322059053E+0
+            b = 0.9716857199366665E-1
+            v = 0.5311120836622945E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5943493747246700E+0
+            b = 0.1465205839795055E+0
+            v = 0.5384309319956951E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6421314033564943E+0
+            b = 0.1953579449803574E+0
+            v = 0.5421859504051886E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6020628374713980E+0
+            b = 0.4916375015738108E-1
+            v = 0.5390948355046314E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6529222529856881E+0
+            b = 0.9861621540127005E-1
+            v = 0.5433312705027845E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 2354:
+
+            v = 0.3922616270665292E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.4703831750854424E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.4678202801282136E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2290024646530589E-1
+            v = 0.1437832228979900E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5779086652271284E-1
+            v = 0.2303572493577644E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9863103576375984E-1
+            v = 0.2933110752447454E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1428155792982185E+0
+            v = 0.3402905998359838E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1888978116601463E+0
+            v = 0.3759138466870372E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2359091682970210E+0
+            v = 0.4030638447899798E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2831228833706171E+0
+            v = 0.4236591432242211E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3299495857966693E+0
+            v = 0.4390522656946746E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3758840802660796E+0
+            v = 0.4502523466626247E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4204751831009480E+0
+            v = 0.4580577727783541E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4633068518751051E+0
+            v = 0.4631391616615899E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5039849474507313E+0
+            v = 0.4660928953698676E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5421265793440747E+0
+            v = 0.4674751807936953E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6092660230557310E+0
+            v = 0.4676414903932920E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6374654204984869E+0
+            v = 0.4674086492347870E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6615136472609892E+0
+            v = 0.4674928539483207E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6809487285958127E+0
+            v = 0.4680748979686447E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6952980021665196E+0
+            v = 0.4690449806389040E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7041245497695400E+0
+            v = 0.4699877075860818E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6744033088306065E-1
+            v = 0.2099942281069176E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1678684485334166E+0
+            v = 0.3172269150712804E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2793559049539613E+0
+            v = 0.3832051358546523E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3935264218057639E+0
+            v = 0.4252193818146985E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5052629268232558E+0
+            v = 0.4513807963755000E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6107905315437531E+0
+            v = 0.4657797469114178E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1135081039843524E+0
+            b = 0.3331954884662588E-1
+            v = 0.2733362800522836E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1612866626099378E+0
+            b = 0.7247167465436538E-1
+            v = 0.3235485368463559E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2100786550168205E+0
+            b = 0.1151539110849745E+0
+            v = 0.3624908726013453E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2592282009459942E+0
+            b = 0.1599491097143677E+0
+            v = 0.3925540070712828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3081740561320203E+0
+            b = 0.2058699956028027E+0
+            v = 0.4156129781116235E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3564289781578164E+0
+            b = 0.2521624953502911E+0
+            v = 0.4330644984623263E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4035587288240703E+0
+            b = 0.2982090785797674E+0
+            v = 0.4459677725921312E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4491671196373903E+0
+            b = 0.3434762087235733E+0
+            v = 0.4551593004456795E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4928854782917489E+0
+            b = 0.3874831357203437E+0
+            v = 0.4613341462749918E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5343646791958988E+0
+            b = 0.4297814821746926E+0
+            v = 0.4651019618269806E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5732683216530990E+0
+            b = 0.4699402260943537E+0
+            v = 0.4670249536100625E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2214131583218986E+0
+            b = 0.3873602040643895E-1
+            v = 0.3549555576441708E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2741796504750071E+0
+            b = 0.8089496256902013E-1
+            v = 0.3856108245249010E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3259797439149485E+0
+            b = 0.1251732177620872E+0
+            v = 0.4098622845756882E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3765441148826891E+0
+            b = 0.1706260286403185E+0
+            v = 0.4286328604268950E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4255773574530558E+0
+            b = 0.2165115147300408E+0
+            v = 0.4427802198993945E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4727795117058430E+0
+            b = 0.2622089812225259E+0
+            v = 0.4530473511488561E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5178546895819012E+0
+            b = 0.3071721431296201E+0
+            v = 0.4600805475703138E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5605141192097460E+0
+            b = 0.3508998998801138E+0
+            v = 0.4644599059958017E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6004763319352512E+0
+            b = 0.3929160876166931E+0
+            v = 0.4667274455712508E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3352842634946949E+0
+            b = 0.4202563457288019E-1
+            v = 0.4069360518020356E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3891971629814670E+0
+            b = 0.8614309758870850E-1
+            v = 0.4260442819919195E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4409875565542281E+0
+            b = 0.1314500879380001E+0
+            v = 0.4408678508029063E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4904893058592484E+0
+            b = 0.1772189657383859E+0
+            v = 0.4518748115548597E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5375056138769549E+0
+            b = 0.2228277110050294E+0
+            v = 0.4595564875375116E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5818255708669969E+0
+            b = 0.2677179935014386E+0
+            v = 0.4643988774315846E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6232334858144959E+0
+            b = 0.3113675035544165E+0
+            v = 0.4668827491646946E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4489485354492058E+0
+            b = 0.4409162378368174E-1
+            v = 0.4400541823741973E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5015136875933150E+0
+            b = 0.8939009917748489E-1
+            v = 0.4514512890193797E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5511300550512623E+0
+            b = 0.1351806029383365E+0
+            v = 0.4596198627347549E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5976720409858000E+0
+            b = 0.1808370355053196E+0
+            v = 0.4648659016801781E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6409956378989354E+0
+            b = 0.2257852192301602E+0
+            v = 0.4675502017157673E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5581222330827514E+0
+            b = 0.4532173421637160E-1
+            v = 0.4598494476455523E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6074705984161695E+0
+            b = 0.9117488031840314E-1
+            v = 0.4654916955152048E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6532272537379033E+0
+            b = 0.1369294213140155E+0
+            v = 0.4684709779505137E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6594761494500487E+0
+            b = 0.4589901487275583E-1
+            v = 0.4691445539106986E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 2702:
+
+            v = 0.2998675149888161E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.4077860529495355E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2065562538818703E-1
+            v = 0.1185349192520667E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5250918173022379E-1
+            v = 0.1913408643425751E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8993480082038376E-1
+            v = 0.2452886577209897E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1306023924436019E+0
+            v = 0.2862408183288702E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1732060388531418E+0
+            v = 0.3178032258257357E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2168727084820249E+0
+            v = 0.3422945667633690E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2609528309173586E+0
+            v = 0.3612790520235922E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3049252927938952E+0
+            v = 0.3758638229818521E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3483484138084404E+0
+            v = 0.3868711798859953E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3908321549106406E+0
+            v = 0.3949429933189938E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4320210071894814E+0
+            v = 0.4006068107541156E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4715824795890053E+0
+            v = 0.4043192149672723E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5091984794078453E+0
+            v = 0.4064947495808078E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5445580145650803E+0
+            v = 0.4075245619813152E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6072575796841768E+0
+            v = 0.4076423540893566E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6339484505755803E+0
+            v = 0.4074280862251555E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6570718257486958E+0
+            v = 0.4074163756012244E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6762557330090709E+0
+            v = 0.4077647795071246E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6911161696923790E+0
+            v = 0.4084517552782530E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7012841911659961E+0
+            v = 0.4092468459224052E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7064559272410020E+0
+            v = 0.4097872687240906E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6123554989894765E-1
+            v = 0.1738986811745028E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1533070348312393E+0
+            v = 0.2659616045280191E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2563902605244206E+0
+            v = 0.3240596008171533E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3629346991663361E+0
+            v = 0.3621195964432943E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4683949968987538E+0
+            v = 0.3868838330760539E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5694479240657952E+0
+            v = 0.4018911532693111E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6634465430993955E+0
+            v = 0.4089929432983252E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1033958573552305E+0
+            b = 0.3034544009063584E-1
+            v = 0.2279907527706409E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1473521412414395E+0
+            b = 0.6618803044247135E-1
+            v = 0.2715205490578897E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1924552158705967E+0
+            b = 0.1054431128987715E+0
+            v = 0.3057917896703976E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2381094362890328E+0
+            b = 0.1468263551238858E+0
+            v = 0.3326913052452555E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2838121707936760E+0
+            b = 0.1894486108187886E+0
+            v = 0.3537334711890037E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3291323133373415E+0
+            b = 0.2326374238761579E+0
+            v = 0.3700567500783129E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3736896978741460E+0
+            b = 0.2758485808485768E+0
+            v = 0.3825245372589122E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4171406040760013E+0
+            b = 0.3186179331996921E+0
+            v = 0.3918125171518296E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4591677985256915E+0
+            b = 0.3605329796303794E+0
+            v = 0.3984720419937579E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4994733831718418E+0
+            b = 0.4012147253586509E+0
+            v = 0.4029746003338211E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5377731830445096E+0
+            b = 0.4403050025570692E+0
+            v = 0.4057428632156627E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5737917830001331E+0
+            b = 0.4774565904277483E+0
+            v = 0.4071719274114857E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2027323586271389E+0
+            b = 0.3544122504976147E-1
+            v = 0.2990236950664119E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2516942375187273E+0
+            b = 0.7418304388646328E-1
+            v = 0.3262951734212878E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3000227995257181E+0
+            b = 0.1150502745727186E+0
+            v = 0.3482634608242413E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3474806691046342E+0
+            b = 0.1571963371209364E+0
+            v = 0.3656596681700892E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3938103180359209E+0
+            b = 0.1999631877247100E+0
+            v = 0.3791740467794218E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4387519590455703E+0
+            b = 0.2428073457846535E+0
+            v = 0.3894034450156905E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4820503960077787E+0
+            b = 0.2852575132906155E+0
+            v = 0.3968600245508371E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5234573778475101E+0
+            b = 0.3268884208674639E+0
+            v = 0.4019931351420050E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5627318647235282E+0
+            b = 0.3673033321675939E+0
+            v = 0.4052108801278599E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5996390607156954E+0
+            b = 0.4061211551830290E+0
+            v = 0.4068978613940934E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3084780753791947E+0
+            b = 0.3860125523100059E-1
+            v = 0.3454275351319704E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3589988275920223E+0
+            b = 0.7928938987104867E-1
+            v = 0.3629963537007920E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4078628415881973E+0
+            b = 0.1212614643030087E+0
+            v = 0.3770187233889873E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4549287258889735E+0
+            b = 0.1638770827382693E+0
+            v = 0.3878608613694378E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5000278512957279E+0
+            b = 0.2065965798260176E+0
+            v = 0.3959065270221274E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5429785044928199E+0
+            b = 0.2489436378852235E+0
+            v = 0.4015286975463570E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5835939850491711E+0
+            b = 0.2904811368946891E+0
+            v = 0.4050866785614717E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6216870353444856E+0
+            b = 0.3307941957666609E+0
+            v = 0.4069320185051913E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4151104662709091E+0
+            b = 0.4064829146052554E-1
+            v = 0.3760120964062763E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4649804275009218E+0
+            b = 0.8258424547294755E-1
+            v = 0.3870969564418064E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5124695757009662E+0
+            b = 0.1251841962027289E+0
+            v = 0.3955287790534055E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5574711100606224E+0
+            b = 0.1679107505976331E+0
+            v = 0.4015361911302668E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5998597333287227E+0
+            b = 0.2102805057358715E+0
+            v = 0.4053836986719548E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6395007148516600E+0
+            b = 0.2518418087774107E+0
+            v = 0.4073578673299117E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5188456224746252E+0
+            b = 0.4194321676077518E-1
+            v = 0.3954628379231406E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5664190707942778E+0
+            b = 0.8457661551921499E-1
+            v = 0.4017645508847530E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6110464353283153E+0
+            b = 0.1273652932519396E+0
+            v = 0.4059030348651293E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6526430302051563E+0
+            b = 0.1698173239076354E+0
+            v = 0.4080565809484880E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6167551880377548E+0
+            b = 0.4266398851548864E-1
+            v = 0.4063018753664651E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6607195418355383E+0
+            b = 0.8551925814238349E-1
+            v = 0.4087191292799671E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 3074:
+
+            v = 0.2599095953754734E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3603134089687541E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.3586067974412447E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1886108518723392E-1
+            v = 0.9831528474385880E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4800217244625303E-1
+            v = 0.1605023107954450E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8244922058397242E-1
+            v = 0.2072200131464099E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1200408362484023E+0
+            v = 0.2431297618814187E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1595773530809965E+0
+            v = 0.2711819064496707E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2002635973434064E+0
+            v = 0.2932762038321116E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2415127590139982E+0
+            v = 0.3107032514197368E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2828584158458477E+0
+            v = 0.3243808058921213E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3239091015338138E+0
+            v = 0.3349899091374030E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3643225097962194E+0
+            v = 0.3430580688505218E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4037897083691802E+0
+            v = 0.3490124109290343E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4420247515194127E+0
+            v = 0.3532148948561955E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4787572538464938E+0
+            v = 0.3559862669062833E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5137265251275234E+0
+            v = 0.3576224317551411E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5466764056654611E+0
+            v = 0.3584050533086076E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6054859420813535E+0
+            v = 0.3584903581373224E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6308106701764562E+0
+            v = 0.3582991879040586E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6530369230179584E+0
+            v = 0.3582371187963125E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6718609524611158E+0
+            v = 0.3584353631122350E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6869676499894013E+0
+            v = 0.3589120166517785E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6980467077240748E+0
+            v = 0.3595445704531601E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7048241721250522E+0
+            v = 0.3600943557111074E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5591105222058232E-1
+            v = 0.1456447096742039E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1407384078513916E+0
+            v = 0.2252370188283782E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2364035438976309E+0
+            v = 0.2766135443474897E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3360602737818170E+0
+            v = 0.3110729491500851E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4356292630054665E+0
+            v = 0.3342506712303391E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5321569415256174E+0
+            v = 0.3491981834026860E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6232956305040554E+0
+            v = 0.3576003604348932E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9469870086838469E-1
+            b = 0.2778748387309470E-1
+            v = 0.1921921305788564E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1353170300568141E+0
+            b = 0.6076569878628364E-1
+            v = 0.2301458216495632E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1771679481726077E+0
+            b = 0.9703072762711040E-1
+            v = 0.2604248549522893E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2197066664231751E+0
+            b = 0.1354112458524762E+0
+            v = 0.2845275425870697E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2624783557374927E+0
+            b = 0.1750996479744100E+0
+            v = 0.3036870897974840E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3050969521214442E+0
+            b = 0.2154896907449802E+0
+            v = 0.3188414832298066E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3472252637196021E+0
+            b = 0.2560954625740152E+0
+            v = 0.3307046414722089E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3885610219026360E+0
+            b = 0.2965070050624096E+0
+            v = 0.3398330969031360E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4288273776062765E+0
+            b = 0.3363641488734497E+0
+            v = 0.3466757899705373E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4677662471302948E+0
+            b = 0.3753400029836788E+0
+            v = 0.3516095923230054E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5051333589553359E+0
+            b = 0.4131297522144286E+0
+            v = 0.3549645184048486E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5406942145810492E+0
+            b = 0.4494423776081795E+0
+            v = 0.3570415969441392E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5742204122576457E+0
+            b = 0.4839938958841502E+0
+            v = 0.3581251798496118E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1865407027225188E+0
+            b = 0.3259144851070796E-1
+            v = 0.2543491329913348E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2321186453689432E+0
+            b = 0.6835679505297343E-1
+            v = 0.2786711051330776E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2773159142523882E+0
+            b = 0.1062284864451989E+0
+            v = 0.2985552361083679E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3219200192237254E+0
+            b = 0.1454404409323047E+0
+            v = 0.3145867929154039E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3657032593944029E+0
+            b = 0.1854018282582510E+0
+            v = 0.3273290662067609E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4084376778363622E+0
+            b = 0.2256297412014750E+0
+            v = 0.3372705511943501E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4499004945751427E+0
+            b = 0.2657104425000896E+0
+            v = 0.3448274437851510E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4898758141326335E+0
+            b = 0.3052755487631557E+0
+            v = 0.3503592783048583E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5281547442266309E+0
+            b = 0.3439863920645423E+0
+            v = 0.3541854792663162E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5645346989813992E+0
+            b = 0.3815229456121914E+0
+            v = 0.3565995517909428E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5988181252159848E+0
+            b = 0.4175752420966734E+0
+            v = 0.3578802078302898E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2850425424471603E+0
+            b = 0.3562149509862536E-1
+            v = 0.2958644592860982E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3324619433027876E+0
+            b = 0.7330318886871096E-1
+            v = 0.3119548129116835E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3785848333076282E+0
+            b = 0.1123226296008472E+0
+            v = 0.3250745225005984E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4232891028562115E+0
+            b = 0.1521084193337708E+0
+            v = 0.3355153415935208E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4664287050829722E+0
+            b = 0.1921844459223610E+0
+            v = 0.3435847568549328E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5078458493735726E+0
+            b = 0.2321360989678303E+0
+            v = 0.3495786831622488E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5473779816204180E+0
+            b = 0.2715886486360520E+0
+            v = 0.3537767805534621E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5848617133811376E+0
+            b = 0.3101924707571355E+0
+            v = 0.3564459815421428E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6201348281584888E+0
+            b = 0.3476121052890973E+0
+            v = 0.3578464061225468E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3852191185387871E+0
+            b = 0.3763224880035108E-1
+            v = 0.3239748762836212E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4325025061073423E+0
+            b = 0.7659581935637135E-1
+            v = 0.3345491784174287E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4778486229734490E+0
+            b = 0.1163381306083900E+0
+            v = 0.3429126177301782E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5211663693009000E+0
+            b = 0.1563890598752899E+0
+            v = 0.3492420343097421E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5623469504853703E+0
+            b = 0.1963320810149200E+0
+            v = 0.3537399050235257E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6012718188659246E+0
+            b = 0.2357847407258738E+0
+            v = 0.3566209152659172E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6378179206390117E+0
+            b = 0.2743846121244060E+0
+            v = 0.3581084321919782E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4836936460214534E+0
+            b = 0.3895902610739024E-1
+            v = 0.3426522117591512E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5293792562683797E+0
+            b = 0.7871246819312640E-1
+            v = 0.3491848770121379E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5726281253100033E+0
+            b = 0.1187963808202981E+0
+            v = 0.3539318235231476E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6133658776169068E+0
+            b = 0.1587914708061787E+0
+            v = 0.3570231438458694E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6515085491865307E+0
+            b = 0.1983058575227646E+0
+            v = 0.3586207335051714E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5778692716064976E+0
+            b = 0.3977209689791542E-1
+            v = 0.3541196205164025E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6207904288086192E+0
+            b = 0.7990157592981152E-1
+            v = 0.3574296911573953E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6608688171046802E+0
+            b = 0.1199671308754309E+0
+            v = 0.3591993279818963E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6656263089489130E+0
+            b = 0.4015955957805969E-1
+            v = 0.3595855034661997E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 3470:
+
+            v = 0.2040382730826330E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3178149703889544E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1721420832906233E-1
+            v = 0.8288115128076110E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4408875374981770E-1
+            v = 0.1360883192522954E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7594680813878681E-1
+            v = 0.1766854454542662E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1108335359204799E+0
+            v = 0.2083153161230153E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1476517054388567E+0
+            v = 0.2333279544657158E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1856731870860615E+0
+            v = 0.2532809539930247E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2243634099428821E+0
+            v = 0.2692472184211158E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2633006881662727E+0
+            v = 0.2819949946811885E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3021340904916283E+0
+            v = 0.2920953593973030E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3405594048030089E+0
+            v = 0.2999889782948352E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3783044434007372E+0
+            v = 0.3060292120496902E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4151194767407910E+0
+            v = 0.3105109167522192E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4507705766443257E+0
+            v = 0.3136902387550312E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4850346056573187E+0
+            v = 0.3157984652454632E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5176950817792470E+0
+            v = 0.3170516518425422E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5485384240820989E+0
+            v = 0.3176568425633755E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6039117238943308E+0
+            v = 0.3177198411207062E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6279956655573113E+0
+            v = 0.3175519492394733E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6493636169568952E+0
+            v = 0.3174654952634756E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6677644117704504E+0
+            v = 0.3175676415467654E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6829368572115624E+0
+            v = 0.3178923417835410E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6946195818184121E+0
+            v = 0.3183788287531909E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7025711542057026E+0
+            v = 0.3188755151918807E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7066004767140119E+0
+            v = 0.3191916889313849E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5132537689946062E-1
+            v = 0.1231779611744508E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1297994661331225E+0
+            v = 0.1924661373839880E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2188852049401307E+0
+            v = 0.2380881867403424E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3123174824903457E+0
+            v = 0.2693100663037885E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4064037620738195E+0
+            v = 0.2908673382834366E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4984958396944782E+0
+            v = 0.3053914619381535E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5864975046021365E+0
+            v = 0.3143916684147777E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6686711634580175E+0
+            v = 0.3187042244055363E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.8715738780835950E-1
+            b = 0.2557175233367578E-1
+            v = 0.1635219535869790E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1248383123134007E+0
+            b = 0.5604823383376681E-1
+            v = 0.1968109917696070E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1638062693383378E+0
+            b = 0.8968568601900765E-1
+            v = 0.2236754342249974E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2035586203373176E+0
+            b = 0.1254086651976279E+0
+            v = 0.2453186687017181E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2436798975293774E+0
+            b = 0.1624780150162012E+0
+            v = 0.2627551791580541E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2838207507773806E+0
+            b = 0.2003422342683208E+0
+            v = 0.2767654860152220E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3236787502217692E+0
+            b = 0.2385628026255263E+0
+            v = 0.2879467027765895E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3629849554840691E+0
+            b = 0.2767731148783578E+0
+            v = 0.2967639918918702E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4014948081992087E+0
+            b = 0.3146542308245309E+0
+            v = 0.3035900684660351E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4389818379260225E+0
+            b = 0.3519196415895088E+0
+            v = 0.3087338237298308E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4752331143674377E+0
+            b = 0.3883050984023654E+0
+            v = 0.3124608838860167E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5100457318374018E+0
+            b = 0.4235613423908649E+0
+            v = 0.3150084294226743E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5432238388954868E+0
+            b = 0.4574484717196220E+0
+            v = 0.3165958398598402E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5745758685072442E+0
+            b = 0.4897311639255524E+0
+            v = 0.3174320440957372E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1723981437592809E+0
+            b = 0.3010630597881105E-1
+            v = 0.2182188909812599E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2149553257844597E+0
+            b = 0.6326031554204694E-1
+            v = 0.2399727933921445E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2573256081247422E+0
+            b = 0.9848566980258631E-1
+            v = 0.2579796133514652E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2993163751238106E+0
+            b = 0.1350835952384266E+0
+            v = 0.2727114052623535E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3407238005148000E+0
+            b = 0.1725184055442181E+0
+            v = 0.2846327656281355E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3813454978483264E+0
+            b = 0.2103559279730725E+0
+            v = 0.2941491102051334E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4209848104423343E+0
+            b = 0.2482278774554860E+0
+            v = 0.3016049492136107E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4594519699996300E+0
+            b = 0.2858099509982883E+0
+            v = 0.3072949726175648E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4965640166185930E+0
+            b = 0.3228075659915428E+0
+            v = 0.3114768142886460E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5321441655571562E+0
+            b = 0.3589459907204151E+0
+            v = 0.3143823673666223E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5660208438582166E+0
+            b = 0.3939630088864310E+0
+            v = 0.3162269764661535E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5980264315964364E+0
+            b = 0.4276029922949089E+0
+            v = 0.3172164663759821E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2644215852350733E+0
+            b = 0.3300939429072552E-1
+            v = 0.2554575398967435E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3090113743443063E+0
+            b = 0.6803887650078501E-1
+            v = 0.2701704069135677E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3525871079197808E+0
+            b = 0.1044326136206709E+0
+            v = 0.2823693413468940E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3950418005354029E+0
+            b = 0.1416751597517679E+0
+            v = 0.2922898463214289E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4362475663430163E+0
+            b = 0.1793408610504821E+0
+            v = 0.3001829062162428E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4760661812145854E+0
+            b = 0.2170630750175722E+0
+            v = 0.3062890864542953E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5143551042512103E+0
+            b = 0.2545145157815807E+0
+            v = 0.3108328279264746E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5509709026935597E+0
+            b = 0.2913940101706601E+0
+            v = 0.3140243146201245E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5857711030329428E+0
+            b = 0.3274169910910705E+0
+            v = 0.3160638030977130E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6186149917404392E+0
+            b = 0.3623081329317265E+0
+            v = 0.3171462882206275E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3586894569557064E+0
+            b = 0.3497354386450040E-1
+            v = 0.2812388416031796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4035266610019441E+0
+            b = 0.7129736739757095E-1
+            v = 0.2912137500288045E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4467775312332510E+0
+            b = 0.1084758620193165E+0
+            v = 0.2993241256502206E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4883638346608543E+0
+            b = 0.1460915689241772E+0
+            v = 0.3057101738983822E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5281908348434601E+0
+            b = 0.1837790832369980E+0
+            v = 0.3105319326251432E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5661542687149311E+0
+            b = 0.2212075390874021E+0
+            v = 0.3139565514428167E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6021450102031452E+0
+            b = 0.2580682841160985E+0
+            v = 0.3161543006806366E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6360520783610050E+0
+            b = 0.2940656362094121E+0
+            v = 0.3172985960613294E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4521611065087196E+0
+            b = 0.3631055365867002E-1
+            v = 0.2989400336901431E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4959365651560963E+0
+            b = 0.7348318468484350E-1
+            v = 0.3054555883947677E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5376815804038283E+0
+            b = 0.1111087643812648E+0
+            v = 0.3104764960807702E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5773314480243768E+0
+            b = 0.1488226085145408E+0
+            v = 0.3141015825977616E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6148113245575056E+0
+            b = 0.1862892274135151E+0
+            v = 0.3164520621159896E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6500407462842380E+0
+            b = 0.2231909701714456E+0
+            v = 0.3176652305912204E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5425151448707213E+0
+            b = 0.3718201306118944E-1
+            v = 0.3105097161023939E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5841860556907931E+0
+            b = 0.7483616335067346E-1
+            v = 0.3143014117890550E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6234632186851500E+0
+            b = 0.1125990834266120E+0
+            v = 0.3168172866287200E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6602934551848843E+0
+            b = 0.1501303813157619E+0
+            v = 0.3181401865570968E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6278573968375105E+0
+            b = 0.3767559930245720E-1
+            v = 0.3170663659156037E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6665611711264577E+0
+            b = 0.7548443301360158E-1
+            v = 0.3185447944625510E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 3890:
+
+            v = 0.1807395252196920E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2848008782238827E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.2836065837530581E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1587876419858352E-1
+            v = 0.7013149266673816E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4069193593751206E-1
+            v = 0.1162798021956766E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7025888115257997E-1
+            v = 0.1518728583972105E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1027495450028704E+0
+            v = 0.1798796108216934E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1371457730893426E+0
+            v = 0.2022593385972785E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1727758532671953E+0
+            v = 0.2203093105575464E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2091492038929037E+0
+            v = 0.2349294234299855E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2458813281751915E+0
+            v = 0.2467682058747003E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2826545859450066E+0
+            v = 0.2563092683572224E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3191957291799622E+0
+            v = 0.2639253896763318E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3552621469299578E+0
+            v = 0.2699137479265108E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3906329503406230E+0
+            v = 0.2745196420166739E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4251028614093031E+0
+            v = 0.2779529197397593E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4584777520111870E+0
+            v = 0.2803996086684265E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4905711358710193E+0
+            v = 0.2820302356715842E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5212011669847385E+0
+            v = 0.2830056747491068E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5501878488737995E+0
+            v = 0.2834808950776839E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6025037877479342E+0
+            v = 0.2835282339078929E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6254572689549016E+0
+            v = 0.2833819267065800E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6460107179528248E+0
+            v = 0.2832858336906784E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6639541138154251E+0
+            v = 0.2833268235451244E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6790688515667495E+0
+            v = 0.2835432677029253E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6911338580371512E+0
+            v = 0.2839091722743049E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6999385956126490E+0
+            v = 0.2843308178875841E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7053037748656896E+0
+            v = 0.2846703550533846E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4732224387180115E-1
+            v = 0.1051193406971900E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1202100529326803E+0
+            v = 0.1657871838796974E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2034304820664855E+0
+            v = 0.2064648113714232E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2912285643573002E+0
+            v = 0.2347942745819741E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3802361792726768E+0
+            v = 0.2547775326597726E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4680598511056146E+0
+            v = 0.2686876684847025E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5528151052155599E+0
+            v = 0.2778665755515867E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6329386307803041E+0
+            v = 0.2830996616782929E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.8056516651369069E-1
+            b = 0.2363454684003124E-1
+            v = 0.1403063340168372E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1156476077139389E+0
+            b = 0.5191291632545936E-1
+            v = 0.1696504125939477E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1520473382760421E+0
+            b = 0.8322715736994519E-1
+            v = 0.1935787242745390E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1892986699745931E+0
+            b = 0.1165855667993712E+0
+            v = 0.2130614510521968E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2270194446777792E+0
+            b = 0.1513077167409504E+0
+            v = 0.2289381265931048E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2648908185093273E+0
+            b = 0.1868882025807859E+0
+            v = 0.2418630292816186E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3026389259574136E+0
+            b = 0.2229277629776224E+0
+            v = 0.2523400495631193E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3400220296151384E+0
+            b = 0.2590951840746235E+0
+            v = 0.2607623973449605E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3768217953335510E+0
+            b = 0.2951047291750847E+0
+            v = 0.2674441032689209E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4128372900921884E+0
+            b = 0.3307019714169930E+0
+            v = 0.2726432360343356E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4478807131815630E+0
+            b = 0.3656544101087634E+0
+            v = 0.2765787685924545E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4817742034089257E+0
+            b = 0.3997448951939695E+0
+            v = 0.2794428690642224E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5143472814653344E+0
+            b = 0.4327667110812024E+0
+            v = 0.2814099002062895E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5454346213905650E+0
+            b = 0.4645196123532293E+0
+            v = 0.2826429531578994E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5748739313170252E+0
+            b = 0.4948063555703345E+0
+            v = 0.2832983542550884E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1599598738286342E+0
+            b = 0.2792357590048985E-1
+            v = 0.1886695565284976E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1998097412500951E+0
+            b = 0.5877141038139065E-1
+            v = 0.2081867882748234E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2396228952566202E+0
+            b = 0.9164573914691377E-1
+            v = 0.2245148680600796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2792228341097746E+0
+            b = 0.1259049641962687E+0
+            v = 0.2380370491511872E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3184251107546741E+0
+            b = 0.1610594823400863E+0
+            v = 0.2491398041852455E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3570481164426244E+0
+            b = 0.1967151653460898E+0
+            v = 0.2581632405881230E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3949164710492144E+0
+            b = 0.2325404606175168E+0
+            v = 0.2653965506227417E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4318617293970503E+0
+            b = 0.2682461141151439E+0
+            v = 0.2710857216747087E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4677221009931678E+0
+            b = 0.3035720116011973E+0
+            v = 0.2754434093903659E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5023417939270955E+0
+            b = 0.3382781859197439E+0
+            v = 0.2786579932519380E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5355701836636128E+0
+            b = 0.3721383065625942E+0
+            v = 0.2809011080679474E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5672608451328771E+0
+            b = 0.4049346360466055E+0
+            v = 0.2823336184560987E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5972704202540162E+0
+            b = 0.4364538098633802E+0
+            v = 0.2831101175806309E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2461687022333596E+0
+            b = 0.3070423166833368E-1
+            v = 0.2221679970354546E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2881774566286831E+0
+            b = 0.6338034669281885E-1
+            v = 0.2356185734270703E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3293963604116978E+0
+            b = 0.9742862487067941E-1
+            v = 0.2469228344805590E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3697303822241377E+0
+            b = 0.1323799532282290E+0
+            v = 0.2562726348642046E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4090663023135127E+0
+            b = 0.1678497018129336E+0
+            v = 0.2638756726753028E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4472819355411712E+0
+            b = 0.2035095105326114E+0
+            v = 0.2699311157390862E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4842513377231437E+0
+            b = 0.2390692566672091E+0
+            v = 0.2746233268403837E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5198477629962928E+0
+            b = 0.2742649818076149E+0
+            v = 0.2781225674454771E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5539453011883145E+0
+            b = 0.3088503806580094E+0
+            v = 0.2805881254045684E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5864196762401251E+0
+            b = 0.3425904245906614E+0
+            v = 0.2821719877004913E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6171484466668390E+0
+            b = 0.3752562294789468E+0
+            v = 0.2830222502333124E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3350337830565727E+0
+            b = 0.3261589934634747E-1
+            v = 0.2457995956744870E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3775773224758284E+0
+            b = 0.6658438928081572E-1
+            v = 0.2551474407503706E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4188155229848973E+0
+            b = 0.1014565797157954E+0
+            v = 0.2629065335195311E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4586805892009344E+0
+            b = 0.1368573320843822E+0
+            v = 0.2691900449925075E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4970895714224235E+0
+            b = 0.1724614851951608E+0
+            v = 0.2741275485754276E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5339505133960747E+0
+            b = 0.2079779381416412E+0
+            v = 0.2778530970122595E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5691665792531440E+0
+            b = 0.2431385788322288E+0
+            v = 0.2805010567646741E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6026387682680377E+0
+            b = 0.2776901883049853E+0
+            v = 0.2822055834031040E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6342676150163307E+0
+            b = 0.3113881356386632E+0
+            v = 0.2831016901243473E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4237951119537067E+0
+            b = 0.3394877848664351E-1
+            v = 0.2624474901131803E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4656918683234929E+0
+            b = 0.6880219556291447E-1
+            v = 0.2688034163039377E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5058857069185980E+0
+            b = 0.1041946859721635E+0
+            v = 0.2738932751287636E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5443204666713996E+0
+            b = 0.1398039738736393E+0
+            v = 0.2777944791242523E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5809298813759742E+0
+            b = 0.1753373381196155E+0
+            v = 0.2806011661660987E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6156416039447128E+0
+            b = 0.2105215793514010E+0
+            v = 0.2824181456597460E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6483801351066604E+0
+            b = 0.2450953312157051E+0
+            v = 0.2833585216577828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5103616577251688E+0
+            b = 0.3485560643800719E-1
+            v = 0.2738165236962878E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5506738792580681E+0
+            b = 0.7026308631512033E-1
+            v = 0.2778365208203180E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5889573040995292E+0
+            b = 0.1059035061296403E+0
+            v = 0.2807852940418966E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6251641589516930E+0
+            b = 0.1414823925236026E+0
+            v = 0.2827245949674705E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6592414921570178E+0
+            b = 0.1767207908214530E+0
+            v = 0.2837342344829828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5930314017533384E+0
+            b = 0.3542189339561672E-1
+            v = 0.2809233907610981E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6309812253390175E+0
+            b = 0.7109574040369549E-1
+            v = 0.2829930809742694E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6666296011353230E+0
+            b = 0.1067259792282730E+0
+            v = 0.2841097874111479E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6703715271049922E+0
+            b = 0.3569455268820809E-1
+            v = 0.2843455206008783E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 4334:
+
+            v = 0.1449063022537883E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2546377329828424E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1462896151831013E-1
+            v = 0.6018432961087496E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3769840812493139E-1
+            v = 0.1002286583263673E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6524701904096891E-1
+            v = 0.1315222931028093E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9560543416134648E-1
+            v = 0.1564213746876724E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1278335898929198E+0
+            v = 0.1765118841507736E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1613096104466031E+0
+            v = 0.1928737099311080E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1955806225745371E+0
+            v = 0.2062658534263270E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2302935218498028E+0
+            v = 0.2172395445953787E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2651584344113027E+0
+            v = 0.2262076188876047E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2999276825183209E+0
+            v = 0.2334885699462397E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3343828669718798E+0
+            v = 0.2393355273179203E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3683265013750518E+0
+            v = 0.2439559200468863E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4015763206518108E+0
+            v = 0.2475251866060002E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4339612026399770E+0
+            v = 0.2501965558158773E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4653180651114582E+0
+            v = 0.2521081407925925E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4954893331080803E+0
+            v = 0.2533881002388081E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5243207068924930E+0
+            v = 0.2541582900848261E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5516590479041704E+0
+            v = 0.2545365737525860E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6012371927804176E+0
+            v = 0.2545726993066799E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6231574466449819E+0
+            v = 0.2544456197465555E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6429416514181271E+0
+            v = 0.2543481596881064E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6604124272943595E+0
+            v = 0.2543506451429194E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6753851470408250E+0
+            v = 0.2544905675493763E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6876717970626160E+0
+            v = 0.2547611407344429E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6970895061319234E+0
+            v = 0.2551060375448869E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7034746912553310E+0
+            v = 0.2554291933816039E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7067017217542295E+0
+            v = 0.2556255710686343E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4382223501131123E-1
+            v = 0.9041339695118195E-4
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1117474077400006E+0
+            v = 0.1438426330079022E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1897153252911440E+0
+            v = 0.1802523089820518E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2724023009910331E+0
+            v = 0.2060052290565496E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3567163308709902E+0
+            v = 0.2245002248967466E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4404784483028087E+0
+            v = 0.2377059847731150E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5219833154161411E+0
+            v = 0.2468118955882525E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5998179868977553E+0
+            v = 0.2525410872966528E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6727803154548222E+0
+            v = 0.2553101409933397E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.7476563943166086E-1
+            b = 0.2193168509461185E-1
+            v = 0.1212879733668632E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1075341482001416E+0
+            b = 0.4826419281533887E-1
+            v = 0.1472872881270931E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1416344885203259E+0
+            b = 0.7751191883575742E-1
+            v = 0.1686846601010828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1766325315388586E+0
+            b = 0.1087558139247680E+0
+            v = 0.1862698414660208E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2121744174481514E+0
+            b = 0.1413661374253096E+0
+            v = 0.2007430956991861E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2479669443408145E+0
+            b = 0.1748768214258880E+0
+            v = 0.2126568125394796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2837600452294113E+0
+            b = 0.2089216406612073E+0
+            v = 0.2224394603372113E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3193344933193984E+0
+            b = 0.2431987685545972E+0
+            v = 0.2304264522673135E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3544935442438745E+0
+            b = 0.2774497054377770E+0
+            v = 0.2368854288424087E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3890571932288154E+0
+            b = 0.3114460356156915E+0
+            v = 0.2420352089461772E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4228581214259090E+0
+            b = 0.3449806851913012E+0
+            v = 0.2460597113081295E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4557387211304052E+0
+            b = 0.3778618641248256E+0
+            v = 0.2491181912257687E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4875487950541643E+0
+            b = 0.4099086391698978E+0
+            v = 0.2513528194205857E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5181436529962997E+0
+            b = 0.4409474925853973E+0
+            v = 0.2528943096693220E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5473824095600661E+0
+            b = 0.4708094517711291E+0
+            v = 0.2538660368488136E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5751263398976174E+0
+            b = 0.4993275140354637E+0
+            v = 0.2543868648299022E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1489515746840028E+0
+            b = 0.2599381993267017E-1
+            v = 0.1642595537825183E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1863656444351767E+0
+            b = 0.5479286532462190E-1
+            v = 0.1818246659849308E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2238602880356348E+0
+            b = 0.8556763251425254E-1
+            v = 0.1966565649492420E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2612723375728160E+0
+            b = 0.1177257802267011E+0
+            v = 0.2090677905657991E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2984332990206190E+0
+            b = 0.1508168456192700E+0
+            v = 0.2193820409510504E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3351786584663333E+0
+            b = 0.1844801892177727E+0
+            v = 0.2278870827661928E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3713505522209120E+0
+            b = 0.2184145236087598E+0
+            v = 0.2348283192282090E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4067981098954663E+0
+            b = 0.2523590641486229E+0
+            v = 0.2404139755581477E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4413769993687534E+0
+            b = 0.2860812976901373E+0
+            v = 0.2448227407760734E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4749487182516394E+0
+            b = 0.3193686757808996E+0
+            v = 0.2482110455592573E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5073798105075426E+0
+            b = 0.3520226949547602E+0
+            v = 0.2507192397774103E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5385410448878654E+0
+            b = 0.3838544395667890E+0
+            v = 0.2524765968534880E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5683065353670530E+0
+            b = 0.4146810037640963E+0
+            v = 0.2536052388539425E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5965527620663510E+0
+            b = 0.4443224094681121E+0
+            v = 0.2542230588033068E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2299227700856157E+0
+            b = 0.2865757664057584E-1
+            v = 0.1944817013047896E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2695752998553267E+0
+            b = 0.5923421684485993E-1
+            v = 0.2067862362746635E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3086178716611389E+0
+            b = 0.9117817776057715E-1
+            v = 0.2172440734649114E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3469649871659077E+0
+            b = 0.1240593814082605E+0
+            v = 0.2260125991723423E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3845153566319655E+0
+            b = 0.1575272058259175E+0
+            v = 0.2332655008689523E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4211600033403215E+0
+            b = 0.1912845163525413E+0
+            v = 0.2391699681532458E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4567867834329882E+0
+            b = 0.2250710177858171E+0
+            v = 0.2438801528273928E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4912829319232061E+0
+            b = 0.2586521303440910E+0
+            v = 0.2475370504260665E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5245364793303812E+0
+            b = 0.2918112242865407E+0
+            v = 0.2502707235640574E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5564369788915756E+0
+            b = 0.3243439239067890E+0
+            v = 0.2522031701054241E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5868757697775287E+0
+            b = 0.3560536787835351E+0
+            v = 0.2534511269978784E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6157458853519617E+0
+            b = 0.3867480821242581E+0
+            v = 0.2541284914955151E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3138461110672113E+0
+            b = 0.3051374637507278E-1
+            v = 0.2161509250688394E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3542495872050569E+0
+            b = 0.6237111233730755E-1
+            v = 0.2248778513437852E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3935751553120181E+0
+            b = 0.9516223952401907E-1
+            v = 0.2322388803404617E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4317634668111147E+0
+            b = 0.1285467341508517E+0
+            v = 0.2383265471001355E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4687413842250821E+0
+            b = 0.1622318931656033E+0
+            v = 0.2432476675019525E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5044274237060283E+0
+            b = 0.1959581153836453E+0
+            v = 0.2471122223750674E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5387354077925727E+0
+            b = 0.2294888081183837E+0
+            v = 0.2500291752486870E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5715768898356105E+0
+            b = 0.2626031152713945E+0
+            v = 0.2521055942764682E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6028627200136111E+0
+            b = 0.2950904075286713E+0
+            v = 0.2534472785575503E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6325039812653463E+0
+            b = 0.3267458451113286E+0
+            v = 0.2541599713080121E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3981986708423407E+0
+            b = 0.3183291458749821E-1
+            v = 0.2317380975862936E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4382791182133300E+0
+            b = 0.6459548193880908E-1
+            v = 0.2378550733719775E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4769233057218166E+0
+            b = 0.9795757037087952E-1
+            v = 0.2428884456739118E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5140823911194238E+0
+            b = 0.1316307235126655E+0
+            v = 0.2469002655757292E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5496977833862983E+0
+            b = 0.1653556486358704E+0
+            v = 0.2499657574265851E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5837047306512727E+0
+            b = 0.1988931724126510E+0
+            v = 0.2521676168486082E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6160349566926879E+0
+            b = 0.2320174581438950E+0
+            v = 0.2535935662645334E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6466185353209440E+0
+            b = 0.2645106562168662E+0
+            v = 0.2543356743363214E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4810835158795404E+0
+            b = 0.3275917807743992E-1
+            v = 0.2427353285201535E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5199925041324341E+0
+            b = 0.6612546183967181E-1
+            v = 0.2468258039744386E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5571717692207494E+0
+            b = 0.9981498331474143E-1
+            v = 0.2500060956440310E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5925789250836378E+0
+            b = 0.1335687001410374E+0
+            v = 0.2523238365420979E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6261658523859670E+0
+            b = 0.1671444402896463E+0
+            v = 0.2538399260252846E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6578811126669331E+0
+            b = 0.2003106382156076E+0
+            v = 0.2546255927268069E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5609624612998100E+0
+            b = 0.3337500940231335E-1
+            v = 0.2500583360048449E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5979959659984670E+0
+            b = 0.6708750335901803E-1
+            v = 0.2524777638260203E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6330523711054002E+0
+            b = 0.1008792126424850E+0
+            v = 0.2540951193860656E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6660960998103972E+0
+            b = 0.1345050343171794E+0
+            v = 0.2549524085027472E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6365384364585819E+0
+            b = 0.3372799460737052E-1
+            v = 0.2542569507009158E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6710994302899275E+0
+            b = 0.6755249309678028E-1
+            v = 0.2552114127580376E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 4802:
+
+            v = 0.9687521879420705E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2307897895367918E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.2297310852498558E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2335728608887064E-1
+            v = 0.7386265944001919E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4352987836550653E-1
+            v = 0.8257977698542210E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6439200521088801E-1
+            v = 0.9706044762057630E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9003943631993181E-1
+            v = 0.1302393847117003E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1196706615548473E+0
+            v = 0.1541957004600968E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1511715412838134E+0
+            v = 0.1704459770092199E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1835982828503801E+0
+            v = 0.1827374890942906E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2165081259155405E+0
+            v = 0.1926360817436107E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2496208720417563E+0
+            v = 0.2008010239494833E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2827200673567900E+0
+            v = 0.2075635983209175E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3156190823994346E+0
+            v = 0.2131306638690909E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3481476793749115E+0
+            v = 0.2176562329937335E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3801466086947226E+0
+            v = 0.2212682262991018E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4114652119634011E+0
+            v = 0.2240799515668565E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4419598786519751E+0
+            v = 0.2261959816187525E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4714925949329543E+0
+            v = 0.2277156368808855E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4999293972879466E+0
+            v = 0.2287351772128336E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5271387221431248E+0
+            v = 0.2293490814084085E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5529896780837761E+0
+            v = 0.2296505312376273E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6000856099481712E+0
+            v = 0.2296793832318756E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6210562192785175E+0
+            v = 0.2295785443842974E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6401165879934240E+0
+            v = 0.2295017931529102E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6571144029244334E+0
+            v = 0.2295059638184868E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6718910821718863E+0
+            v = 0.2296232343237362E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6842845591099010E+0
+            v = 0.2298530178740771E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6941353476269816E+0
+            v = 0.2301579790280501E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7012965242212991E+0
+            v = 0.2304690404996513E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7056471428242644E+0
+            v = 0.2307027995907102E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4595557643585895E-1
+            v = 0.9312274696671092E-4
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1049316742435023E+0
+            v = 0.1199919385876926E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1773548879549274E+0
+            v = 0.1598039138877690E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2559071411236127E+0
+            v = 0.1822253763574900E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3358156837985898E+0
+            v = 0.1988579593655040E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4155835743763893E+0
+            v = 0.2112620102533307E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4937894296167472E+0
+            v = 0.2201594887699007E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5691569694793316E+0
+            v = 0.2261622590895036E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6405840854894251E+0
+            v = 0.2296458453435705E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.7345133894143348E-1
+            b = 0.2177844081486067E-1
+            v = 0.1006006990267000E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1009859834044931E+0
+            b = 0.4590362185775188E-1
+            v = 0.1227676689635876E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1324289619748758E+0
+            b = 0.7255063095690877E-1
+            v = 0.1467864280270117E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1654272109607127E+0
+            b = 0.1017825451960684E+0
+            v = 0.1644178912101232E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1990767186776461E+0
+            b = 0.1325652320980364E+0
+            v = 0.1777664890718961E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2330125945523278E+0
+            b = 0.1642765374496765E+0
+            v = 0.1884825664516690E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2670080611108287E+0
+            b = 0.1965360374337889E+0
+            v = 0.1973269246453848E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3008753376294316E+0
+            b = 0.2290726770542238E+0
+            v = 0.2046767775855328E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3344475596167860E+0
+            b = 0.2616645495370823E+0
+            v = 0.2107600125918040E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3675709724070786E+0
+            b = 0.2941150728843141E+0
+            v = 0.2157416362266829E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4001000887587812E+0
+            b = 0.3262440400919066E+0
+            v = 0.2197557816920721E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4318956350436028E+0
+            b = 0.3578835350611916E+0
+            v = 0.2229192611835437E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4628239056795531E+0
+            b = 0.3888751854043678E+0
+            v = 0.2253385110212775E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4927563229773636E+0
+            b = 0.4190678003222840E+0
+            v = 0.2271137107548774E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5215687136707969E+0
+            b = 0.4483151836883852E+0
+            v = 0.2283414092917525E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5491402346984905E+0
+            b = 0.4764740676087880E+0
+            v = 0.2291161673130077E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5753520160126075E+0
+            b = 0.5034021310998277E+0
+            v = 0.2295313908576598E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1388326356417754E+0
+            b = 0.2435436510372806E-1
+            v = 0.1438204721359031E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1743686900537244E+0
+            b = 0.5118897057342652E-1
+            v = 0.1607738025495257E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2099737037950268E+0
+            b = 0.8014695048539634E-1
+            v = 0.1741483853528379E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2454492590908548E+0
+            b = 0.1105117874155699E+0
+            v = 0.1851918467519151E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2807219257864278E+0
+            b = 0.1417950531570966E+0
+            v = 0.1944628638070613E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3156842271975842E+0
+            b = 0.1736604945719597E+0
+            v = 0.2022495446275152E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3502090945177752E+0
+            b = 0.2058466324693981E+0
+            v = 0.2087462382438514E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3841684849519686E+0
+            b = 0.2381284261195919E+0
+            v = 0.2141074754818308E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4174372367906016E+0
+            b = 0.2703031270422569E+0
+            v = 0.2184640913748162E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4498926465011892E+0
+            b = 0.3021845683091309E+0
+            v = 0.2219309165220329E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4814146229807701E+0
+            b = 0.3335993355165720E+0
+            v = 0.2246123118340624E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5118863625734701E+0
+            b = 0.3643833735518232E+0
+            v = 0.2266062766915125E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5411947455119144E+0
+            b = 0.3943789541958179E+0
+            v = 0.2280072952230796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5692301500357246E+0
+            b = 0.4234320144403542E+0
+            v = 0.2289082025202583E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5958857204139576E+0
+            b = 0.4513897947419260E+0
+            v = 0.2294012695120025E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2156270284785766E+0
+            b = 0.2681225755444491E-1
+            v = 0.1722434488736947E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2532385054909710E+0
+            b = 0.5557495747805614E-1
+            v = 0.1830237421455091E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2902564617771537E+0
+            b = 0.8569368062950249E-1
+            v = 0.1923855349997633E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3266979823143256E+0
+            b = 0.1167367450324135E+0
+            v = 0.2004067861936271E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3625039627493614E+0
+            b = 0.1483861994003304E+0
+            v = 0.2071817297354263E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3975838937548699E+0
+            b = 0.1803821503011405E+0
+            v = 0.2128250834102103E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4318396099009774E+0
+            b = 0.2124962965666424E+0
+            v = 0.2174513719440102E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4651706555732742E+0
+            b = 0.2445221837805913E+0
+            v = 0.2211661839150214E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4974752649620969E+0
+            b = 0.2762701224322987E+0
+            v = 0.2240665257813102E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5286517579627517E+0
+            b = 0.3075627775211328E+0
+            v = 0.2262439516632620E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5586001195731895E+0
+            b = 0.3382311089826877E+0
+            v = 0.2277874557231869E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5872229902021319E+0
+            b = 0.3681108834741399E+0
+            v = 0.2287854314454994E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6144258616235123E+0
+            b = 0.3970397446872839E+0
+            v = 0.2293268499615575E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2951676508064861E+0
+            b = 0.2867499538750441E-1
+            v = 0.1912628201529828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3335085485472725E+0
+            b = 0.5867879341903510E-1
+            v = 0.1992499672238701E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3709561760636381E+0
+            b = 0.8961099205022284E-1
+            v = 0.2061275533454027E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4074722861667498E+0
+            b = 0.1211627927626297E+0
+            v = 0.2119318215968572E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4429923648839117E+0
+            b = 0.1530748903554898E+0
+            v = 0.2167416581882652E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4774428052721736E+0
+            b = 0.1851176436721877E+0
+            v = 0.2206430730516600E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5107446539535904E+0
+            b = 0.2170829107658179E+0
+            v = 0.2237186938699523E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5428151370542935E+0
+            b = 0.2487786689026271E+0
+            v = 0.2260480075032884E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5735699292556964E+0
+            b = 0.2800239952795016E+0
+            v = 0.2277098884558542E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6029253794562866E+0
+            b = 0.3106445702878119E+0
+            v = 0.2287845715109671E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6307998987073145E+0
+            b = 0.3404689500841194E+0
+            v = 0.2293547268236294E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3752652273692719E+0
+            b = 0.2997145098184479E-1
+            v = 0.2056073839852528E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4135383879344028E+0
+            b = 0.6086725898678011E-1
+            v = 0.2114235865831876E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4506113885153907E+0
+            b = 0.9238849548435643E-1
+            v = 0.2163175629770551E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4864401554606072E+0
+            b = 0.1242786603851851E+0
+            v = 0.2203392158111650E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5209708076611709E+0
+            b = 0.1563086731483386E+0
+            v = 0.2235473176847839E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5541422135830122E+0
+            b = 0.1882696509388506E+0
+            v = 0.2260024141501235E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5858880915113817E+0
+            b = 0.2199672979126059E+0
+            v = 0.2277675929329182E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6161399390603444E+0
+            b = 0.2512165482924867E+0
+            v = 0.2289102112284834E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6448296482255090E+0
+            b = 0.2818368701871888E+0
+            v = 0.2295027954625118E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4544796274917948E+0
+            b = 0.3088970405060312E-1
+            v = 0.2161281589879992E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4919389072146628E+0
+            b = 0.6240947677636835E-1
+            v = 0.2201980477395102E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5279313026985183E+0
+            b = 0.9430706144280313E-1
+            v = 0.2234952066593166E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5624169925571135E+0
+            b = 0.1263547818770374E+0
+            v = 0.2260540098520838E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5953484627093287E+0
+            b = 0.1583430788822594E+0
+            v = 0.2279157981899988E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6266730715339185E+0
+            b = 0.1900748462555988E+0
+            v = 0.2291296918565571E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6563363204278871E+0
+            b = 0.2213599519592567E+0
+            v = 0.2297533752536649E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5314574716585696E+0
+            b = 0.3152508811515374E-1
+            v = 0.2234927356465995E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5674614932298185E+0
+            b = 0.6343865291465561E-1
+            v = 0.2261288012985219E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6017706004970264E+0
+            b = 0.9551503504223951E-1
+            v = 0.2280818160923688E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6343471270264178E+0
+            b = 0.1275440099801196E+0
+            v = 0.2293773295180159E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6651494599127802E+0
+            b = 0.1593252037671960E+0
+            v = 0.2300528767338634E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6050184986005704E+0
+            b = 0.3192538338496105E-1
+            v = 0.2281893855065666E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6390163550880400E+0
+            b = 0.6402824353962306E-1
+            v = 0.2295720444840727E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6711199107088448E+0
+            b = 0.9609805077002909E-1
+            v = 0.2303227649026753E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6741354429572275E+0
+            b = 0.3211853196273233E-1
+            v = 0.2304831913227114E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 5294:
+
+            v = 0.9080510764308163E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2084824361987793E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2303261686261450E-1
+            v = 0.5011105657239616E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3757208620162394E-1
+            v = 0.5942520409683854E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5821912033821852E-1
+            v = 0.9564394826109721E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8403127529194872E-1
+            v = 0.1185530657126338E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1122927798060578E+0
+            v = 0.1364510114230331E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1420125319192987E+0
+            v = 0.1505828825605415E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1726396437341978E+0
+            v = 0.1619298749867023E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2038170058115696E+0
+            v = 0.1712450504267789E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2352849892876508E+0
+            v = 0.1789891098164999E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2668363354312461E+0
+            v = 0.1854474955629795E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2982941279900452E+0
+            v = 0.1908148636673661E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3295002922087076E+0
+            v = 0.1952377405281833E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3603094918363593E+0
+            v = 0.1988349254282232E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3905857895173920E+0
+            v = 0.2017079807160050E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4202005758160837E+0
+            v = 0.2039473082709094E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4490310061597227E+0
+            v = 0.2056360279288953E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4769586160311491E+0
+            v = 0.2068525823066865E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5038679887049750E+0
+            v = 0.2076724877534488E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5296454286519961E+0
+            v = 0.2081694278237885E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5541776207164850E+0
+            v = 0.2084157631219326E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5990467321921213E+0
+            v = 0.2084381531128593E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6191467096294587E+0
+            v = 0.2083476277129307E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6375251212901849E+0
+            v = 0.2082686194459732E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6540514381131168E+0
+            v = 0.2082475686112415E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6685899064391510E+0
+            v = 0.2083139860289915E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6810013009681648E+0
+            v = 0.2084745561831237E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6911469578730340E+0
+            v = 0.2087091313375890E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6988956915141736E+0
+            v = 0.2089718413297697E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7041335794868720E+0
+            v = 0.2092003303479793E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7067754398018567E+0
+            v = 0.2093336148263241E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3840368707853623E-1
+            v = 0.7591708117365267E-4
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9835485954117399E-1
+            v = 0.1083383968169186E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1665774947612998E+0
+            v = 0.1403019395292510E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2405702335362910E+0
+            v = 0.1615970179286436E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3165270770189046E+0
+            v = 0.1771144187504911E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3927386145645443E+0
+            v = 0.1887760022988168E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4678825918374656E+0
+            v = 0.1973474670768214E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5408022024266935E+0
+            v = 0.2033787661234659E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6104967445752438E+0
+            v = 0.2072343626517331E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6760910702685738E+0
+            v = 0.2091177834226918E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6655644120217392E-1
+            b = 0.1936508874588424E-1
+            v = 0.9316684484675566E-4
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9446246161270182E-1
+            b = 0.4252442002115869E-1
+            v = 0.1116193688682976E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1242651925452509E+0
+            b = 0.6806529315354374E-1
+            v = 0.1298623551559414E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1553438064846751E+0
+            b = 0.9560957491205369E-1
+            v = 0.1450236832456426E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1871137110542670E+0
+            b = 0.1245931657452888E+0
+            v = 0.1572719958149914E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2192612628836257E+0
+            b = 0.1545385828778978E+0
+            v = 0.1673234785867195E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2515682807206955E+0
+            b = 0.1851004249723368E+0
+            v = 0.1756860118725188E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2838535866287290E+0
+            b = 0.2160182608272384E+0
+            v = 0.1826776290439367E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3159578817528521E+0
+            b = 0.2470799012277111E+0
+            v = 0.1885116347992865E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3477370882791392E+0
+            b = 0.2781014208986402E+0
+            v = 0.1933457860170574E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3790576960890540E+0
+            b = 0.3089172523515731E+0
+            v = 0.1973060671902064E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4097938317810200E+0
+            b = 0.3393750055472244E+0
+            v = 0.2004987099616311E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4398256572859637E+0
+            b = 0.3693322470987730E+0
+            v = 0.2030170909281499E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4690384114718480E+0
+            b = 0.3986541005609877E+0
+            v = 0.2049461460119080E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4973216048301053E+0
+            b = 0.4272112491408562E+0
+            v = 0.2063653565200186E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5245681526132446E+0
+            b = 0.4548781735309936E+0
+            v = 0.2073507927381027E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5506733911803888E+0
+            b = 0.4815315355023251E+0
+            v = 0.2079764593256122E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5755339829522475E+0
+            b = 0.5070486445801855E+0
+            v = 0.2083150534968778E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1305472386056362E+0
+            b = 0.2284970375722366E-1
+            v = 0.1262715121590664E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1637327908216477E+0
+            b = 0.4812254338288384E-1
+            v = 0.1414386128545972E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1972734634149637E+0
+            b = 0.7531734457511935E-1
+            v = 0.1538740401313898E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2308694653110130E+0
+            b = 0.1039043639882017E+0
+            v = 0.1642434942331432E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2643899218338160E+0
+            b = 0.1334526587117626E+0
+            v = 0.1729790609237496E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2977171599622171E+0
+            b = 0.1636414868936382E+0
+            v = 0.1803505190260828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3307293903032310E+0
+            b = 0.1942195406166568E+0
+            v = 0.1865475350079657E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3633069198219073E+0
+            b = 0.2249752879943753E+0
+            v = 0.1917182669679069E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3953346955922727E+0
+            b = 0.2557218821820032E+0
+            v = 0.1959851709034382E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4267018394184914E+0
+            b = 0.2862897925213193E+0
+            v = 0.1994529548117882E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4573009622571704E+0
+            b = 0.3165224536636518E+0
+            v = 0.2022138911146548E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4870279559856109E+0
+            b = 0.3462730221636496E+0
+            v = 0.2043518024208592E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5157819581450322E+0
+            b = 0.3754016870282835E+0
+            v = 0.2059450313018110E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5434651666465393E+0
+            b = 0.4037733784993613E+0
+            v = 0.2070685715318472E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5699823887764627E+0
+            b = 0.4312557784139123E+0
+            v = 0.2077955310694373E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5952403350947741E+0
+            b = 0.4577175367122110E+0
+            v = 0.2081980387824712E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2025152599210369E+0
+            b = 0.2520253617719557E-1
+            v = 0.1521318610377956E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2381066653274425E+0
+            b = 0.5223254506119000E-1
+            v = 0.1622772720185755E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2732823383651612E+0
+            b = 0.8060669688588620E-1
+            v = 0.1710498139420709E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3080137692611118E+0
+            b = 0.1099335754081255E+0
+            v = 0.1785911149448736E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3422405614587601E+0
+            b = 0.1399120955959857E+0
+            v = 0.1850125313687736E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3758808773890420E+0
+            b = 0.1702977801651705E+0
+            v = 0.1904229703933298E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4088458383438932E+0
+            b = 0.2008799256601680E+0
+            v = 0.1949259956121987E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4410450550841152E+0
+            b = 0.2314703052180836E+0
+            v = 0.1986161545363960E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4723879420561312E+0
+            b = 0.2618972111375892E+0
+            v = 0.2015790585641370E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5027843561874343E+0
+            b = 0.2920013195600270E+0
+            v = 0.2038934198707418E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5321453674452458E+0
+            b = 0.3216322555190551E+0
+            v = 0.2056334060538251E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5603839113834030E+0
+            b = 0.3506456615934198E+0
+            v = 0.2068705959462289E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5874150706875146E+0
+            b = 0.3789007181306267E+0
+            v = 0.2076753906106002E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6131559381660038E+0
+            b = 0.4062580170572782E+0
+            v = 0.2081179391734803E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2778497016394506E+0
+            b = 0.2696271276876226E-1
+            v = 0.1700345216228943E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3143733562261912E+0
+            b = 0.5523469316960465E-1
+            v = 0.1774906779990410E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3501485810261827E+0
+            b = 0.8445193201626464E-1
+            v = 0.1839659377002642E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3851430322303653E+0
+            b = 0.1143263119336083E+0
+            v = 0.1894987462975169E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4193013979470415E+0
+            b = 0.1446177898344475E+0
+            v = 0.1941548809452595E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4525585960458567E+0
+            b = 0.1751165438438091E+0
+            v = 0.1980078427252384E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4848447779622947E+0
+            b = 0.2056338306745660E+0
+            v = 0.2011296284744488E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5160871208276894E+0
+            b = 0.2359965487229226E+0
+            v = 0.2035888456966776E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5462112185696926E+0
+            b = 0.2660430223139146E+0
+            v = 0.2054516325352142E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5751425068101757E+0
+            b = 0.2956193664498032E+0
+            v = 0.2067831033092635E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6028073872853596E+0
+            b = 0.3245763905312779E+0
+            v = 0.2076485320284876E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6291338275278409E+0
+            b = 0.3527670026206972E+0
+            v = 0.2081141439525255E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3541797528439391E+0
+            b = 0.2823853479435550E-1
+            v = 0.1834383015469222E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3908234972074657E+0
+            b = 0.5741296374713106E-1
+            v = 0.1889540591777677E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4264408450107590E+0
+            b = 0.8724646633650199E-1
+            v = 0.1936677023597375E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4609949666553286E+0
+            b = 0.1175034422915616E+0
+            v = 0.1976176495066504E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4944389496536006E+0
+            b = 0.1479755652628428E+0
+            v = 0.2008536004560983E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5267194884346086E+0
+            b = 0.1784740659484352E+0
+            v = 0.2034280351712291E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5577787810220990E+0
+            b = 0.2088245700431244E+0
+            v = 0.2053944466027758E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5875563763536670E+0
+            b = 0.2388628136570763E+0
+            v = 0.2068077642882360E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6159910016391269E+0
+            b = 0.2684308928769185E+0
+            v = 0.2077250949661599E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6430219602956268E+0
+            b = 0.2973740761960252E+0
+            v = 0.2082062440705320E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4300647036213646E+0
+            b = 0.2916399920493977E-1
+            v = 0.1934374486546626E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4661486308935531E+0
+            b = 0.5898803024755659E-1
+            v = 0.1974107010484300E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5009658555287261E+0
+            b = 0.8924162698525409E-1
+            v = 0.2007129290388658E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5344824270447704E+0
+            b = 0.1197185199637321E+0
+            v = 0.2033736947471293E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5666575997416371E+0
+            b = 0.1502300756161382E+0
+            v = 0.2054287125902493E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5974457471404752E+0
+            b = 0.1806004191913564E+0
+            v = 0.2069184936818894E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6267984444116886E+0
+            b = 0.2106621764786252E+0
+            v = 0.2078883689808782E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6546664713575417E+0
+            b = 0.2402526932671914E+0
+            v = 0.2083886366116359E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5042711004437253E+0
+            b = 0.2982529203607657E-1
+            v = 0.2006593275470817E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5392127456774380E+0
+            b = 0.6008728062339922E-1
+            v = 0.2033728426135397E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5726819437668618E+0
+            b = 0.9058227674571398E-1
+            v = 0.2055008781377608E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6046469254207278E+0
+            b = 0.1211219235803400E+0
+            v = 0.2070651783518502E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6350716157434952E+0
+            b = 0.1515286404791580E+0
+            v = 0.2080953335094320E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6639177679185454E+0
+            b = 0.1816314681255552E+0
+            v = 0.2086284998988521E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5757276040972253E+0
+            b = 0.3026991752575440E-1
+            v = 0.2055549387644668E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6090265823139755E+0
+            b = 0.6078402297870770E-1
+            v = 0.2071871850267654E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6406735344387661E+0
+            b = 0.9135459984176636E-1
+            v = 0.2082856600431965E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6706397927793709E+0
+            b = 0.1218024155966590E+0
+            v = 0.2088705858819358E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6435019674426665E+0
+            b = 0.3052608357660639E-1
+            v = 0.2083995867536322E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6747218676375681E+0
+            b = 0.6112185773983089E-1
+            v = 0.2090509712889637E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 5810:
+
+            v = 0.9735347946175486E-5
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1907581241803167E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.1901059546737578E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1182361662400277E-1
+            v = 0.3926424538919212E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3062145009138958E-1
+            v = 0.6667905467294382E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5329794036834243E-1
+            v = 0.8868891315019135E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7848165532862220E-1
+            v = 0.1066306000958872E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1054038157636201E+0
+            v = 0.1214506743336128E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1335577797766211E+0
+            v = 0.1338054681640871E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1625769955502252E+0
+            v = 0.1441677023628504E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1921787193412792E+0
+            v = 0.1528880200826557E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2221340534690548E+0
+            v = 0.1602330623773609E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2522504912791132E+0
+            v = 0.1664102653445244E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2823610860679697E+0
+            v = 0.1715845854011323E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3123173966267560E+0
+            v = 0.1758901000133069E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3419847036953789E+0
+            v = 0.1794382485256736E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3712386456999758E+0
+            v = 0.1823238106757407E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3999627649876828E+0
+            v = 0.1846293252959976E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4280466458648093E+0
+            v = 0.1864284079323098E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4553844360185711E+0
+            v = 0.1877882694626914E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4818736094437834E+0
+            v = 0.1887716321852025E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5074138709260629E+0
+            v = 0.1894381638175673E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5319061304570707E+0
+            v = 0.1898454899533629E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5552514978677286E+0
+            v = 0.1900497929577815E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5981009025246183E+0
+            v = 0.1900671501924092E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6173990192228116E+0
+            v = 0.1899837555533510E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6351365239411131E+0
+            v = 0.1899014113156229E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6512010228227200E+0
+            v = 0.1898581257705106E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6654758363948120E+0
+            v = 0.1898804756095753E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6778410414853370E+0
+            v = 0.1899793610426402E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6881760887484110E+0
+            v = 0.1901464554844117E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6963645267094598E+0
+            v = 0.1903533246259542E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7023010617153579E+0
+            v = 0.1905556158463228E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7059004636628753E+0
+            v = 0.1907037155663528E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3552470312472575E-1
+            v = 0.5992997844249967E-4
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9151176620841283E-1
+            v = 0.9749059382456978E-4
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1566197930068980E+0
+            v = 0.1241680804599158E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2265467599271907E+0
+            v = 0.1437626154299360E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2988242318581361E+0
+            v = 0.1584200054793902E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3717482419703886E+0
+            v = 0.1694436550982744E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4440094491758889E+0
+            v = 0.1776617014018108E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5145337096756642E+0
+            v = 0.1836132434440077E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5824053672860230E+0
+            v = 0.1876494727075983E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6468283961043370E+0
+            v = 0.1899906535336482E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6095964259104373E-1
+            b = 0.1787828275342931E-1
+            v = 0.8143252820767350E-4
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8811962270959388E-1
+            b = 0.3953888740792096E-1
+            v = 0.9998859890887728E-4
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1165936722428831E+0
+            b = 0.6378121797722990E-1
+            v = 0.1156199403068359E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1460232857031785E+0
+            b = 0.8985890813745037E-1
+            v = 0.1287632092635513E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1761197110181755E+0
+            b = 0.1172606510576162E+0
+            v = 0.1398378643365139E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2066471190463718E+0
+            b = 0.1456102876970995E+0
+            v = 0.1491876468417391E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2374076026328152E+0
+            b = 0.1746153823011775E+0
+            v = 0.1570855679175456E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2682305474337051E+0
+            b = 0.2040383070295584E+0
+            v = 0.1637483948103775E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2989653312142369E+0
+            b = 0.2336788634003698E+0
+            v = 0.1693500566632843E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3294762752772209E+0
+            b = 0.2633632752654219E+0
+            v = 0.1740322769393633E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3596390887276086E+0
+            b = 0.2929369098051601E+0
+            v = 0.1779126637278296E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3893383046398812E+0
+            b = 0.3222592785275512E+0
+            v = 0.1810908108835412E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4184653789358347E+0
+            b = 0.3512004791195743E+0
+            v = 0.1836529132600190E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4469172319076166E+0
+            b = 0.3796385677684537E+0
+            v = 0.1856752841777379E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4745950813276976E+0
+            b = 0.4074575378263879E+0
+            v = 0.1872270566606832E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5014034601410262E+0
+            b = 0.4345456906027828E+0
+            v = 0.1883722645591307E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5272493404551239E+0
+            b = 0.4607942515205134E+0
+            v = 0.1891714324525297E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5520413051846366E+0
+            b = 0.4860961284181720E+0
+            v = 0.1896827480450146E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5756887237503077E+0
+            b = 0.5103447395342790E+0
+            v = 0.1899628417059528E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1225039430588352E+0
+            b = 0.2136455922655793E-1
+            v = 0.1123301829001669E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1539113217321372E+0
+            b = 0.4520926166137188E-1
+            v = 0.1253698826711277E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1856213098637712E+0
+            b = 0.7086468177864818E-1
+            v = 0.1366266117678531E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2174998728035131E+0
+            b = 0.9785239488772918E-1
+            v = 0.1462736856106918E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2494128336938330E+0
+            b = 0.1258106396267210E+0
+            v = 0.1545076466685412E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2812321562143480E+0
+            b = 0.1544529125047001E+0
+            v = 0.1615096280814007E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3128372276456111E+0
+            b = 0.1835433512202753E+0
+            v = 0.1674366639741759E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3441145160177973E+0
+            b = 0.2128813258619585E+0
+            v = 0.1724225002437900E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3749567714853510E+0
+            b = 0.2422913734880829E+0
+            v = 0.1765810822987288E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4052621732015610E+0
+            b = 0.2716163748391453E+0
+            v = 0.1800104126010751E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4349335453522385E+0
+            b = 0.3007127671240280E+0
+            v = 0.1827960437331284E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4638776641524965E+0
+            b = 0.3294470677216479E+0
+            v = 0.1850140300716308E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4920046410462687E+0
+            b = 0.3576932543699155E+0
+            v = 0.1867333507394938E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5192273554861704E+0
+            b = 0.3853307059757764E+0
+            v = 0.1880178688638289E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5454609081136522E+0
+            b = 0.4122425044452694E+0
+            v = 0.1889278925654758E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5706220661424140E+0
+            b = 0.4383139587781027E+0
+            v = 0.1895213832507346E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5946286755181518E+0
+            b = 0.4634312536300553E+0
+            v = 0.1898548277397420E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1905370790924295E+0
+            b = 0.2371311537781979E-1
+            v = 0.1349105935937341E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2242518717748009E+0
+            b = 0.4917878059254806E-1
+            v = 0.1444060068369326E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2577190808025936E+0
+            b = 0.7595498960495142E-1
+            v = 0.1526797390930008E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2908724534927187E+0
+            b = 0.1036991083191100E+0
+            v = 0.1598208771406474E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3236354020056219E+0
+            b = 0.1321348584450234E+0
+            v = 0.1659354368615331E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3559267359304543E+0
+            b = 0.1610316571314789E+0
+            v = 0.1711279910946440E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3876637123676956E+0
+            b = 0.1901912080395707E+0
+            v = 0.1754952725601440E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4187636705218842E+0
+            b = 0.2194384950137950E+0
+            v = 0.1791247850802529E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4491449019883107E+0
+            b = 0.2486155334763858E+0
+            v = 0.1820954300877716E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4787270932425445E+0
+            b = 0.2775768931812335E+0
+            v = 0.1844788524548449E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5074315153055574E+0
+            b = 0.3061863786591120E+0
+            v = 0.1863409481706220E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5351810507738336E+0
+            b = 0.3343144718152556E+0
+            v = 0.1877433008795068E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5619001025975381E+0
+            b = 0.3618362729028427E+0
+            v = 0.1887444543705232E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5875144035268046E+0
+            b = 0.3886297583620408E+0
+            v = 0.1894009829375006E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6119507308734495E+0
+            b = 0.4145742277792031E+0
+            v = 0.1897683345035198E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2619733870119463E+0
+            b = 0.2540047186389353E-1
+            v = 0.1517327037467653E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2968149743237949E+0
+            b = 0.5208107018543989E-1
+            v = 0.1587740557483543E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3310451504860488E+0
+            b = 0.7971828470885599E-1
+            v = 0.1649093382274097E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3646215567376676E+0
+            b = 0.1080465999177927E+0
+            v = 0.1701915216193265E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3974916785279360E+0
+            b = 0.1368413849366629E+0
+            v = 0.1746847753144065E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4295967403772029E+0
+            b = 0.1659073184763559E+0
+            v = 0.1784555512007570E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4608742854473447E+0
+            b = 0.1950703730454614E+0
+            v = 0.1815687562112174E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4912598858949903E+0
+            b = 0.2241721144376724E+0
+            v = 0.1840864370663302E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5206882758945558E+0
+            b = 0.2530655255406489E+0
+            v = 0.1860676785390006E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5490940914019819E+0
+            b = 0.2816118409731066E+0
+            v = 0.1875690583743703E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5764123302025542E+0
+            b = 0.3096780504593238E+0
+            v = 0.1886453236347225E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6025786004213506E+0
+            b = 0.3371348366394987E+0
+            v = 0.1893501123329645E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6275291964794956E+0
+            b = 0.3638547827694396E+0
+            v = 0.1897366184519868E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3348189479861771E+0
+            b = 0.2664841935537443E-1
+            v = 0.1643908815152736E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3699515545855295E+0
+            b = 0.5424000066843495E-1
+            v = 0.1696300350907768E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4042003071474669E+0
+            b = 0.8251992715430854E-1
+            v = 0.1741553103844483E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4375320100182624E+0
+            b = 0.1112695182483710E+0
+            v = 0.1780015282386092E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4699054490335947E+0
+            b = 0.1402964116467816E+0
+            v = 0.1812116787077125E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5012739879431952E+0
+            b = 0.1694275117584291E+0
+            v = 0.1838323158085421E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5315874883754966E+0
+            b = 0.1985038235312689E+0
+            v = 0.1859113119837737E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5607937109622117E+0
+            b = 0.2273765660020893E+0
+            v = 0.1874969220221698E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5888393223495521E+0
+            b = 0.2559041492849764E+0
+            v = 0.1886375612681076E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6156705979160163E+0
+            b = 0.2839497251976899E+0
+            v = 0.1893819575809276E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6412338809078123E+0
+            b = 0.3113791060500690E+0
+            v = 0.1897794748256767E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4076051259257167E+0
+            b = 0.2757792290858463E-1
+            v = 0.1738963926584846E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4423788125791520E+0
+            b = 0.5584136834984293E-1
+            v = 0.1777442359873466E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4760480917328258E+0
+            b = 0.8457772087727143E-1
+            v = 0.1810010815068719E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5085838725946297E+0
+            b = 0.1135975846359248E+0
+            v = 0.1836920318248129E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5399513637391218E+0
+            b = 0.1427286904765053E+0
+            v = 0.1858489473214328E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5701118433636380E+0
+            b = 0.1718112740057635E+0
+            v = 0.1875079342496592E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5990240530606021E+0
+            b = 0.2006944855985351E+0
+            v = 0.1887080239102310E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6266452685139695E+0
+            b = 0.2292335090598907E+0
+            v = 0.1894905752176822E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6529320971415942E+0
+            b = 0.2572871512353714E+0
+            v = 0.1898991061200695E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4791583834610126E+0
+            b = 0.2826094197735932E-1
+            v = 0.1809065016458791E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5130373952796940E+0
+            b = 0.5699871359683649E-1
+            v = 0.1836297121596799E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5456252429628476E+0
+            b = 0.8602712528554394E-1
+            v = 0.1858426916241869E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5768956329682385E+0
+            b = 0.1151748137221281E+0
+            v = 0.1875654101134641E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6068186944699046E+0
+            b = 0.1442811654136362E+0
+            v = 0.1888240751833503E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6353622248024907E+0
+            b = 0.1731930321657680E+0
+            v = 0.1896497383866979E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6624927035731797E+0
+            b = 0.2017619958756061E+0
+            v = 0.1900775530219121E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5484933508028488E+0
+            b = 0.2874219755907391E-1
+            v = 0.1858525041478814E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5810207682142106E+0
+            b = 0.5778312123713695E-1
+            v = 0.1876248690077947E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6120955197181352E+0
+            b = 0.8695262371439526E-1
+            v = 0.1889404439064607E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6416944284294319E+0
+            b = 0.1160893767057166E+0
+            v = 0.1898168539265290E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6697926391731260E+0
+            b = 0.1450378826743251E+0
+            v = 0.1902779940661772E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6147594390585488E+0
+            b = 0.2904957622341456E-1
+            v = 0.1890125641731815E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6455390026356783E+0
+            b = 0.5823809152617197E-1
+            v = 0.1899434637795751E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6747258588365477E+0
+            b = 0.8740384899884715E-1
+            v = 0.1904520856831751E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6772135750395347E+0
+            b = 0.2919946135808105E-1
+            v = 0.1905534498734563E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case _:
+            raise Exception('Angular grid unrecognized, choices are 6, 14, 26, 38, 50, 74, 86, 110, 146, 170, 194, 230, 266, 302, 350, 434, 590, 770, 974, 1202, 1454, 1730, 2030, 2354, 2702, 3074, 3470, 3890, 4334, 4802, 5294, 5810')  # noqa: E501
+
+    leb_tmp.n = degree
+    return leb_tmp
+
+
+def get_lebedev_recurrence_points(type_, start, a, b, v, leb):
+    c = 0.0
+
+    match type_:
+
+        case 1:
+            a = 1.0
+
+            leb.x[start] = a
+            leb.y[start] = 0.0
+            leb.z[start] = 0.0
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = -a
+            leb.y[start + 1] = 0.0
+            leb.z[start + 1] = 0.0
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = 0.0
+            leb.y[start + 2] = a
+            leb.z[start + 2] = 0.0
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = 0.0
+            leb.y[start + 3] = -a
+            leb.z[start + 3] = 0.0
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = 0.0
+            leb.y[start + 4] = 0.0
+            leb.z[start + 4] = a
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = 0.0
+            leb.y[start + 5] = 0.0
+            leb.z[start + 5] = -a
+            leb.w[start + 5] = 4.0 * pi * v
+            start = start + 6
+
+        case 2:
+            a = sqrt(0.5)
+            leb.x[start] = 0.0
+            leb.y[start] = a
+            leb.z[start] = a
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = 0.0
+            leb.y[start + 1] = -a
+            leb.z[start + 1] = a
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = 0.0
+            leb.y[start + 2] = a
+            leb.z[start + 2] = -a
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = 0.0
+            leb.y[start + 3] = -a
+            leb.z[start + 3] = -a
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = a
+            leb.y[start + 4] = 0.0
+            leb.z[start + 4] = a
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = a
+            leb.y[start + 5] = 0.0
+            leb.z[start + 5] = -a
+            leb.w[start + 5] = 4.0 * pi * v
+
+            leb.x[start + 6] = -a
+            leb.y[start + 6] = 0.0
+            leb.z[start + 6] = a
+            leb.w[start + 6] = 4.0 * pi * v
+
+            leb.x[start + 7] = -a
+            leb.y[start + 7] = 0.0
+            leb.z[start + 7] = -a
+            leb.w[start + 7] = 4.0 * pi * v
+
+            leb.x[start + 8] = a
+            leb.y[start + 8] = a
+            leb.z[start + 8] = 0.0
+            leb.w[start + 8] = 4.0 * pi * v
+
+            leb.x[start + 9] = -a
+            leb.y[start + 9] = a
+            leb.z[start + 9] = 0.0
+            leb.w[start + 9] = 4.0 * pi * v
+
+            leb.x[start + 10] = a
+            leb.y[start + 10] = -a
+            leb.z[start + 10] = 0.0
+            leb.w[start + 10] = 4.0 * pi * v
+
+            leb.x[start + 11] = -a
+            leb.y[start + 11] = -a
+            leb.z[start + 11] = 0.0
+            leb.w[start + 11] = 4.0 * pi * v
+            start = start + 12
+
+        case 3:
+            a = sqrt(1.0 / 3.0)
+            leb.x[start] = a
+            leb.y[start] = a
+            leb.z[start] = a
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = -a
+            leb.y[start + 1] = a
+            leb.z[start + 1] = a
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = a
+            leb.y[start + 2] = -a
+            leb.z[start + 2] = a
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = a
+            leb.y[start + 3] = a
+            leb.z[start + 3] = -a
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = -a
+            leb.y[start + 4] = -a
+            leb.z[start + 4] = a
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = a
+            leb.y[start + 5] = -a
+            leb.z[start + 5] = -a
+            leb.w[start + 5] = 4.0 * pi * v
+
+            leb.x[start + 6] = -a
+            leb.y[start + 6] = a
+            leb.z[start + 6] = -a
+            leb.w[start + 6] = 4.0 * pi * v
+
+            leb.x[start + 7] = -a
+            leb.y[start + 7] = -a
+            leb.z[start + 7] = -a
+            leb.w[start + 7] = 4.0 * pi * v
+            start = start + 8
+
+        case 4:
+            # /* In this case A is inputed */
+            b = sqrt(1.0 - 2.0 * a * a)
+            leb.x[start] = a
+            leb.y[start] = a
+            leb.z[start] = b
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = -a
+            leb.y[start + 1] = a
+            leb.z[start + 1] = b
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = a
+            leb.y[start + 2] = -a
+            leb.z[start + 2] = b
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = a
+            leb.y[start + 3] = a
+            leb.z[start + 3] = -b
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = -a
+            leb.y[start + 4] = -a
+            leb.z[start + 4] = b
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = -a
+            leb.y[start + 5] = a
+            leb.z[start + 5] = -b
+            leb.w[start + 5] = 4.0 * pi * v
+
+            leb.x[start + 6] = a
+            leb.y[start + 6] = -a
+            leb.z[start + 6] = -b
+            leb.w[start + 6] = 4.0 * pi * v
+
+            leb.x[start + 7] = -a
+            leb.y[start + 7] = -a
+            leb.z[start + 7] = -b
+            leb.w[start + 7] = 4.0 * pi * v
+
+            leb.x[start + 8] = -a
+            leb.y[start + 8] = b
+            leb.z[start + 8] = a
+            leb.w[start + 8] = 4.0 * pi * v
+
+            leb.x[start + 9] = a
+            leb.y[start + 9] = -b
+            leb.z[start + 9] = a
+            leb.w[start + 9] = 4.0 * pi * v
+
+            leb.x[start + 10] = a
+            leb.y[start + 10] = b
+            leb.z[start + 10] = -a
+            leb.w[start + 10] = 4.0 * pi * v
+
+            leb.x[start + 11] = -a
+            leb.y[start + 11] = -b
+            leb.z[start + 11] = a
+            leb.w[start + 11] = 4.0 * pi * v
+
+            leb.x[start + 12] = -a
+            leb.y[start + 12] = b
+            leb.z[start + 12] = -a
+            leb.w[start + 12] = 4.0 * pi * v
+
+            leb.x[start + 13] = a
+            leb.y[start + 13] = -b
+            leb.z[start + 13] = -a
+            leb.w[start + 13] = 4.0 * pi * v
+
+            leb.x[start + 14] = -a
+            leb.y[start + 14] = -b
+            leb.z[start + 14] = -a
+            leb.w[start + 14] = 4.0 * pi * v
+
+            leb.x[start + 15] = a
+            leb.y[start + 15] = b
+            leb.z[start + 15] = a
+            leb.w[start + 15] = 4.0 * pi * v
+
+            leb.x[start + 16] = b
+            leb.y[start + 16] = a
+            leb.z[start + 16] = a
+            leb.w[start + 16] = 4.0 * pi * v
+
+            leb.x[start + 17] = -b
+            leb.y[start + 17] = a
+            leb.z[start + 17] = a
+            leb.w[start + 17] = 4.0 * pi * v
+
+            leb.x[start + 18] = b
+            leb.y[start + 18] = -a
+            leb.z[start + 18] = a
+            leb.w[start + 18] = 4.0 * pi * v
+
+            leb.x[start + 19] = b
+            leb.y[start + 19] = a
+            leb.z[start + 19] = -a
+            leb.w[start + 19] = 4.0 * pi * v
+
+            leb.x[start + 20] = -b
+            leb.y[start + 20] = -a
+            leb.z[start + 20] = a
+            leb.w[start + 20] = 4.0 * pi * v
+
+            leb.x[start + 21] = -b
+            leb.y[start + 21] = a
+            leb.z[start + 21] = -a
+            leb.w[start + 21] = 4.0 * pi * v
+
+            leb.x[start + 22] = b
+            leb.y[start + 22] = -a
+            leb.z[start + 22] = -a
+            leb.w[start + 22] = 4.0 * pi * v
+
+            leb.x[start + 23] = -b
+            leb.y[start + 23] = -a
+            leb.z[start + 23] = -a
+            leb.w[start + 23] = 4.0 * pi * v
+            start = start + 24
+
+        case 5:
+            # /* A is inputed in this case as well*/
+            b = sqrt(1 - a * a)
+            leb.x[start] = a
+            leb.y[start] = b
+            leb.z[start] = 0.0
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = -a
+            leb.y[start + 1] = b
+            leb.z[start + 1] = 0.0
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = a
+            leb.y[start + 2] = -b
+            leb.z[start + 2] = 0.0
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = -a
+            leb.y[start + 3] = -b
+            leb.z[start + 3] = 0.0
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = b
+            leb.y[start + 4] = a
+            leb.z[start + 4] = 0.0
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = -b
+            leb.y[start + 5] = a
+            leb.z[start + 5] = 0.0
+            leb.w[start + 5] = 4.0 * pi * v
+
+            leb.x[start + 6] = b
+            leb.y[start + 6] = -a
+            leb.z[start + 6] = 0.0
+            leb.w[start + 6] = 4.0 * pi * v
+
+            leb.x[start + 7] = -b
+            leb.y[start + 7] = -a
+            leb.z[start + 7] = 0.0
+            leb.w[start + 7] = 4.0 * pi * v
+
+            leb.x[start + 8] = a
+            leb.y[start + 8] = 0.0
+            leb.z[start + 8] = b
+            leb.w[start + 8] = 4.0 * pi * v
+
+            leb.x[start + 9] = -a
+            leb.y[start + 9] = 0.0
+            leb.z[start + 9] = b
+            leb.w[start + 9] = 4.0 * pi * v
+
+            leb.x[start + 10] = a
+            leb.y[start + 10] = 0.0
+            leb.z[start + 10] = -b
+            leb.w[start + 10] = 4.0 * pi * v
+
+            leb.x[start + 11] = -a
+            leb.y[start + 11] = 0.0
+            leb.z[start + 11] = -b
+            leb.w[start + 11] = 4.0 * pi * v
+
+            leb.x[start + 12] = b
+            leb.y[start + 12] = 0.0
+            leb.z[start + 12] = a
+            leb.w[start + 12] = 4.0 * pi * v
+
+            leb.x[start + 13] = -b
+            leb.y[start + 13] = 0.0
+            leb.z[start + 13] = a
+            leb.w[start + 13] = 4.0 * pi * v
+
+            leb.x[start + 14] = b
+            leb.y[start + 14] = 0.0
+            leb.z[start + 14] = -a
+            leb.w[start + 14] = 4.0 * pi * v
+
+            leb.x[start + 15] = -b
+            leb.y[start + 15] = 0.0
+            leb.z[start + 15] = -a
+            leb.w[start + 15] = 4.0 * pi * v
+
+            leb.x[start + 16] = 0.0
+            leb.y[start + 16] = a
+            leb.z[start + 16] = b
+            leb.w[start + 16] = 4.0 * pi * v
+
+            leb.x[start + 17] = 0.0
+            leb.y[start + 17] = -a
+            leb.z[start + 17] = b
+            leb.w[start + 17] = 4.0 * pi * v
+
+            leb.x[start + 18] = 0.0
+            leb.y[start + 18] = a
+            leb.z[start + 18] = -b
+            leb.w[start + 18] = 4.0 * pi * v
+
+            leb.x[start + 19] = 0.0
+            leb.y[start + 19] = -a
+            leb.z[start + 19] = -b
+            leb.w[start + 19] = 4.0 * pi * v
+
+            leb.x[start + 20] = 0.0
+            leb.y[start + 20] = b
+            leb.z[start + 20] = a
+            leb.w[start + 20] = 4.0 * pi * v
+
+            leb.x[start + 21] = 0.0
+            leb.y[start + 21] = -b
+            leb.z[start + 21] = a
+            leb.w[start + 21] = 4.0 * pi * v
+
+            leb.x[start + 22] = 0.0
+            leb.y[start + 22] = b
+            leb.z[start + 22] = -a
+            leb.w[start + 22] = 4.0 * pi * v
+
+            leb.x[start + 23] = 0.0
+            leb.y[start + 23] = -b
+            leb.z[start + 23] = -a
+            leb.w[start + 23] = 4.0 * pi * v
+            start = start + 24
+
+        case 6:
+            # /* both A and B are inputed in this case */
+            c = sqrt(1.0 - a * a - b * b)
+            leb.x[start] = a
+            leb.y[start] = b
+            leb.z[start] = c
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = -a
+            leb.y[start + 1] = b
+            leb.z[start + 1] = c
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = a
+            leb.y[start + 2] = -b
+            leb.z[start + 2] = c
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = a
+            leb.y[start + 3] = b
+            leb.z[start + 3] = -c
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = -a
+            leb.y[start + 4] = -b
+            leb.z[start + 4] = c
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = a
+            leb.y[start + 5] = -b
+            leb.z[start + 5] = -c
+            leb.w[start + 5] = 4.0 * pi * v
+
+            leb.x[start + 6] = -a
+            leb.y[start + 6] = b
+            leb.z[start + 6] = -c
+            leb.w[start + 6] = 4.0 * pi * v
+
+            leb.x[start + 7] = -a
+            leb.y[start + 7] = -b
+            leb.z[start + 7] = -c
+            leb.w[start + 7] = 4.0 * pi * v
+
+            leb.x[start + 8] = b
+            leb.y[start + 8] = a
+            leb.z[start + 8] = c
+            leb.w[start + 8] = 4.0 * pi * v
+
+            leb.x[start + 9] = -b
+            leb.y[start + 9] = a
+            leb.z[start + 9] = c
+            leb.w[start + 9] = 4.0 * pi * v
+
+            leb.x[start + 10] = b
+            leb.y[start + 10] = -a
+            leb.z[start + 10] = c
+            leb.w[start + 10] = 4.0 * pi * v
+
+            leb.x[start + 11] = b
+            leb.y[start + 11] = a
+            leb.z[start + 11] = -c
+            leb.w[start + 11] = 4.0 * pi * v
+
+            leb.x[start + 12] = -b
+            leb.y[start + 12] = -a
+            leb.z[start + 12] = c
+            leb.w[start + 12] = 4.0 * pi * v
+
+            leb.x[start + 13] = b
+            leb.y[start + 13] = -a
+            leb.z[start + 13] = -c
+            leb.w[start + 13] = 4.0 * pi * v
+
+            leb.x[start + 14] = -b
+            leb.y[start + 14] = a
+            leb.z[start + 14] = -c
+            leb.w[start + 14] = 4.0 * pi * v
+
+            leb.x[start + 15] = -b
+            leb.y[start + 15] = -a
+            leb.z[start + 15] = -c
+            leb.w[start + 15] = 4.0 * pi * v
+
+            leb.x[start + 16] = c
+            leb.y[start + 16] = a
+            leb.z[start + 16] = b
+            leb.w[start + 16] = 4.0 * pi * v
+
+            leb.x[start + 17] = -c
+            leb.y[start + 17] = a
+            leb.z[start + 17] = b
+            leb.w[start + 17] = 4.0 * pi * v
+
+            leb.x[start + 18] = c
+            leb.y[start + 18] = -a
+            leb.z[start + 18] = b
+            leb.w[start + 18] = 4.0 * pi * v
+
+            leb.x[start + 19] = c
+            leb.y[start + 19] = a
+            leb.z[start + 19] = -b
+            leb.w[start + 19] = 4.0 * pi * v
+
+            leb.x[start + 20] = -c
+            leb.y[start + 20] = -a
+            leb.z[start + 20] = b
+            leb.w[start + 20] = 4.0 * pi * v
+
+            leb.x[start + 21] = c
+            leb.y[start + 21] = -a
+            leb.z[start + 21] = -b
+            leb.w[start + 21] = 4.0 * pi * v
+
+            leb.x[start + 22] = -c
+            leb.y[start + 22] = a
+            leb.z[start + 22] = -b
+            leb.w[start + 22] = 4.0 * pi * v
+
+            leb.x[start + 23] = -c
+            leb.y[start + 23] = -a
+            leb.z[start + 23] = -b
+            leb.w[start + 23] = 4.0 * pi * v
+
+            leb.x[start + 24] = c
+            leb.y[start + 24] = b
+            leb.z[start + 24] = a
+            leb.w[start + 24] = 4.0 * pi * v
+
+            leb.x[start + 25] = -c
+            leb.y[start + 25] = b
+            leb.z[start + 25] = a
+            leb.w[start + 25] = 4.0 * pi * v
+
+            leb.x[start + 26] = c
+            leb.y[start + 26] = -b
+            leb.z[start + 26] = a
+            leb.w[start + 26] = 4.0 * pi * v
+
+            leb.x[start + 27] = c
+            leb.y[start + 27] = b
+            leb.z[start + 27] = -a
+            leb.w[start + 27] = 4.0 * pi * v
+
+            leb.x[start + 28] = -c
+            leb.y[start + 28] = -b
+            leb.z[start + 28] = a
+            leb.w[start + 28] = 4.0 * pi * v
+
+            leb.x[start + 29] = c
+            leb.y[start + 29] = -b
+            leb.z[start + 29] = -a
+            leb.w[start + 29] = 4.0 * pi * v
+
+            leb.x[start + 30] = -c
+            leb.y[start + 30] = b
+            leb.z[start + 30] = -a
+            leb.w[start + 30] = 4.0 * pi * v
+
+            leb.x[start + 31] = -c
+            leb.y[start + 31] = -b
+            leb.z[start + 31] = -a
+            leb.w[start + 31] = 4.0 * pi * v
+
+            leb.x[start + 32] = a
+            leb.y[start + 32] = c
+            leb.z[start + 32] = b
+            leb.w[start + 32] = 4.0 * pi * v
+
+            leb.x[start + 33] = -a
+            leb.y[start + 33] = c
+            leb.z[start + 33] = b
+            leb.w[start + 33] = 4.0 * pi * v
+
+            leb.x[start + 34] = a
+            leb.y[start + 34] = -c
+            leb.z[start + 34] = b
+            leb.w[start + 34] = 4.0 * pi * v
+
+            leb.x[start + 35] = a
+            leb.y[start + 35] = c
+            leb.z[start + 35] = -b
+            leb.w[start + 35] = 4.0 * pi * v
+
+            leb.x[start + 36] = -a
+            leb.y[start + 36] = -c
+            leb.z[start + 36] = b
+            leb.w[start + 36] = 4.0 * pi * v
+
+            leb.x[start + 37] = a
+            leb.y[start + 37] = -c
+            leb.z[start + 37] = -b
+            leb.w[start + 37] = 4.0 * pi * v
+
+            leb.x[start + 38] = -a
+            leb.y[start + 38] = c
+            leb.z[start + 38] = -b
+            leb.w[start + 38] = 4.0 * pi * v
+
+            leb.x[start + 39] = -a
+            leb.y[start + 39] = -c
+            leb.z[start + 39] = -b
+            leb.w[start + 39] = 4.0 * pi * v
+
+            leb.x[start + 40] = b
+            leb.y[start + 40] = c
+            leb.z[start + 40] = a
+            leb.w[start + 40] = 4.0 * pi * v
+
+            leb.x[start + 41] = -b
+            leb.y[start + 41] = c
+            leb.z[start + 41] = a
+            leb.w[start + 41] = 4.0 * pi * v
+
+            leb.x[start + 42] = b
+            leb.y[start + 42] = -c
+            leb.z[start + 42] = a
+            leb.w[start + 42] = 4.0 * pi * v
+
+            leb.x[start + 43] = b
+            leb.y[start + 43] = c
+            leb.z[start + 43] = -a
+            leb.w[start + 43] = 4.0 * pi * v
+
+            leb.x[start + 44] = -b
+            leb.y[start + 44] = -c
+            leb.z[start + 44] = a
+            leb.w[start + 44] = 4.0 * pi * v
+
+            leb.x[start + 45] = b
+            leb.y[start + 45] = -c
+            leb.z[start + 45] = -a
+            leb.w[start + 45] = 4.0 * pi * v
+
+            leb.x[start + 46] = -b
+            leb.y[start + 46] = c
+            leb.z[start + 46] = -a
+            leb.w[start + 46] = 4.0 * pi * v
+
+            leb.x[start + 47] = -b
+            leb.y[start + 47] = -c
+            leb.z[start + 47] = -a
+            leb.w[start + 47] = 4.0 * pi * v
+            start = start + 48
+
+        case _:
+            raise Exception('Bad grid order')
+
+    return leb, start
+
+
+def lebedev_rule(n):
+    r"""Lebedev quadrature.
+
+    Compute the sample points and weights for Lebedev quadrature [1]_
+    for integration of a function over the surface of a unit sphere.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order. See Notes for supported values.
+
+    Returns
+    -------
+    x : ndarray of shape ``(3, m)``
+        Sample points on the unit sphere in Cartesian coordinates.
+        ``m`` is the "degree" corresponding with the specified order; see Notes.
+    w : ndarray of shape ``(m,)``
+        Weights
+
+    Notes
+    -----
+    Implemented by translating the Matlab code of [2]_ to Python.
+
+    The available orders (argument `n`) are::
+
+        3, 5, 7, 9, 11, 13, 15, 17,
+        19, 21, 23, 25, 27, 29, 31, 35,
+        41, 47, 53, 59, 65, 71, 77, 83,
+        89, 95, 101, 107, 113, 119, 125, 131
+
+    The corresponding degrees ``m`` are::
+
+        6, 14, 26, 38, 50, 74, 86, 110,
+        146, 170, 194, 230, 266, 302, 350, 434,
+        590, 770, 974, 1202, 1454, 1730, 2030, 2354,
+        2702, 3074, 3470, 3890, 4334, 4802, 5294, 5810
+
+    References
+    ----------
+    .. [1] V.I. Lebedev, and D.N. Laikov. "A quadrature formula for the sphere of
+           the 131st algebraic order of accuracy". Doklady Mathematics, Vol. 59,
+           No. 3, 1999, pp. 477-481.
+    .. [2] R. Parrish. ``getLebedevSphere``. Matlab Central File Exchange.
+           https://www.mathworks.com/matlabcentral/fileexchange/27097-getlebedevsphere.
+    .. [3] Bellet, Jean-Baptiste, Matthieu Brachet, and Jean-Pierre Croisille.
+           "Quadrature and symmetry on the Cubed Sphere." Journal of Computational and
+           Applied Mathematics 409 (2022): 114142. :doi:`10.1016/j.cam.2022.114142`.
+
+    Examples
+    --------
+    An example given in [3]_ is integration of :math:`f(x, y, z) = \exp(x)` over a
+    sphere of radius :math:`1`; the reference there is ``14.7680137457653``.
+    Show the convergence to the expected result as the order increases:
+
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy as np
+    >>> from scipy.integrate import lebedev_rule
+    >>>
+    >>> def f(x):
+    ...     return np.exp(x[0])
+    >>>
+    >>> res = []
+    >>> orders = np.arange(3, 20, 2)
+    >>> for n in orders:
+    ...     x, w = lebedev_rule(n)
+    ...     res.append(w @ f(x))
+    >>>
+    >>> ref = np.full_like(res, 14.7680137457653)
+    >>> err = abs(res - ref)/abs(ref)
+    >>> plt.semilogy(orders, err)
+    >>> plt.xlabel('order $n$')
+    >>> plt.ylabel('relative error')
+    >>> plt.title(r'Convergence for $f(x, y, z) = \exp(x)$')
+    >>> plt.show()
+
+    """
+    degree = [6, 14, 26, 38, 50, 74, 86, 110, 146, 170, 194, 230, 266, 302, 350,
+              434, 590, 770, 974, 1202, 1454, 1730, 2030, 2354, 2702, 3074, 3470,
+              3890, 4334, 4802, 5294, 5810]
+    order = [3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 35, 41, 47,
+             53, 59, 65, 71, 77, 83, 89, 95, 101, 107, 113, 119, 125, 131]
+    order_degree_map = dict(zip(order, degree))
+
+    if n not in order_degree_map:
+        message = f"Order {n=} not available. Available orders are {order}."
+        raise NotImplementedError(message)
+
+    degree = order_degree_map[n]
+    res = get_lebedev_sphere(degree)
+    x = np.stack((res.x, res.y, res.z))
+    w = res.w
+
+    return x, w
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_lsoda.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_lsoda.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..b96e1f37e9a266d09b96aaffe18f35981efd5da8
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_lsoda.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c4ed8ce8abebcad0c463c00b8384ad1540864a8d63ab2136877ee6c108dafa01
+size 516881
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_ode.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_ode.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c1fff502c48803ba6e5460ae0a5e53605f84b04
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_ode.py
@@ -0,0 +1,1395 @@
+# Authors: Pearu Peterson, Pauli Virtanen, John Travers
+"""
+First-order ODE integrators.
+
+User-friendly interface to various numerical integrators for solving a
+system of first order ODEs with prescribed initial conditions::
+
+    d y(t)[i]
+    ---------  = f(t,y(t))[i],
+       d t
+
+    y(t=0)[i] = y0[i],
+
+where::
+
+    i = 0, ..., len(y0) - 1
+
+class ode
+---------
+
+A generic interface class to numeric integrators. It has the following
+methods::
+
+    integrator = ode(f, jac=None)
+    integrator = integrator.set_integrator(name, **params)
+    integrator = integrator.set_initial_value(y0, t0=0.0)
+    integrator = integrator.set_f_params(*args)
+    integrator = integrator.set_jac_params(*args)
+    y1 = integrator.integrate(t1, step=False, relax=False)
+    flag = integrator.successful()
+
+class complex_ode
+-----------------
+
+This class has the same generic interface as ode, except it can handle complex
+f, y and Jacobians by transparently translating them into the equivalent
+real-valued system. It supports the real-valued solvers (i.e., not zvode) and is
+an alternative to ode with the zvode solver, sometimes performing better.
+"""
+# XXX: Integrators must have:
+# ===========================
+# cvode - C version of vode and vodpk with many improvements.
+#   Get it from http://www.netlib.org/ode/cvode.tar.gz.
+#   To wrap cvode to Python, one must write the extension module by
+#   hand. Its interface is too much 'advanced C' that using f2py
+#   would be too complicated (or impossible).
+#
+# How to define a new integrator:
+# ===============================
+#
+# class myodeint(IntegratorBase):
+#
+#     runner =  or None
+#
+#     def __init__(self,...):                           # required
+#         
+#
+#     def reset(self,n,has_jac):                        # optional
+#         # n - the size of the problem (number of equations)
+#         # has_jac - whether user has supplied its own routine for Jacobian
+#         
+#
+#     def run(self,f,jac,y0,t0,t1,f_params,jac_params): # required
+#         # this method is called to integrate from t=t0 to t=t1
+#         # with initial condition y0. f and jac are user-supplied functions
+#         # that define the problem. f_params,jac_params are additional
+#         # arguments
+#         # to these functions.
+#         
+#         if :
+#             self.success = 0
+#         return t1,y1
+#
+#     # In addition, one can define step() and run_relax() methods (they
+#     # take the same arguments as run()) if the integrator can support
+#     # these features (see IntegratorBase doc strings).
+#
+# if myodeint.runner:
+#     IntegratorBase.integrator_classes.append(myodeint)
+
+__all__ = ['ode', 'complex_ode']
+
+import re
+import threading
+import warnings
+
+from numpy import asarray, array, zeros, isscalar, real, imag, vstack
+
+from . import _vode
+from . import _dop
+from . import _lsoda
+
+
+_dop_int_dtype = _dop.types.intvar.dtype
+_vode_int_dtype = _vode.types.intvar.dtype
+_lsoda_int_dtype = _lsoda.types.intvar.dtype
+
+
+# lsoda, vode and zvode are not thread-safe. VODE_LOCK protects both vode and
+# zvode; they share the `def run` implementation
+LSODA_LOCK = threading.Lock()
+VODE_LOCK = threading.Lock()
+
+
+# ------------------------------------------------------------------------------
+# User interface
+# ------------------------------------------------------------------------------
+
+
+class ode:
+    """
+    A generic interface class to numeric integrators.
+
+    Solve an equation system :math:`y'(t) = f(t,y)` with (optional) ``jac = df/dy``.
+
+    *Note*: The first two arguments of ``f(t, y, ...)`` are in the
+    opposite order of the arguments in the system definition function used
+    by `scipy.integrate.odeint`.
+
+    Parameters
+    ----------
+    f : callable ``f(t, y, *f_args)``
+        Right-hand side of the differential equation. t is a scalar,
+        ``y.shape == (n,)``.
+        ``f_args`` is set by calling ``set_f_params(*args)``.
+        `f` should return a scalar, array or list (not a tuple).
+    jac : callable ``jac(t, y, *jac_args)``, optional
+        Jacobian of the right-hand side, ``jac[i,j] = d f[i] / d y[j]``.
+        ``jac_args`` is set by calling ``set_jac_params(*args)``.
+
+    Attributes
+    ----------
+    t : float
+        Current time.
+    y : ndarray
+        Current variable values.
+
+    See also
+    --------
+    odeint : an integrator with a simpler interface based on lsoda from ODEPACK
+    quad : for finding the area under a curve
+
+    Notes
+    -----
+    Available integrators are listed below. They can be selected using
+    the `set_integrator` method.
+
+    "vode"
+
+        Real-valued Variable-coefficient Ordinary Differential Equation
+        solver, with fixed-leading-coefficient implementation. It provides
+        implicit Adams method (for non-stiff problems) and a method based on
+        backward differentiation formulas (BDF) (for stiff problems).
+
+        Source: http://www.netlib.org/ode/vode.f
+
+        .. warning::
+
+           This integrator is not re-entrant. You cannot have two `ode`
+           instances using the "vode" integrator at the same time.
+
+        This integrator accepts the following parameters in `set_integrator`
+        method of the `ode` class:
+
+        - atol : float or sequence
+          absolute tolerance for solution
+        - rtol : float or sequence
+          relative tolerance for solution
+        - lband : None or int
+        - uband : None or int
+          Jacobian band width, jac[i,j] != 0 for i-lband <= j <= i+uband.
+          Setting these requires your jac routine to return the jacobian
+          in packed format, jac_packed[i-j+uband, j] = jac[i,j]. The
+          dimension of the matrix must be (lband+uband+1, len(y)).
+        - method: 'adams' or 'bdf'
+          Which solver to use, Adams (non-stiff) or BDF (stiff)
+        - with_jacobian : bool
+          This option is only considered when the user has not supplied a
+          Jacobian function and has not indicated (by setting either band)
+          that the Jacobian is banded. In this case, `with_jacobian` specifies
+          whether the iteration method of the ODE solver's correction step is
+          chord iteration with an internally generated full Jacobian or
+          functional iteration with no Jacobian.
+        - nsteps : int
+          Maximum number of (internally defined) steps allowed during one
+          call to the solver.
+        - first_step : float
+        - min_step : float
+        - max_step : float
+          Limits for the step sizes used by the integrator.
+        - order : int
+          Maximum order used by the integrator,
+          order <= 12 for Adams, <= 5 for BDF.
+
+    "zvode"
+
+        Complex-valued Variable-coefficient Ordinary Differential Equation
+        solver, with fixed-leading-coefficient implementation. It provides
+        implicit Adams method (for non-stiff problems) and a method based on
+        backward differentiation formulas (BDF) (for stiff problems).
+
+        Source: http://www.netlib.org/ode/zvode.f
+
+        .. warning::
+
+           This integrator is not re-entrant. You cannot have two `ode`
+           instances using the "zvode" integrator at the same time.
+
+        This integrator accepts the same parameters in `set_integrator`
+        as the "vode" solver.
+
+        .. note::
+
+            When using ZVODE for a stiff system, it should only be used for
+            the case in which the function f is analytic, that is, when each f(i)
+            is an analytic function of each y(j). Analyticity means that the
+            partial derivative df(i)/dy(j) is a unique complex number, and this
+            fact is critical in the way ZVODE solves the dense or banded linear
+            systems that arise in the stiff case. For a complex stiff ODE system
+            in which f is not analytic, ZVODE is likely to have convergence
+            failures, and for this problem one should instead use DVODE on the
+            equivalent real system (in the real and imaginary parts of y).
+
+    "lsoda"
+
+        Real-valued Variable-coefficient Ordinary Differential Equation
+        solver, with fixed-leading-coefficient implementation. It provides
+        automatic method switching between implicit Adams method (for non-stiff
+        problems) and a method based on backward differentiation formulas (BDF)
+        (for stiff problems).
+
+        Source: http://www.netlib.org/odepack
+
+        .. warning::
+
+           This integrator is not re-entrant. You cannot have two `ode`
+           instances using the "lsoda" integrator at the same time.
+
+        This integrator accepts the following parameters in `set_integrator`
+        method of the `ode` class:
+
+        - atol : float or sequence
+          absolute tolerance for solution
+        - rtol : float or sequence
+          relative tolerance for solution
+        - lband : None or int
+        - uband : None or int
+          Jacobian band width, jac[i,j] != 0 for i-lband <= j <= i+uband.
+          Setting these requires your jac routine to return the jacobian
+          in packed format, jac_packed[i-j+uband, j] = jac[i,j].
+        - with_jacobian : bool
+          *Not used.*
+        - nsteps : int
+          Maximum number of (internally defined) steps allowed during one
+          call to the solver.
+        - first_step : float
+        - min_step : float
+        - max_step : float
+          Limits for the step sizes used by the integrator.
+        - max_order_ns : int
+          Maximum order used in the nonstiff case (default 12).
+        - max_order_s : int
+          Maximum order used in the stiff case (default 5).
+        - max_hnil : int
+          Maximum number of messages reporting too small step size (t + h = t)
+          (default 0)
+        - ixpr : int
+          Whether to generate extra printing at method switches (default False).
+
+    "dopri5"
+
+        This is an explicit runge-kutta method of order (4)5 due to Dormand &
+        Prince (with stepsize control and dense output).
+
+        Authors:
+
+            E. Hairer and G. Wanner
+            Universite de Geneve, Dept. de Mathematiques
+            CH-1211 Geneve 24, Switzerland
+            e-mail:  ernst.hairer@math.unige.ch, gerhard.wanner@math.unige.ch
+
+        This code is described in [HNW93]_.
+
+        This integrator accepts the following parameters in set_integrator()
+        method of the ode class:
+
+        - atol : float or sequence
+          absolute tolerance for solution
+        - rtol : float or sequence
+          relative tolerance for solution
+        - nsteps : int
+          Maximum number of (internally defined) steps allowed during one
+          call to the solver.
+        - first_step : float
+        - max_step : float
+        - safety : float
+          Safety factor on new step selection (default 0.9)
+        - ifactor : float
+        - dfactor : float
+          Maximum factor to increase/decrease step size by in one step
+        - beta : float
+          Beta parameter for stabilised step size control.
+        - verbosity : int
+          Switch for printing messages (< 0 for no messages).
+
+    "dop853"
+
+        This is an explicit runge-kutta method of order 8(5,3) due to Dormand
+        & Prince (with stepsize control and dense output).
+
+        Options and references the same as "dopri5".
+
+    Examples
+    --------
+
+    A problem to integrate and the corresponding jacobian:
+
+    >>> from scipy.integrate import ode
+    >>>
+    >>> y0, t0 = [1.0j, 2.0], 0
+    >>>
+    >>> def f(t, y, arg1):
+    ...     return [1j*arg1*y[0] + y[1], -arg1*y[1]**2]
+    >>> def jac(t, y, arg1):
+    ...     return [[1j*arg1, 1], [0, -arg1*2*y[1]]]
+
+    The integration:
+
+    >>> r = ode(f, jac).set_integrator('zvode', method='bdf')
+    >>> r.set_initial_value(y0, t0).set_f_params(2.0).set_jac_params(2.0)
+    >>> t1 = 10
+    >>> dt = 1
+    >>> while r.successful() and r.t < t1:
+    ...     print(r.t+dt, r.integrate(r.t+dt))
+    1 [-0.71038232+0.23749653j  0.40000271+0.j        ]
+    2.0 [0.19098503-0.52359246j 0.22222356+0.j        ]
+    3.0 [0.47153208+0.52701229j 0.15384681+0.j        ]
+    4.0 [-0.61905937+0.30726255j  0.11764744+0.j        ]
+    5.0 [0.02340997-0.61418799j 0.09523835+0.j        ]
+    6.0 [0.58643071+0.339819j 0.08000018+0.j      ]
+    7.0 [-0.52070105+0.44525141j  0.06896565+0.j        ]
+    8.0 [-0.15986733-0.61234476j  0.06060616+0.j        ]
+    9.0 [0.64850462+0.15048982j 0.05405414+0.j        ]
+    10.0 [-0.38404699+0.56382299j  0.04878055+0.j        ]
+
+    References
+    ----------
+    .. [HNW93] E. Hairer, S.P. Norsett and G. Wanner, Solving Ordinary
+        Differential Equations i. Nonstiff Problems. 2nd edition.
+        Springer Series in Computational Mathematics,
+        Springer-Verlag (1993)
+
+    """
+
+    def __init__(self, f, jac=None):
+        self.stiff = 0
+        self.f = f
+        self.jac = jac
+        self.f_params = ()
+        self.jac_params = ()
+        self._y = []
+
+    @property
+    def y(self):
+        return self._y
+
+    def set_initial_value(self, y, t=0.0):
+        """Set initial conditions y(t) = y."""
+        if isscalar(y):
+            y = [y]
+        n_prev = len(self._y)
+        if not n_prev:
+            self.set_integrator('')  # find first available integrator
+        self._y = asarray(y, self._integrator.scalar)
+        self.t = t
+        self._integrator.reset(len(self._y), self.jac is not None)
+        return self
+
+    def set_integrator(self, name, **integrator_params):
+        """
+        Set integrator by name.
+
+        Parameters
+        ----------
+        name : str
+            Name of the integrator.
+        **integrator_params
+            Additional parameters for the integrator.
+        """
+        integrator = find_integrator(name)
+        if integrator is None:
+            # FIXME: this really should be raise an exception. Will that break
+            # any code?
+            message = f'No integrator name match with {name!r} or is not available.'
+            warnings.warn(message, stacklevel=2)
+        else:
+            self._integrator = integrator(**integrator_params)
+            if not len(self._y):
+                self.t = 0.0
+                self._y = array([0.0], self._integrator.scalar)
+            self._integrator.reset(len(self._y), self.jac is not None)
+        return self
+
+    def integrate(self, t, step=False, relax=False):
+        """Find y=y(t), set y as an initial condition, and return y.
+
+        Parameters
+        ----------
+        t : float
+            The endpoint of the integration step.
+        step : bool
+            If True, and if the integrator supports the step method,
+            then perform a single integration step and return.
+            This parameter is provided in order to expose internals of
+            the implementation, and should not be changed from its default
+            value in most cases.
+        relax : bool
+            If True and if the integrator supports the run_relax method,
+            then integrate until t_1 >= t and return. ``relax`` is not
+            referenced if ``step=True``.
+            This parameter is provided in order to expose internals of
+            the implementation, and should not be changed from its default
+            value in most cases.
+
+        Returns
+        -------
+        y : float
+            The integrated value at t
+        """
+        if step and self._integrator.supports_step:
+            mth = self._integrator.step
+        elif relax and self._integrator.supports_run_relax:
+            mth = self._integrator.run_relax
+        else:
+            mth = self._integrator.run
+
+        try:
+            self._y, self.t = mth(self.f, self.jac or (lambda: None),
+                                  self._y, self.t, t,
+                                  self.f_params, self.jac_params)
+        except SystemError as e:
+            # f2py issue with tuple returns, see ticket 1187.
+            raise ValueError(
+                'Function to integrate must not return a tuple.'
+            ) from e
+
+        return self._y
+
+    def successful(self):
+        """Check if integration was successful."""
+        try:
+            self._integrator
+        except AttributeError:
+            self.set_integrator('')
+        return self._integrator.success == 1
+
+    def get_return_code(self):
+        """Extracts the return code for the integration to enable better control
+        if the integration fails.
+
+        In general, a return code > 0 implies success, while a return code < 0
+        implies failure.
+
+        Notes
+        -----
+        This section describes possible return codes and their meaning, for available
+        integrators that can be selected by `set_integrator` method.
+
+        "vode"
+
+        ===========  =======
+        Return Code  Message
+        ===========  =======
+        2            Integration successful.
+        -1           Excess work done on this call. (Perhaps wrong MF.)
+        -2           Excess accuracy requested. (Tolerances too small.)
+        -3           Illegal input detected. (See printed message.)
+        -4           Repeated error test failures. (Check all input.)
+        -5           Repeated convergence failures. (Perhaps bad Jacobian
+                     supplied or wrong choice of MF or tolerances.)
+        -6           Error weight became zero during problem. (Solution
+                     component i vanished, and ATOL or ATOL(i) = 0.)
+        ===========  =======
+
+        "zvode"
+
+        ===========  =======
+        Return Code  Message
+        ===========  =======
+        2            Integration successful.
+        -1           Excess work done on this call. (Perhaps wrong MF.)
+        -2           Excess accuracy requested. (Tolerances too small.)
+        -3           Illegal input detected. (See printed message.)
+        -4           Repeated error test failures. (Check all input.)
+        -5           Repeated convergence failures. (Perhaps bad Jacobian
+                     supplied or wrong choice of MF or tolerances.)
+        -6           Error weight became zero during problem. (Solution
+                     component i vanished, and ATOL or ATOL(i) = 0.)
+        ===========  =======
+
+        "dopri5"
+
+        ===========  =======
+        Return Code  Message
+        ===========  =======
+        1            Integration successful.
+        2            Integration successful (interrupted by solout).
+        -1           Input is not consistent.
+        -2           Larger nsteps is needed.
+        -3           Step size becomes too small.
+        -4           Problem is probably stiff (interrupted).
+        ===========  =======
+
+        "dop853"
+
+        ===========  =======
+        Return Code  Message
+        ===========  =======
+        1            Integration successful.
+        2            Integration successful (interrupted by solout).
+        -1           Input is not consistent.
+        -2           Larger nsteps is needed.
+        -3           Step size becomes too small.
+        -4           Problem is probably stiff (interrupted).
+        ===========  =======
+
+        "lsoda"
+
+        ===========  =======
+        Return Code  Message
+        ===========  =======
+        2            Integration successful.
+        -1           Excess work done on this call (perhaps wrong Dfun type).
+        -2           Excess accuracy requested (tolerances too small).
+        -3           Illegal input detected (internal error).
+        -4           Repeated error test failures (internal error).
+        -5           Repeated convergence failures (perhaps bad Jacobian or tolerances).
+        -6           Error weight became zero during problem.
+        -7           Internal workspace insufficient to finish (internal error).
+        ===========  =======
+        """
+        try:
+            self._integrator
+        except AttributeError:
+            self.set_integrator('')
+        return self._integrator.istate
+
+    def set_f_params(self, *args):
+        """Set extra parameters for user-supplied function f."""
+        self.f_params = args
+        return self
+
+    def set_jac_params(self, *args):
+        """Set extra parameters for user-supplied function jac."""
+        self.jac_params = args
+        return self
+
+    def set_solout(self, solout):
+        """
+        Set callable to be called at every successful integration step.
+
+        Parameters
+        ----------
+        solout : callable
+            ``solout(t, y)`` is called at each internal integrator step,
+            t is a scalar providing the current independent position
+            y is the current solution ``y.shape == (n,)``
+            solout should return -1 to stop integration
+            otherwise it should return None or 0
+
+        """
+        if self._integrator.supports_solout:
+            self._integrator.set_solout(solout)
+            if self._y is not None:
+                self._integrator.reset(len(self._y), self.jac is not None)
+        else:
+            raise ValueError("selected integrator does not support solout,"
+                             " choose another one")
+
+
+def _transform_banded_jac(bjac):
+    """
+    Convert a real matrix of the form (for example)
+
+        [0 0 A B]        [0 0 0 B]
+        [0 0 C D]        [0 0 A D]
+        [E F G H]   to   [0 F C H]
+        [I J K L]        [E J G L]
+                         [I 0 K 0]
+
+    That is, every other column is shifted up one.
+    """
+    # Shift every other column.
+    newjac = zeros((bjac.shape[0] + 1, bjac.shape[1]))
+    newjac[1:, ::2] = bjac[:, ::2]
+    newjac[:-1, 1::2] = bjac[:, 1::2]
+    return newjac
+
+
+class complex_ode(ode):
+    """
+    A wrapper of ode for complex systems.
+
+    This functions similarly as `ode`, but re-maps a complex-valued
+    equation system to a real-valued one before using the integrators.
+
+    Parameters
+    ----------
+    f : callable ``f(t, y, *f_args)``
+        Rhs of the equation. t is a scalar, ``y.shape == (n,)``.
+        ``f_args`` is set by calling ``set_f_params(*args)``.
+    jac : callable ``jac(t, y, *jac_args)``
+        Jacobian of the rhs, ``jac[i,j] = d f[i] / d y[j]``.
+        ``jac_args`` is set by calling ``set_f_params(*args)``.
+
+    Attributes
+    ----------
+    t : float
+        Current time.
+    y : ndarray
+        Current variable values.
+
+    Examples
+    --------
+    For usage examples, see `ode`.
+
+    """
+
+    def __init__(self, f, jac=None):
+        self.cf = f
+        self.cjac = jac
+        if jac is None:
+            ode.__init__(self, self._wrap, None)
+        else:
+            ode.__init__(self, self._wrap, self._wrap_jac)
+
+    def _wrap(self, t, y, *f_args):
+        f = self.cf(*((t, y[::2] + 1j * y[1::2]) + f_args))
+        # self.tmp is a real-valued array containing the interleaved
+        # real and imaginary parts of f.
+        self.tmp[::2] = real(f)
+        self.tmp[1::2] = imag(f)
+        return self.tmp
+
+    def _wrap_jac(self, t, y, *jac_args):
+        # jac is the complex Jacobian computed by the user-defined function.
+        jac = self.cjac(*((t, y[::2] + 1j * y[1::2]) + jac_args))
+
+        # jac_tmp is the real version of the complex Jacobian.  Each complex
+        # entry in jac, say 2+3j, becomes a 2x2 block of the form
+        #     [2 -3]
+        #     [3  2]
+        jac_tmp = zeros((2 * jac.shape[0], 2 * jac.shape[1]))
+        jac_tmp[1::2, 1::2] = jac_tmp[::2, ::2] = real(jac)
+        jac_tmp[1::2, ::2] = imag(jac)
+        jac_tmp[::2, 1::2] = -jac_tmp[1::2, ::2]
+
+        ml = getattr(self._integrator, 'ml', None)
+        mu = getattr(self._integrator, 'mu', None)
+        if ml is not None or mu is not None:
+            # Jacobian is banded.  The user's Jacobian function has computed
+            # the complex Jacobian in packed format.  The corresponding
+            # real-valued version has every other column shifted up.
+            jac_tmp = _transform_banded_jac(jac_tmp)
+
+        return jac_tmp
+
+    @property
+    def y(self):
+        return self._y[::2] + 1j * self._y[1::2]
+
+    def set_integrator(self, name, **integrator_params):
+        """
+        Set integrator by name.
+
+        Parameters
+        ----------
+        name : str
+            Name of the integrator
+        **integrator_params
+            Additional parameters for the integrator.
+        """
+        if name == 'zvode':
+            raise ValueError("zvode must be used with ode, not complex_ode")
+
+        lband = integrator_params.get('lband')
+        uband = integrator_params.get('uband')
+        if lband is not None or uband is not None:
+            # The Jacobian is banded.  Override the user-supplied bandwidths
+            # (which are for the complex Jacobian) with the bandwidths of
+            # the corresponding real-valued Jacobian wrapper of the complex
+            # Jacobian.
+            integrator_params['lband'] = 2 * (lband or 0) + 1
+            integrator_params['uband'] = 2 * (uband or 0) + 1
+
+        return ode.set_integrator(self, name, **integrator_params)
+
+    def set_initial_value(self, y, t=0.0):
+        """Set initial conditions y(t) = y."""
+        y = asarray(y)
+        self.tmp = zeros(y.size * 2, 'float')
+        self.tmp[::2] = real(y)
+        self.tmp[1::2] = imag(y)
+        return ode.set_initial_value(self, self.tmp, t)
+
+    def integrate(self, t, step=False, relax=False):
+        """Find y=y(t), set y as an initial condition, and return y.
+
+        Parameters
+        ----------
+        t : float
+            The endpoint of the integration step.
+        step : bool
+            If True, and if the integrator supports the step method,
+            then perform a single integration step and return.
+            This parameter is provided in order to expose internals of
+            the implementation, and should not be changed from its default
+            value in most cases.
+        relax : bool
+            If True and if the integrator supports the run_relax method,
+            then integrate until t_1 >= t and return. ``relax`` is not
+            referenced if ``step=True``.
+            This parameter is provided in order to expose internals of
+            the implementation, and should not be changed from its default
+            value in most cases.
+
+        Returns
+        -------
+        y : float
+            The integrated value at t
+        """
+        y = ode.integrate(self, t, step, relax)
+        return y[::2] + 1j * y[1::2]
+
+    def set_solout(self, solout):
+        """
+        Set callable to be called at every successful integration step.
+
+        Parameters
+        ----------
+        solout : callable
+            ``solout(t, y)`` is called at each internal integrator step,
+            t is a scalar providing the current independent position
+            y is the current solution ``y.shape == (n,)``
+            solout should return -1 to stop integration
+            otherwise it should return None or 0
+
+        """
+        if self._integrator.supports_solout:
+            self._integrator.set_solout(solout, complex=True)
+        else:
+            raise TypeError("selected integrator does not support solouta, "
+                            "choose another one")
+
+
+# ------------------------------------------------------------------------------
+# ODE integrators
+# ------------------------------------------------------------------------------
+
+def find_integrator(name):
+    for cl in IntegratorBase.integrator_classes:
+        if re.match(name, cl.__name__, re.I):
+            return cl
+    return None
+
+
+class IntegratorConcurrencyError(RuntimeError):
+    """
+    Failure due to concurrent usage of an integrator that can be used
+    only for a single problem at a time.
+
+    """
+
+    def __init__(self, name):
+        msg = (f"Integrator `{name}` can be used to solve only a single problem "
+                "at a time. If you want to integrate multiple problems, "
+                "consider using a different integrator (see `ode.set_integrator`)")
+        RuntimeError.__init__(self, msg)
+
+
+class IntegratorBase:
+    runner = None  # runner is None => integrator is not available
+    success = None  # success==1 if integrator was called successfully
+    istate = None  # istate > 0 means success, istate < 0 means failure
+    supports_run_relax = None
+    supports_step = None
+    supports_solout = False
+    integrator_classes = []
+    scalar = float
+
+    def acquire_new_handle(self):
+        # Some of the integrators have internal state (ancient
+        # Fortran...), and so only one instance can use them at a time.
+        # We keep track of this, and fail when concurrent usage is tried.
+        self.__class__.active_global_handle += 1
+        self.handle = self.__class__.active_global_handle
+
+    def check_handle(self):
+        if self.handle is not self.__class__.active_global_handle:
+            raise IntegratorConcurrencyError(self.__class__.__name__)
+
+    def reset(self, n, has_jac):
+        """Prepare integrator for call: allocate memory, set flags, etc.
+        n - number of equations.
+        has_jac - if user has supplied function for evaluating Jacobian.
+        """
+
+    def run(self, f, jac, y0, t0, t1, f_params, jac_params):
+        """Integrate from t=t0 to t=t1 using y0 as an initial condition.
+        Return 2-tuple (y1,t1) where y1 is the result and t=t1
+        defines the stoppage coordinate of the result.
+        """
+        raise NotImplementedError('all integrators must define '
+                                  'run(f, jac, t0, t1, y0, f_params, jac_params)')
+
+    def step(self, f, jac, y0, t0, t1, f_params, jac_params):
+        """Make one integration step and return (y1,t1)."""
+        raise NotImplementedError(f'{self.__class__.__name__} '
+                                  'does not support step() method')
+
+    def run_relax(self, f, jac, y0, t0, t1, f_params, jac_params):
+        """Integrate from t=t0 to t>=t1 and return (y1,t)."""
+        raise NotImplementedError(f'{self.__class__.__name__} '
+                                  'does not support run_relax() method')
+
+    # XXX: __str__ method for getting visual state of the integrator
+
+
+def _banded_jac_wrapper(jacfunc, ml, jac_params):
+    """
+    Wrap a banded Jacobian function with a function that pads
+    the Jacobian with `ml` rows of zeros.
+    """
+
+    def jac_wrapper(t, y):
+        jac = asarray(jacfunc(t, y, *jac_params))
+        padded_jac = vstack((jac, zeros((ml, jac.shape[1]))))
+        return padded_jac
+
+    return jac_wrapper
+
+
+class vode(IntegratorBase):
+    runner = getattr(_vode, 'dvode', None)
+
+    messages = {-1: 'Excess work done on this call. (Perhaps wrong MF.)',
+                -2: 'Excess accuracy requested. (Tolerances too small.)',
+                -3: 'Illegal input detected. (See printed message.)',
+                -4: 'Repeated error test failures. (Check all input.)',
+                -5: 'Repeated convergence failures. (Perhaps bad'
+                    ' Jacobian supplied or wrong choice of MF or tolerances.)',
+                -6: 'Error weight became zero during problem. (Solution'
+                    ' component i vanished, and ATOL or ATOL(i) = 0.)'
+                }
+    supports_run_relax = 1
+    supports_step = 1
+    active_global_handle = 0
+
+    def __init__(self,
+                 method='adams',
+                 with_jacobian=False,
+                 rtol=1e-6, atol=1e-12,
+                 lband=None, uband=None,
+                 order=12,
+                 nsteps=500,
+                 max_step=0.0,  # corresponds to infinite
+                 min_step=0.0,
+                 first_step=0.0,  # determined by solver
+                 ):
+
+        if re.match(method, r'adams', re.I):
+            self.meth = 1
+        elif re.match(method, r'bdf', re.I):
+            self.meth = 2
+        else:
+            raise ValueError(f'Unknown integration method {method}')
+        self.with_jacobian = with_jacobian
+        self.rtol = rtol
+        self.atol = atol
+        self.mu = uband
+        self.ml = lband
+
+        self.order = order
+        self.nsteps = nsteps
+        self.max_step = max_step
+        self.min_step = min_step
+        self.first_step = first_step
+        self.success = 1
+
+        self.initialized = False
+
+    def _determine_mf_and_set_bands(self, has_jac):
+        """
+        Determine the `MF` parameter (Method Flag) for the Fortran subroutine `dvode`.
+
+        In the Fortran code, the legal values of `MF` are:
+            10, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25,
+            -11, -12, -14, -15, -21, -22, -24, -25
+        but this Python wrapper does not use negative values.
+
+        Returns
+
+            mf  = 10*self.meth + miter
+
+        self.meth is the linear multistep method:
+            self.meth == 1:  method="adams"
+            self.meth == 2:  method="bdf"
+
+        miter is the correction iteration method:
+            miter == 0:  Functional iteration; no Jacobian involved.
+            miter == 1:  Chord iteration with user-supplied full Jacobian.
+            miter == 2:  Chord iteration with internally computed full Jacobian.
+            miter == 3:  Chord iteration with internally computed diagonal Jacobian.
+            miter == 4:  Chord iteration with user-supplied banded Jacobian.
+            miter == 5:  Chord iteration with internally computed banded Jacobian.
+
+        Side effects: If either self.mu or self.ml is not None and the other is None,
+        then the one that is None is set to 0.
+        """
+
+        jac_is_banded = self.mu is not None or self.ml is not None
+        if jac_is_banded:
+            if self.mu is None:
+                self.mu = 0
+            if self.ml is None:
+                self.ml = 0
+
+        # has_jac is True if the user provided a Jacobian function.
+        if has_jac:
+            if jac_is_banded:
+                miter = 4
+            else:
+                miter = 1
+        else:
+            if jac_is_banded:
+                if self.ml == self.mu == 0:
+                    miter = 3  # Chord iteration with internal diagonal Jacobian.
+                else:
+                    miter = 5  # Chord iteration with internal banded Jacobian.
+            else:
+                # self.with_jacobian is set by the user in
+                # the call to ode.set_integrator.
+                if self.with_jacobian:
+                    miter = 2  # Chord iteration with internal full Jacobian.
+                else:
+                    miter = 0  # Functional iteration; no Jacobian involved.
+
+        mf = 10 * self.meth + miter
+        return mf
+
+    def reset(self, n, has_jac):
+        mf = self._determine_mf_and_set_bands(has_jac)
+
+        if mf == 10:
+            lrw = 20 + 16 * n
+        elif mf in [11, 12]:
+            lrw = 22 + 16 * n + 2 * n * n
+        elif mf == 13:
+            lrw = 22 + 17 * n
+        elif mf in [14, 15]:
+            lrw = 22 + 18 * n + (3 * self.ml + 2 * self.mu) * n
+        elif mf == 20:
+            lrw = 20 + 9 * n
+        elif mf in [21, 22]:
+            lrw = 22 + 9 * n + 2 * n * n
+        elif mf == 23:
+            lrw = 22 + 10 * n
+        elif mf in [24, 25]:
+            lrw = 22 + 11 * n + (3 * self.ml + 2 * self.mu) * n
+        else:
+            raise ValueError(f'Unexpected mf={mf}')
+
+        if mf % 10 in [0, 3]:
+            liw = 30
+        else:
+            liw = 30 + n
+
+        rwork = zeros((lrw,), float)
+        rwork[4] = self.first_step
+        rwork[5] = self.max_step
+        rwork[6] = self.min_step
+        self.rwork = rwork
+
+        iwork = zeros((liw,), _vode_int_dtype)
+        if self.ml is not None:
+            iwork[0] = self.ml
+        if self.mu is not None:
+            iwork[1] = self.mu
+        iwork[4] = self.order
+        iwork[5] = self.nsteps
+        iwork[6] = 2  # mxhnil
+        self.iwork = iwork
+
+        self.call_args = [self.rtol, self.atol, 1, 1,
+                          self.rwork, self.iwork, mf]
+        self.success = 1
+        self.initialized = False
+
+    def run(self, f, jac, y0, t0, t1, f_params, jac_params):
+        if self.initialized:
+            self.check_handle()
+        else:
+            self.initialized = True
+            self.acquire_new_handle()
+
+        if self.ml is not None and self.ml > 0:
+            # Banded Jacobian. Wrap the user-provided function with one
+            # that pads the Jacobian array with the extra `self.ml` rows
+            # required by the f2py-generated wrapper.
+            jac = _banded_jac_wrapper(jac, self.ml, jac_params)
+
+        args = ((f, jac, y0, t0, t1) + tuple(self.call_args) +
+                (f_params, jac_params))
+
+        with VODE_LOCK:
+            y1, t, istate = self.runner(*args)
+
+        self.istate = istate
+        if istate < 0:
+            unexpected_istate_msg = f'Unexpected istate={istate:d}'
+            warnings.warn(f'{self.__class__.__name__:s}: '
+                          f'{self.messages.get(istate, unexpected_istate_msg):s}',
+                          stacklevel=2)
+            self.success = 0
+        else:
+            self.call_args[3] = 2  # upgrade istate from 1 to 2
+            self.istate = 2
+        return y1, t
+
+    def step(self, *args):
+        itask = self.call_args[2]
+        self.call_args[2] = 2
+        r = self.run(*args)
+        self.call_args[2] = itask
+        return r
+
+    def run_relax(self, *args):
+        itask = self.call_args[2]
+        self.call_args[2] = 3
+        r = self.run(*args)
+        self.call_args[2] = itask
+        return r
+
+
+if vode.runner is not None:
+    IntegratorBase.integrator_classes.append(vode)
+
+
+class zvode(vode):
+    runner = getattr(_vode, 'zvode', None)
+
+    supports_run_relax = 1
+    supports_step = 1
+    scalar = complex
+    active_global_handle = 0
+
+    def reset(self, n, has_jac):
+        mf = self._determine_mf_and_set_bands(has_jac)
+
+        if mf in (10,):
+            lzw = 15 * n
+        elif mf in (11, 12):
+            lzw = 15 * n + 2 * n ** 2
+        elif mf in (-11, -12):
+            lzw = 15 * n + n ** 2
+        elif mf in (13,):
+            lzw = 16 * n
+        elif mf in (14, 15):
+            lzw = 17 * n + (3 * self.ml + 2 * self.mu) * n
+        elif mf in (-14, -15):
+            lzw = 16 * n + (2 * self.ml + self.mu) * n
+        elif mf in (20,):
+            lzw = 8 * n
+        elif mf in (21, 22):
+            lzw = 8 * n + 2 * n ** 2
+        elif mf in (-21, -22):
+            lzw = 8 * n + n ** 2
+        elif mf in (23,):
+            lzw = 9 * n
+        elif mf in (24, 25):
+            lzw = 10 * n + (3 * self.ml + 2 * self.mu) * n
+        elif mf in (-24, -25):
+            lzw = 9 * n + (2 * self.ml + self.mu) * n
+
+        lrw = 20 + n
+
+        if mf % 10 in (0, 3):
+            liw = 30
+        else:
+            liw = 30 + n
+
+        zwork = zeros((lzw,), complex)
+        self.zwork = zwork
+
+        rwork = zeros((lrw,), float)
+        rwork[4] = self.first_step
+        rwork[5] = self.max_step
+        rwork[6] = self.min_step
+        self.rwork = rwork
+
+        iwork = zeros((liw,), _vode_int_dtype)
+        if self.ml is not None:
+            iwork[0] = self.ml
+        if self.mu is not None:
+            iwork[1] = self.mu
+        iwork[4] = self.order
+        iwork[5] = self.nsteps
+        iwork[6] = 2  # mxhnil
+        self.iwork = iwork
+
+        self.call_args = [self.rtol, self.atol, 1, 1,
+                          self.zwork, self.rwork, self.iwork, mf]
+        self.success = 1
+        self.initialized = False
+
+
+if zvode.runner is not None:
+    IntegratorBase.integrator_classes.append(zvode)
+
+
+class dopri5(IntegratorBase):
+    runner = getattr(_dop, 'dopri5', None)
+    name = 'dopri5'
+    supports_solout = True
+
+    messages = {1: 'computation successful',
+                2: 'computation successful (interrupted by solout)',
+                -1: 'input is not consistent',
+                -2: 'larger nsteps is needed',
+                -3: 'step size becomes too small',
+                -4: 'problem is probably stiff (interrupted)',
+                }
+
+    def __init__(self,
+                 rtol=1e-6, atol=1e-12,
+                 nsteps=500,
+                 max_step=0.0,
+                 first_step=0.0,  # determined by solver
+                 safety=0.9,
+                 ifactor=10.0,
+                 dfactor=0.2,
+                 beta=0.0,
+                 method=None,
+                 verbosity=-1,  # no messages if negative
+                 ):
+        self.rtol = rtol
+        self.atol = atol
+        self.nsteps = nsteps
+        self.max_step = max_step
+        self.first_step = first_step
+        self.safety = safety
+        self.ifactor = ifactor
+        self.dfactor = dfactor
+        self.beta = beta
+        self.verbosity = verbosity
+        self.success = 1
+        self.set_solout(None)
+
+    def set_solout(self, solout, complex=False):
+        self.solout = solout
+        self.solout_cmplx = complex
+        if solout is None:
+            self.iout = 0
+        else:
+            self.iout = 1
+
+    def reset(self, n, has_jac):
+        work = zeros((8 * n + 21,), float)
+        work[1] = self.safety
+        work[2] = self.dfactor
+        work[3] = self.ifactor
+        work[4] = self.beta
+        work[5] = self.max_step
+        work[6] = self.first_step
+        self.work = work
+        iwork = zeros((21,), _dop_int_dtype)
+        iwork[0] = self.nsteps
+        iwork[2] = self.verbosity
+        self.iwork = iwork
+        self.call_args = [self.rtol, self.atol, self._solout,
+                          self.iout, self.work, self.iwork]
+        self.success = 1
+
+    def run(self, f, jac, y0, t0, t1, f_params, jac_params):
+        x, y, iwork, istate = self.runner(*((f, t0, y0, t1) +
+                                          tuple(self.call_args) + (f_params,)))
+        self.istate = istate
+        if istate < 0:
+            unexpected_istate_msg = f'Unexpected istate={istate:d}'
+            warnings.warn(f'{self.__class__.__name__:s}: '
+                          f'{self.messages.get(istate, unexpected_istate_msg):s}',
+                          stacklevel=2)
+            self.success = 0
+        return y, x
+
+    def _solout(self, nr, xold, x, y, nd, icomp, con):
+        if self.solout is not None:
+            if self.solout_cmplx:
+                y = y[::2] + 1j * y[1::2]
+            return self.solout(x, y)
+        else:
+            return 1
+
+
+if dopri5.runner is not None:
+    IntegratorBase.integrator_classes.append(dopri5)
+
+
+class dop853(dopri5):
+    runner = getattr(_dop, 'dop853', None)
+    name = 'dop853'
+
+    def __init__(self,
+                 rtol=1e-6, atol=1e-12,
+                 nsteps=500,
+                 max_step=0.0,
+                 first_step=0.0,  # determined by solver
+                 safety=0.9,
+                 ifactor=6.0,
+                 dfactor=0.3,
+                 beta=0.0,
+                 method=None,
+                 verbosity=-1,  # no messages if negative
+                 ):
+        super().__init__(rtol, atol, nsteps, max_step, first_step, safety,
+                         ifactor, dfactor, beta, method, verbosity)
+
+    def reset(self, n, has_jac):
+        work = zeros((11 * n + 21,), float)
+        work[1] = self.safety
+        work[2] = self.dfactor
+        work[3] = self.ifactor
+        work[4] = self.beta
+        work[5] = self.max_step
+        work[6] = self.first_step
+        self.work = work
+        iwork = zeros((21,), _dop_int_dtype)
+        iwork[0] = self.nsteps
+        iwork[2] = self.verbosity
+        self.iwork = iwork
+        self.call_args = [self.rtol, self.atol, self._solout,
+                          self.iout, self.work, self.iwork]
+        self.success = 1
+
+
+if dop853.runner is not None:
+    IntegratorBase.integrator_classes.append(dop853)
+
+
+class lsoda(IntegratorBase):
+    runner = getattr(_lsoda, 'lsoda', None)
+    active_global_handle = 0
+
+    messages = {
+        2: "Integration successful.",
+        -1: "Excess work done on this call (perhaps wrong Dfun type).",
+        -2: "Excess accuracy requested (tolerances too small).",
+        -3: "Illegal input detected (internal error).",
+        -4: "Repeated error test failures (internal error).",
+        -5: "Repeated convergence failures (perhaps bad Jacobian or tolerances).",
+        -6: "Error weight became zero during problem.",
+        -7: "Internal workspace insufficient to finish (internal error)."
+    }
+
+    def __init__(self,
+                 with_jacobian=False,
+                 rtol=1e-6, atol=1e-12,
+                 lband=None, uband=None,
+                 nsteps=500,
+                 max_step=0.0,  # corresponds to infinite
+                 min_step=0.0,
+                 first_step=0.0,  # determined by solver
+                 ixpr=0,
+                 max_hnil=0,
+                 max_order_ns=12,
+                 max_order_s=5,
+                 method=None
+                 ):
+
+        self.with_jacobian = with_jacobian
+        self.rtol = rtol
+        self.atol = atol
+        self.mu = uband
+        self.ml = lband
+
+        self.max_order_ns = max_order_ns
+        self.max_order_s = max_order_s
+        self.nsteps = nsteps
+        self.max_step = max_step
+        self.min_step = min_step
+        self.first_step = first_step
+        self.ixpr = ixpr
+        self.max_hnil = max_hnil
+        self.success = 1
+
+        self.initialized = False
+
+    def reset(self, n, has_jac):
+        # Calculate parameters for Fortran subroutine dvode.
+        if has_jac:
+            if self.mu is None and self.ml is None:
+                jt = 1
+            else:
+                if self.mu is None:
+                    self.mu = 0
+                if self.ml is None:
+                    self.ml = 0
+                jt = 4
+        else:
+            if self.mu is None and self.ml is None:
+                jt = 2
+            else:
+                if self.mu is None:
+                    self.mu = 0
+                if self.ml is None:
+                    self.ml = 0
+                jt = 5
+        lrn = 20 + (self.max_order_ns + 4) * n
+        if jt in [1, 2]:
+            lrs = 22 + (self.max_order_s + 4) * n + n * n
+        elif jt in [4, 5]:
+            lrs = 22 + (self.max_order_s + 5 + 2 * self.ml + self.mu) * n
+        else:
+            raise ValueError(f'Unexpected jt={jt}')
+        lrw = max(lrn, lrs)
+        liw = 20 + n
+        rwork = zeros((lrw,), float)
+        rwork[4] = self.first_step
+        rwork[5] = self.max_step
+        rwork[6] = self.min_step
+        self.rwork = rwork
+        iwork = zeros((liw,), _lsoda_int_dtype)
+        if self.ml is not None:
+            iwork[0] = self.ml
+        if self.mu is not None:
+            iwork[1] = self.mu
+        iwork[4] = self.ixpr
+        iwork[5] = self.nsteps
+        iwork[6] = self.max_hnil
+        iwork[7] = self.max_order_ns
+        iwork[8] = self.max_order_s
+        self.iwork = iwork
+        self.call_args = [self.rtol, self.atol, 1, 1,
+                          self.rwork, self.iwork, jt]
+        self.success = 1
+        self.initialized = False
+
+    def run(self, f, jac, y0, t0, t1, f_params, jac_params):
+        if self.initialized:
+            self.check_handle()
+        else:
+            self.initialized = True
+            self.acquire_new_handle()
+
+        if jac is not None and self.ml is not None and self.ml > 0:
+            # Banded Jacobian. Wrap the user-provided function with one
+            # that pads the Jacobian array with the extra `self.ml` rows
+            # required by the f2py-generated wrapper.
+            jac = _banded_jac_wrapper(jac, self.ml, jac_params)
+
+        args = [f, y0, t0, t1] + self.call_args[:-1] + \
+               [jac, self.call_args[-1], f_params, 0, jac_params]
+
+        with LSODA_LOCK:
+            y1, t, istate = self.runner(*args)
+
+        self.istate = istate
+        if istate < 0:
+            unexpected_istate_msg = f'Unexpected istate={istate:d}'
+            warnings.warn(f'{self.__class__.__name__:s}: '
+                          f'{self.messages.get(istate, unexpected_istate_msg):s}',
+                          stacklevel=2)
+            self.success = 0
+        else:
+            self.call_args[3] = 2  # upgrade istate from 1 to 2
+            self.istate = 2
+        return y1, t
+
+    def step(self, *args):
+        itask = self.call_args[2]
+        self.call_args[2] = 2
+        r = self.run(*args)
+        self.call_args[2] = itask
+        return r
+
+    def run_relax(self, *args):
+        itask = self.call_args[2]
+        self.call_args[2] = 3
+        r = self.run(*args)
+        self.call_args[2] = itask
+        return r
+
+
+if lsoda.runner:
+    IntegratorBase.integrator_classes.append(lsoda)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_odepack.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_odepack.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..788129cb32c16a73cd72947c2855768d7bcf199a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_odepack.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:157269fe88cd78f001896f4af6206bbaca0661d77f0b2877be367bad12e2fdb4
+size 479121
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_odepack_py.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_odepack_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..75dfe925b312ae609d19ccbec27927c6c945176f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_odepack_py.py
@@ -0,0 +1,273 @@
+# Author: Travis Oliphant
+
+__all__ = ['odeint', 'ODEintWarning']
+
+import numpy as np
+from . import _odepack
+from copy import copy
+import warnings
+
+from threading import Lock
+
+
+ODE_LOCK = Lock()
+
+
+class ODEintWarning(Warning):
+    """Warning raised during the execution of `odeint`."""
+    pass
+
+
+_msgs = {2: "Integration successful.",
+         1: "Nothing was done; the integration time was 0.",
+         -1: "Excess work done on this call (perhaps wrong Dfun type).",
+         -2: "Excess accuracy requested (tolerances too small).",
+         -3: "Illegal input detected (internal error).",
+         -4: "Repeated error test failures (internal error).",
+         -5: "Repeated convergence failures (perhaps bad Jacobian or tolerances).",
+         -6: "Error weight became zero during problem.",
+         -7: "Internal workspace insufficient to finish (internal error).",
+         -8: "Run terminated (internal error)."
+         }
+
+
+def odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0,
+           ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=0.0,
+           hmax=0.0, hmin=0.0, ixpr=0, mxstep=0, mxhnil=0, mxordn=12,
+           mxords=5, printmessg=0, tfirst=False):
+    """
+    Integrate a system of ordinary differential equations.
+
+    .. note:: For new code, use `scipy.integrate.solve_ivp` to solve a
+              differential equation.
+
+    Solve a system of ordinary differential equations using lsoda from the
+    FORTRAN library odepack.
+
+    Solves the initial value problem for stiff or non-stiff systems
+    of first order ode-s::
+
+        dy/dt = func(y, t, ...)  [or func(t, y, ...)]
+
+    where y can be a vector.
+
+    .. note:: By default, the required order of the first two arguments of
+              `func` are in the opposite order of the arguments in the system
+              definition function used by the `scipy.integrate.ode` class and
+              the function `scipy.integrate.solve_ivp`. To use a function with
+              the signature ``func(t, y, ...)``, the argument `tfirst` must be
+              set to ``True``.
+
+    Parameters
+    ----------
+    func : callable(y, t, ...) or callable(t, y, ...)
+        Computes the derivative of y at t.
+        If the signature is ``callable(t, y, ...)``, then the argument
+        `tfirst` must be set ``True``.
+        `func` must not modify the data in `y`, as it is a
+        view of the data used internally by the ODE solver.
+    y0 : array
+        Initial condition on y (can be a vector).
+    t : array
+        A sequence of time points for which to solve for y. The initial
+        value point should be the first element of this sequence.
+        This sequence must be monotonically increasing or monotonically
+        decreasing; repeated values are allowed.
+    args : tuple, optional
+        Extra arguments to pass to function.
+    Dfun : callable(y, t, ...) or callable(t, y, ...)
+        Gradient (Jacobian) of `func`.
+        If the signature is ``callable(t, y, ...)``, then the argument
+        `tfirst` must be set ``True``.
+        `Dfun` must not modify the data in `y`, as it is a
+        view of the data used internally by the ODE solver.
+    col_deriv : bool, optional
+        True if `Dfun` defines derivatives down columns (faster),
+        otherwise `Dfun` should define derivatives across rows.
+    full_output : bool, optional
+        True if to return a dictionary of optional outputs as the second output
+    printmessg : bool, optional
+        Whether to print the convergence message
+    tfirst : bool, optional
+        If True, the first two arguments of `func` (and `Dfun`, if given)
+        must ``t, y`` instead of the default ``y, t``.
+
+        .. versionadded:: 1.1.0
+
+    Returns
+    -------
+    y : array, shape (len(t), len(y0))
+        Array containing the value of y for each desired time in t,
+        with the initial value `y0` in the first row.
+    infodict : dict, only returned if full_output == True
+        Dictionary containing additional output information
+
+        =======  ============================================================
+        key      meaning
+        =======  ============================================================
+        'hu'     vector of step sizes successfully used for each time step
+        'tcur'   vector with the value of t reached for each time step
+                 (will always be at least as large as the input times)
+        'tolsf'  vector of tolerance scale factors, greater than 1.0,
+                 computed when a request for too much accuracy was detected
+        'tsw'    value of t at the time of the last method switch
+                 (given for each time step)
+        'nst'    cumulative number of time steps
+        'nfe'    cumulative number of function evaluations for each time step
+        'nje'    cumulative number of jacobian evaluations for each time step
+        'nqu'    a vector of method orders for each successful step
+        'imxer'  index of the component of largest magnitude in the
+                 weighted local error vector (e / ewt) on an error return, -1
+                 otherwise
+        'lenrw'  the length of the double work array required
+        'leniw'  the length of integer work array required
+        'mused'  a vector of method indicators for each successful time step:
+                 1: adams (nonstiff), 2: bdf (stiff)
+        =======  ============================================================
+
+    Other Parameters
+    ----------------
+    ml, mu : int, optional
+        If either of these are not None or non-negative, then the
+        Jacobian is assumed to be banded. These give the number of
+        lower and upper non-zero diagonals in this banded matrix.
+        For the banded case, `Dfun` should return a matrix whose
+        rows contain the non-zero bands (starting with the lowest diagonal).
+        Thus, the return matrix `jac` from `Dfun` should have shape
+        ``(ml + mu + 1, len(y0))`` when ``ml >=0`` or ``mu >=0``.
+        The data in `jac` must be stored such that ``jac[i - j + mu, j]``
+        holds the derivative of the ``i``\\ th equation with respect to the
+        ``j``\\ th state variable.  If `col_deriv` is True, the transpose of
+        this `jac` must be returned.
+    rtol, atol : float, optional
+        The input parameters `rtol` and `atol` determine the error
+        control performed by the solver.  The solver will control the
+        vector, e, of estimated local errors in y, according to an
+        inequality of the form ``max-norm of (e / ewt) <= 1``,
+        where ewt is a vector of positive error weights computed as
+        ``ewt = rtol * abs(y) + atol``.
+        rtol and atol can be either vectors the same length as y or scalars.
+        Defaults to 1.49012e-8.
+    tcrit : ndarray, optional
+        Vector of critical points (e.g., singularities) where integration
+        care should be taken.
+    h0 : float, (0: solver-determined), optional
+        The step size to be attempted on the first step.
+    hmax : float, (0: solver-determined), optional
+        The maximum absolute step size allowed.
+    hmin : float, (0: solver-determined), optional
+        The minimum absolute step size allowed.
+    ixpr : bool, optional
+        Whether to generate extra printing at method switches.
+    mxstep : int, (0: solver-determined), optional
+        Maximum number of (internally defined) steps allowed for each
+        integration point in t.
+    mxhnil : int, (0: solver-determined), optional
+        Maximum number of messages printed.
+    mxordn : int, (0: solver-determined), optional
+        Maximum order to be allowed for the non-stiff (Adams) method.
+    mxords : int, (0: solver-determined), optional
+        Maximum order to be allowed for the stiff (BDF) method.
+
+    See Also
+    --------
+    solve_ivp : solve an initial value problem for a system of ODEs
+    ode : a more object-oriented integrator based on VODE
+    quad : for finding the area under a curve
+
+    Examples
+    --------
+    The second order differential equation for the angle `theta` of a
+    pendulum acted on by gravity with friction can be written::
+
+        theta''(t) + b*theta'(t) + c*sin(theta(t)) = 0
+
+    where `b` and `c` are positive constants, and a prime (') denotes a
+    derivative. To solve this equation with `odeint`, we must first convert
+    it to a system of first order equations. By defining the angular
+    velocity ``omega(t) = theta'(t)``, we obtain the system::
+
+        theta'(t) = omega(t)
+        omega'(t) = -b*omega(t) - c*sin(theta(t))
+
+    Let `y` be the vector [`theta`, `omega`]. We implement this system
+    in Python as:
+
+    >>> import numpy as np
+    >>> def pend(y, t, b, c):
+    ...     theta, omega = y
+    ...     dydt = [omega, -b*omega - c*np.sin(theta)]
+    ...     return dydt
+    ...
+
+    We assume the constants are `b` = 0.25 and `c` = 5.0:
+
+    >>> b = 0.25
+    >>> c = 5.0
+
+    For initial conditions, we assume the pendulum is nearly vertical
+    with `theta(0)` = `pi` - 0.1, and is initially at rest, so
+    `omega(0)` = 0.  Then the vector of initial conditions is
+
+    >>> y0 = [np.pi - 0.1, 0.0]
+
+    We will generate a solution at 101 evenly spaced samples in the interval
+    0 <= `t` <= 10.  So our array of times is:
+
+    >>> t = np.linspace(0, 10, 101)
+
+    Call `odeint` to generate the solution. To pass the parameters
+    `b` and `c` to `pend`, we give them to `odeint` using the `args`
+    argument.
+
+    >>> from scipy.integrate import odeint
+    >>> sol = odeint(pend, y0, t, args=(b, c))
+
+    The solution is an array with shape (101, 2). The first column
+    is `theta(t)`, and the second is `omega(t)`. The following code
+    plots both components.
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.plot(t, sol[:, 0], 'b', label='theta(t)')
+    >>> plt.plot(t, sol[:, 1], 'g', label='omega(t)')
+    >>> plt.legend(loc='best')
+    >>> plt.xlabel('t')
+    >>> plt.grid()
+    >>> plt.show()
+    """
+
+    if ml is None:
+        ml = -1  # changed to zero inside function call
+    if mu is None:
+        mu = -1  # changed to zero inside function call
+
+    dt = np.diff(t)
+    if not ((dt >= 0).all() or (dt <= 0).all()):
+        raise ValueError("The values in t must be monotonically increasing "
+                         "or monotonically decreasing; repeated values are "
+                         "allowed.")
+
+    t = copy(t)
+    y0 = copy(y0)
+
+    with ODE_LOCK:
+        output = _odepack.odeint(func, y0, t, args, Dfun, col_deriv, ml, mu,
+                                full_output, rtol, atol, tcrit, h0, hmax, hmin,
+                                ixpr, mxstep, mxhnil, mxordn, mxords,
+                                int(bool(tfirst)))
+    if output[-1] < 0:
+        warning_msg = (f"{_msgs[output[-1]]} Run with full_output = 1 to "
+                       f"get quantitative information.")
+        warnings.warn(warning_msg, ODEintWarning, stacklevel=2)
+    elif printmessg:
+        warning_msg = _msgs[output[-1]]
+        warnings.warn(warning_msg, ODEintWarning, stacklevel=2)
+
+    if full_output:
+        output[1]['message'] = _msgs[output[-1]]
+
+    output = output[:-1]
+    if len(output) == 1:
+        return output[0]
+    else:
+        return output
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_quad_vec.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_quad_vec.py
new file mode 100644
index 0000000000000000000000000000000000000000..0dfbef6d267f36e88636ec7a7c77a50f6124bf07
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_quad_vec.py
@@ -0,0 +1,674 @@
+import sys
+import copy
+import heapq
+import collections
+import functools
+
+import numpy as np
+
+from scipy._lib._util import MapWrapper, _FunctionWrapper
+
+
+class LRUDict(collections.OrderedDict):
+    def __init__(self, max_size):
+        self.__max_size = max_size
+
+    def __setitem__(self, key, value):
+        existing_key = (key in self)
+        super().__setitem__(key, value)
+        if existing_key:
+            self.move_to_end(key)
+        elif len(self) > self.__max_size:
+            self.popitem(last=False)
+
+    def update(self, other):
+        # Not needed below
+        raise NotImplementedError()
+
+
+class SemiInfiniteFunc:
+    """
+    Argument transform from (start, +-oo) to (0, 1)
+    """
+    def __init__(self, func, start, infty):
+        self._func = func
+        self._start = start
+        self._sgn = -1 if infty < 0 else 1
+
+        # Overflow threshold for the 1/t**2 factor
+        self._tmin = sys.float_info.min**0.5
+
+    def get_t(self, x):
+        z = self._sgn * (x - self._start) + 1
+        if z == 0:
+            # Can happen only if point not in range
+            return np.inf
+        return 1 / z
+
+    def __call__(self, t):
+        if t < self._tmin:
+            return 0.0
+        else:
+            x = self._start + self._sgn * (1 - t) / t
+            f = self._func(x)
+            return self._sgn * (f / t) / t
+
+
+class DoubleInfiniteFunc:
+    """
+    Argument transform from (-oo, oo) to (-1, 1)
+    """
+    def __init__(self, func):
+        self._func = func
+
+        # Overflow threshold for the 1/t**2 factor
+        self._tmin = sys.float_info.min**0.5
+
+    def get_t(self, x):
+        s = -1 if x < 0 else 1
+        return s / (abs(x) + 1)
+
+    def __call__(self, t):
+        if abs(t) < self._tmin:
+            return 0.0
+        else:
+            x = (1 - abs(t)) / t
+            f = self._func(x)
+            return (f / t) / t
+
+
+def _max_norm(x):
+    return np.amax(abs(x))
+
+
+def _get_sizeof(obj):
+    try:
+        return sys.getsizeof(obj)
+    except TypeError:
+        # occurs on pypy
+        if hasattr(obj, '__sizeof__'):
+            return int(obj.__sizeof__())
+        return 64
+
+
+class _Bunch:
+    def __init__(self, **kwargs):
+        self.__keys = kwargs.keys()
+        self.__dict__.update(**kwargs)
+
+    def __repr__(self):
+        key_value_pairs = ', '.join(
+            f'{k}={repr(self.__dict__[k])}' for k in self.__keys
+        )
+        return f"_Bunch({key_value_pairs})"
+
+
+def quad_vec(f, a, b, epsabs=1e-200, epsrel=1e-8, norm='2', cache_size=100e6,
+             limit=10000, workers=1, points=None, quadrature=None, full_output=False,
+             *, args=()):
+    r"""Adaptive integration of a vector-valued function.
+
+    Parameters
+    ----------
+    f : callable
+        Vector-valued function f(x) to integrate.
+    a : float
+        Initial point.
+    b : float
+        Final point.
+    epsabs : float, optional
+        Absolute tolerance.
+    epsrel : float, optional
+        Relative tolerance.
+    norm : {'max', '2'}, optional
+        Vector norm to use for error estimation.
+    cache_size : int, optional
+        Number of bytes to use for memoization.
+    limit : float or int, optional
+        An upper bound on the number of subintervals used in the adaptive
+        algorithm.
+    workers : int or map-like callable, optional
+        If `workers` is an integer, part of the computation is done in
+        parallel subdivided to this many tasks (using
+        :class:`python:multiprocessing.pool.Pool`).
+        Supply `-1` to use all cores available to the Process.
+        Alternatively, supply a map-like callable, such as
+        :meth:`python:multiprocessing.pool.Pool.map` for evaluating the
+        population in parallel.
+        This evaluation is carried out as ``workers(func, iterable)``.
+    points : list, optional
+        List of additional breakpoints.
+    quadrature : {'gk21', 'gk15', 'trapezoid'}, optional
+        Quadrature rule to use on subintervals.
+        Options: 'gk21' (Gauss-Kronrod 21-point rule),
+        'gk15' (Gauss-Kronrod 15-point rule),
+        'trapezoid' (composite trapezoid rule).
+        Default: 'gk21' for finite intervals and 'gk15' for (semi-)infinite.
+    full_output : bool, optional
+        Return an additional ``info`` object.
+    args : tuple, optional
+        Extra arguments to pass to function, if any.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    res : {float, array-like}
+        Estimate for the result
+    err : float
+        Error estimate for the result in the given norm
+    info : object
+        Returned only when ``full_output=True``.
+        Result object with the attributes:
+
+        success : bool
+            Whether integration reached target precision.
+        status : int
+            Indicator for convergence, success (0),
+            failure (1), and failure due to rounding error (2).
+        neval : int
+            Number of function evaluations.
+        intervals : ndarray, shape (num_intervals, 2)
+            Start and end points of subdivision intervals.
+        integrals : ndarray, shape (num_intervals, ...)
+            Integral for each interval.
+            Note that at most ``cache_size`` values are recorded,
+            and the array may contains *nan* for missing items.
+        errors : ndarray, shape (num_intervals,)
+            Estimated integration error for each interval.
+
+    Notes
+    -----
+    The algorithm mainly follows the implementation of QUADPACK's
+    DQAG* algorithms, implementing global error control and adaptive
+    subdivision.
+
+    The algorithm here has some differences to the QUADPACK approach:
+
+    Instead of subdividing one interval at a time, the algorithm
+    subdivides N intervals with largest errors at once. This enables
+    (partial) parallelization of the integration.
+
+    The logic of subdividing "next largest" intervals first is then
+    not implemented, and we rely on the above extension to avoid
+    concentrating on "small" intervals only.
+
+    The Wynn epsilon table extrapolation is not used (QUADPACK uses it
+    for infinite intervals). This is because the algorithm here is
+    supposed to work on vector-valued functions, in an user-specified
+    norm, and the extension of the epsilon algorithm to this case does
+    not appear to be widely agreed. For max-norm, using elementwise
+    Wynn epsilon could be possible, but we do not do this here with
+    the hope that the epsilon extrapolation is mainly useful in
+    special cases.
+
+    References
+    ----------
+    [1] R. Piessens, E. de Doncker, QUADPACK (1983).
+
+    Examples
+    --------
+    We can compute integrations of a vector-valued function:
+
+    >>> from scipy.integrate import quad_vec
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> alpha = np.linspace(0.0, 2.0, num=30)
+    >>> f = lambda x: x**alpha
+    >>> x0, x1 = 0, 2
+    >>> y, err = quad_vec(f, x0, x1)
+    >>> plt.plot(alpha, y)
+    >>> plt.xlabel(r"$\alpha$")
+    >>> plt.ylabel(r"$\int_{0}^{2} x^\alpha dx$")
+    >>> plt.show()
+
+    When using the argument `workers`, one should ensure
+    that the main module is import-safe, for instance
+    by rewriting the example above as:
+
+    .. code-block:: python
+
+        from scipy.integrate import quad_vec
+        import numpy as np
+        import matplotlib.pyplot as plt
+
+        alpha = np.linspace(0.0, 2.0, num=30)
+        x0, x1 = 0, 2
+        def f(x):
+            return x**alpha
+
+        if __name__ == "__main__":
+            y, err = quad_vec(f, x0, x1, workers=2)
+    """
+    a = float(a)
+    b = float(b)
+
+    if args:
+        if not isinstance(args, tuple):
+            args = (args,)
+
+        # create a wrapped function to allow the use of map and Pool.map
+        f = _FunctionWrapper(f, args)
+
+    # Use simple transformations to deal with integrals over infinite
+    # intervals.
+    kwargs = dict(epsabs=epsabs,
+                  epsrel=epsrel,
+                  norm=norm,
+                  cache_size=cache_size,
+                  limit=limit,
+                  workers=workers,
+                  points=points,
+                  quadrature='gk15' if quadrature is None else quadrature,
+                  full_output=full_output)
+    if np.isfinite(a) and np.isinf(b):
+        f2 = SemiInfiniteFunc(f, start=a, infty=b)
+        if points is not None:
+            kwargs['points'] = tuple(f2.get_t(xp) for xp in points)
+        return quad_vec(f2, 0, 1, **kwargs)
+    elif np.isfinite(b) and np.isinf(a):
+        f2 = SemiInfiniteFunc(f, start=b, infty=a)
+        if points is not None:
+            kwargs['points'] = tuple(f2.get_t(xp) for xp in points)
+        res = quad_vec(f2, 0, 1, **kwargs)
+        return (-res[0],) + res[1:]
+    elif np.isinf(a) and np.isinf(b):
+        sgn = -1 if b < a else 1
+
+        # NB. explicitly split integral at t=0, which separates
+        # the positive and negative sides
+        f2 = DoubleInfiniteFunc(f)
+        if points is not None:
+            kwargs['points'] = (0,) + tuple(f2.get_t(xp) for xp in points)
+        else:
+            kwargs['points'] = (0,)
+
+        if a != b:
+            res = quad_vec(f2, -1, 1, **kwargs)
+        else:
+            res = quad_vec(f2, 1, 1, **kwargs)
+
+        return (res[0]*sgn,) + res[1:]
+    elif not (np.isfinite(a) and np.isfinite(b)):
+        raise ValueError(f"invalid integration bounds a={a}, b={b}")
+
+    norm_funcs = {
+        None: _max_norm,
+        'max': _max_norm,
+        '2': np.linalg.norm
+    }
+    if callable(norm):
+        norm_func = norm
+    else:
+        norm_func = norm_funcs[norm]
+
+    parallel_count = 128
+    min_intervals = 2
+
+    try:
+        _quadrature = {None: _quadrature_gk21,
+                       'gk21': _quadrature_gk21,
+                       'gk15': _quadrature_gk15,
+                       'trapezoid': _quadrature_trapezoid}[quadrature]
+    except KeyError as e:
+        raise ValueError(f"unknown quadrature {quadrature!r}") from e
+
+    # Initial interval set
+    if points is None:
+        initial_intervals = [(a, b)]
+    else:
+        prev = a
+        initial_intervals = []
+        for p in sorted(points):
+            p = float(p)
+            if not (a < p < b) or p == prev:
+                continue
+            initial_intervals.append((prev, p))
+            prev = p
+        initial_intervals.append((prev, b))
+
+    global_integral = None
+    global_error = None
+    rounding_error = None
+    interval_cache = None
+    intervals = []
+    neval = 0
+
+    for x1, x2 in initial_intervals:
+        ig, err, rnd = _quadrature(x1, x2, f, norm_func)
+        neval += _quadrature.num_eval
+
+        if global_integral is None:
+            if isinstance(ig, float | complex):
+                # Specialize for scalars
+                if norm_func in (_max_norm, np.linalg.norm):
+                    norm_func = abs
+
+            global_integral = ig
+            global_error = float(err)
+            rounding_error = float(rnd)
+
+            cache_count = cache_size // _get_sizeof(ig)
+            interval_cache = LRUDict(cache_count)
+        else:
+            global_integral += ig
+            global_error += err
+            rounding_error += rnd
+
+        interval_cache[(x1, x2)] = copy.copy(ig)
+        intervals.append((-err, x1, x2))
+
+    heapq.heapify(intervals)
+
+    CONVERGED = 0
+    NOT_CONVERGED = 1
+    ROUNDING_ERROR = 2
+    NOT_A_NUMBER = 3
+
+    status_msg = {
+        CONVERGED: "Target precision reached.",
+        NOT_CONVERGED: "Target precision not reached.",
+        ROUNDING_ERROR: "Target precision could not be reached due to rounding error.",
+        NOT_A_NUMBER: "Non-finite values encountered."
+    }
+
+    # Process intervals
+    with MapWrapper(workers) as mapwrapper:
+        ier = NOT_CONVERGED
+
+        while intervals and len(intervals) < limit:
+            # Select intervals with largest errors for subdivision
+            tol = max(epsabs, epsrel*norm_func(global_integral))
+
+            to_process = []
+            err_sum = 0
+
+            for j in range(parallel_count):
+                if not intervals:
+                    break
+
+                if j > 0 and err_sum > global_error - tol/8:
+                    # avoid unnecessary parallel splitting
+                    break
+
+                interval = heapq.heappop(intervals)
+
+                neg_old_err, a, b = interval
+                old_int = interval_cache.pop((a, b), None)
+                to_process.append(
+                    ((-neg_old_err, a, b, old_int), f, norm_func, _quadrature)
+                )
+                err_sum += -neg_old_err
+
+            # Subdivide intervals
+            for parts in mapwrapper(_subdivide_interval, to_process):
+                dint, derr, dround_err, subint, dneval = parts
+                neval += dneval
+                global_integral += dint
+                global_error += derr
+                rounding_error += dround_err
+                for x in subint:
+                    x1, x2, ig, err = x
+                    interval_cache[(x1, x2)] = ig
+                    heapq.heappush(intervals, (-err, x1, x2))
+
+            # Termination check
+            if len(intervals) >= min_intervals:
+                tol = max(epsabs, epsrel*norm_func(global_integral))
+                if global_error < tol/8:
+                    ier = CONVERGED
+                    break
+                if global_error < rounding_error:
+                    ier = ROUNDING_ERROR
+                    break
+
+            if not (np.isfinite(global_error) and np.isfinite(rounding_error)):
+                ier = NOT_A_NUMBER
+                break
+
+    res = global_integral
+    err = global_error + rounding_error
+
+    if full_output:
+        res_arr = np.asarray(res)
+        dummy = np.full(res_arr.shape, np.nan, dtype=res_arr.dtype)
+        integrals = np.array([interval_cache.get((z[1], z[2]), dummy)
+                                      for z in intervals], dtype=res_arr.dtype)
+        errors = np.array([-z[0] for z in intervals])
+        intervals = np.array([[z[1], z[2]] for z in intervals])
+
+        info = _Bunch(neval=neval,
+                      success=(ier == CONVERGED),
+                      status=ier,
+                      message=status_msg[ier],
+                      intervals=intervals,
+                      integrals=integrals,
+                      errors=errors)
+        return (res, err, info)
+    else:
+        return (res, err)
+
+
+def _subdivide_interval(args):
+    interval, f, norm_func, _quadrature = args
+    old_err, a, b, old_int = interval
+
+    c = 0.5 * (a + b)
+
+    # Left-hand side
+    if getattr(_quadrature, 'cache_size', 0) > 0:
+        f = functools.lru_cache(_quadrature.cache_size)(f)
+
+    s1, err1, round1 = _quadrature(a, c, f, norm_func)
+    dneval = _quadrature.num_eval
+    s2, err2, round2 = _quadrature(c, b, f, norm_func)
+    dneval += _quadrature.num_eval
+    if old_int is None:
+        old_int, _, _ = _quadrature(a, b, f, norm_func)
+        dneval += _quadrature.num_eval
+
+    if getattr(_quadrature, 'cache_size', 0) > 0:
+        dneval = f.cache_info().misses
+
+    dint = s1 + s2 - old_int
+    derr = err1 + err2 - old_err
+    dround_err = round1 + round2
+
+    subintervals = ((a, c, s1, err1), (c, b, s2, err2))
+    return dint, derr, dround_err, subintervals, dneval
+
+
+def _quadrature_trapezoid(x1, x2, f, norm_func):
+    """
+    Composite trapezoid quadrature
+    """
+    x3 = 0.5*(x1 + x2)
+    f1 = f(x1)
+    f2 = f(x2)
+    f3 = f(x3)
+
+    s2 = 0.25 * (x2 - x1) * (f1 + 2*f3 + f2)
+
+    round_err = 0.25 * abs(x2 - x1) * (float(norm_func(f1))
+                                       + 2*float(norm_func(f3))
+                                       + float(norm_func(f2))) * 2e-16
+
+    s1 = 0.5 * (x2 - x1) * (f1 + f2)
+    err = 1/3 * float(norm_func(s1 - s2))
+    return s2, err, round_err
+
+
+_quadrature_trapezoid.cache_size = 3 * 3
+_quadrature_trapezoid.num_eval = 3
+
+
+def _quadrature_gk(a, b, f, norm_func, x, w, v):
+    """
+    Generic Gauss-Kronrod quadrature
+    """
+
+    fv = [0.0]*len(x)
+
+    c = 0.5 * (a + b)
+    h = 0.5 * (b - a)
+
+    # Gauss-Kronrod
+    s_k = 0.0
+    s_k_abs = 0.0
+    for i in range(len(x)):
+        ff = f(c + h*x[i])
+        fv[i] = ff
+
+        vv = v[i]
+
+        # \int f(x)
+        s_k += vv * ff
+        # \int |f(x)|
+        s_k_abs += vv * abs(ff)
+
+    # Gauss
+    s_g = 0.0
+    for i in range(len(w)):
+        s_g += w[i] * fv[2*i + 1]
+
+    # Quadrature of abs-deviation from average
+    s_k_dabs = 0.0
+    y0 = s_k / 2.0
+    for i in range(len(x)):
+        # \int |f(x) - y0|
+        s_k_dabs += v[i] * abs(fv[i] - y0)
+
+    # Use similar error estimation as quadpack
+    err = float(norm_func((s_k - s_g) * h))
+    dabs = float(norm_func(s_k_dabs * h))
+    if dabs != 0 and err != 0:
+        err = dabs * min(1.0, (200 * err / dabs)**1.5)
+
+    eps = sys.float_info.epsilon
+    round_err = float(norm_func(50 * eps * h * s_k_abs))
+
+    if round_err > sys.float_info.min:
+        err = max(err, round_err)
+
+    return h * s_k, err, round_err
+
+
+def _quadrature_gk21(a, b, f, norm_func):
+    """
+    Gauss-Kronrod 21 quadrature with error estimate
+    """
+    # Gauss-Kronrod points
+    x = (0.995657163025808080735527280689003,
+         0.973906528517171720077964012084452,
+         0.930157491355708226001207180059508,
+         0.865063366688984510732096688423493,
+         0.780817726586416897063717578345042,
+         0.679409568299024406234327365114874,
+         0.562757134668604683339000099272694,
+         0.433395394129247190799265943165784,
+         0.294392862701460198131126603103866,
+         0.148874338981631210884826001129720,
+         0,
+         -0.148874338981631210884826001129720,
+         -0.294392862701460198131126603103866,
+         -0.433395394129247190799265943165784,
+         -0.562757134668604683339000099272694,
+         -0.679409568299024406234327365114874,
+         -0.780817726586416897063717578345042,
+         -0.865063366688984510732096688423493,
+         -0.930157491355708226001207180059508,
+         -0.973906528517171720077964012084452,
+         -0.995657163025808080735527280689003)
+
+    # 10-point weights
+    w = (0.066671344308688137593568809893332,
+         0.149451349150580593145776339657697,
+         0.219086362515982043995534934228163,
+         0.269266719309996355091226921569469,
+         0.295524224714752870173892994651338,
+         0.295524224714752870173892994651338,
+         0.269266719309996355091226921569469,
+         0.219086362515982043995534934228163,
+         0.149451349150580593145776339657697,
+         0.066671344308688137593568809893332)
+
+    # 21-point weights
+    v = (0.011694638867371874278064396062192,
+         0.032558162307964727478818972459390,
+         0.054755896574351996031381300244580,
+         0.075039674810919952767043140916190,
+         0.093125454583697605535065465083366,
+         0.109387158802297641899210590325805,
+         0.123491976262065851077958109831074,
+         0.134709217311473325928054001771707,
+         0.142775938577060080797094273138717,
+         0.147739104901338491374841515972068,
+         0.149445554002916905664936468389821,
+         0.147739104901338491374841515972068,
+         0.142775938577060080797094273138717,
+         0.134709217311473325928054001771707,
+         0.123491976262065851077958109831074,
+         0.109387158802297641899210590325805,
+         0.093125454583697605535065465083366,
+         0.075039674810919952767043140916190,
+         0.054755896574351996031381300244580,
+         0.032558162307964727478818972459390,
+         0.011694638867371874278064396062192)
+
+    return _quadrature_gk(a, b, f, norm_func, x, w, v)
+
+
+_quadrature_gk21.num_eval = 21
+
+
+def _quadrature_gk15(a, b, f, norm_func):
+    """
+    Gauss-Kronrod 15 quadrature with error estimate
+    """
+    # Gauss-Kronrod points
+    x = (0.991455371120812639206854697526329,
+         0.949107912342758524526189684047851,
+         0.864864423359769072789712788640926,
+         0.741531185599394439863864773280788,
+         0.586087235467691130294144838258730,
+         0.405845151377397166906606412076961,
+         0.207784955007898467600689403773245,
+         0.000000000000000000000000000000000,
+         -0.207784955007898467600689403773245,
+         -0.405845151377397166906606412076961,
+         -0.586087235467691130294144838258730,
+         -0.741531185599394439863864773280788,
+         -0.864864423359769072789712788640926,
+         -0.949107912342758524526189684047851,
+         -0.991455371120812639206854697526329)
+
+    # 7-point weights
+    w = (0.129484966168869693270611432679082,
+         0.279705391489276667901467771423780,
+         0.381830050505118944950369775488975,
+         0.417959183673469387755102040816327,
+         0.381830050505118944950369775488975,
+         0.279705391489276667901467771423780,
+         0.129484966168869693270611432679082)
+
+    # 15-point weights
+    v = (0.022935322010529224963732008058970,
+         0.063092092629978553290700663189204,
+         0.104790010322250183839876322541518,
+         0.140653259715525918745189590510238,
+         0.169004726639267902826583426598550,
+         0.190350578064785409913256402421014,
+         0.204432940075298892414161999234649,
+         0.209482141084727828012999174891714,
+         0.204432940075298892414161999234649,
+         0.190350578064785409913256402421014,
+         0.169004726639267902826583426598550,
+         0.140653259715525918745189590510238,
+         0.104790010322250183839876322541518,
+         0.063092092629978553290700663189204,
+         0.022935322010529224963732008058970)
+
+    return _quadrature_gk(a, b, f, norm_func, x, w, v)
+
+
+_quadrature_gk15.num_eval = 15
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_quadpack.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_quadpack.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee510f8a81cfa3649e8efd853d69985ed77588b3
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_quadpack.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:cb1728d15ddb15a03610d77ebd2796ef68654cdaf87702d7eb3d5b6415fe9da7
+size 112024
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_quadpack_py.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_quadpack_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..77a5d350ab17c24518c2e5da7d674693810388a6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_quadpack_py.py
@@ -0,0 +1,1283 @@
+# Author: Travis Oliphant 2001
+# Author: Nathan Woods 2013 (nquad &c)
+import sys
+import warnings
+from functools import partial
+
+from . import _quadpack
+import numpy as np
+
+__all__ = ["quad", "dblquad", "tplquad", "nquad", "IntegrationWarning"]
+
+
+class IntegrationWarning(UserWarning):
+    """
+    Warning on issues during integration.
+    """
+    pass
+
+
+def quad(func, a, b, args=(), full_output=0, epsabs=1.49e-8, epsrel=1.49e-8,
+         limit=50, points=None, weight=None, wvar=None, wopts=None, maxp1=50,
+         limlst=50, complex_func=False):
+    """
+    Compute a definite integral.
+
+    Integrate func from `a` to `b` (possibly infinite interval) using a
+    technique from the Fortran library QUADPACK.
+
+    Parameters
+    ----------
+    func : {function, scipy.LowLevelCallable}
+        A Python function or method to integrate. If `func` takes many
+        arguments, it is integrated along the axis corresponding to the
+        first argument.
+
+        If the user desires improved integration performance, then `f` may
+        be a `scipy.LowLevelCallable` with one of the signatures::
+
+            double func(double x)
+            double func(double x, void *user_data)
+            double func(int n, double *xx)
+            double func(int n, double *xx, void *user_data)
+
+        The ``user_data`` is the data contained in the `scipy.LowLevelCallable`.
+        In the call forms with ``xx``,  ``n`` is the length of the ``xx``
+        array which contains ``xx[0] == x`` and the rest of the items are
+        numbers contained in the ``args`` argument of quad.
+
+        In addition, certain ctypes call signatures are supported for
+        backward compatibility, but those should not be used in new code.
+    a : float
+        Lower limit of integration (use -numpy.inf for -infinity).
+    b : float
+        Upper limit of integration (use numpy.inf for +infinity).
+    args : tuple, optional
+        Extra arguments to pass to `func`.
+    full_output : int, optional
+        Non-zero to return a dictionary of integration information.
+        If non-zero, warning messages are also suppressed and the
+        message is appended to the output tuple.
+    complex_func : bool, optional
+        Indicate if the function's (`func`) return type is real
+        (``complex_func=False``: default) or complex (``complex_func=True``).
+        In both cases, the function's argument is real.
+        If full_output is also non-zero, the `infodict`, `message`, and
+        `explain` for the real and complex components are returned in
+        a dictionary with keys "real output" and "imag output".
+
+    Returns
+    -------
+    y : float
+        The integral of func from `a` to `b`.
+    abserr : float
+        An estimate of the absolute error in the result.
+    infodict : dict
+        A dictionary containing additional information.
+    message
+        A convergence message.
+    explain
+        Appended only with 'cos' or 'sin' weighting and infinite
+        integration limits, it contains an explanation of the codes in
+        infodict['ierlst']
+
+    Other Parameters
+    ----------------
+    epsabs : float or int, optional
+        Absolute error tolerance. Default is 1.49e-8. `quad` tries to obtain
+        an accuracy of ``abs(i-result) <= max(epsabs, epsrel*abs(i))``
+        where ``i`` = integral of `func` from `a` to `b`, and ``result`` is the
+        numerical approximation. See `epsrel` below.
+    epsrel : float or int, optional
+        Relative error tolerance. Default is 1.49e-8.
+        If ``epsabs <= 0``, `epsrel` must be greater than both 5e-29
+        and ``50 * (machine epsilon)``. See `epsabs` above.
+    limit : float or int, optional
+        An upper bound on the number of subintervals used in the adaptive
+        algorithm.
+    points : (sequence of floats,ints), optional
+        A sequence of break points in the bounded integration interval
+        where local difficulties of the integrand may occur (e.g.,
+        singularities, discontinuities). The sequence does not have
+        to be sorted. Note that this option cannot be used in conjunction
+        with ``weight``.
+    weight : float or int, optional
+        String indicating weighting function. Full explanation for this
+        and the remaining arguments can be found below.
+    wvar : optional
+        Variables for use with weighting functions.
+    wopts : optional
+        Optional input for reusing Chebyshev moments.
+    maxp1 : float or int, optional
+        An upper bound on the number of Chebyshev moments.
+    limlst : int, optional
+        Upper bound on the number of cycles (>=3) for use with a sinusoidal
+        weighting and an infinite end-point.
+
+    See Also
+    --------
+    dblquad : double integral
+    tplquad : triple integral
+    nquad : n-dimensional integrals (uses `quad` recursively)
+    fixed_quad : fixed-order Gaussian quadrature
+    simpson : integrator for sampled data
+    romb : integrator for sampled data
+    scipy.special : for coefficients and roots of orthogonal polynomials
+
+    Notes
+    -----
+    For valid results, the integral must converge; behavior for divergent
+    integrals is not guaranteed.
+
+    **Extra information for quad() inputs and outputs**
+
+    If full_output is non-zero, then the third output argument
+    (infodict) is a dictionary with entries as tabulated below. For
+    infinite limits, the range is transformed to (0,1) and the
+    optional outputs are given with respect to this transformed range.
+    Let M be the input argument limit and let K be infodict['last'].
+    The entries are:
+
+    'neval'
+        The number of function evaluations.
+    'last'
+        The number, K, of subintervals produced in the subdivision process.
+    'alist'
+        A rank-1 array of length M, the first K elements of which are the
+        left end points of the subintervals in the partition of the
+        integration range.
+    'blist'
+        A rank-1 array of length M, the first K elements of which are the
+        right end points of the subintervals.
+    'rlist'
+        A rank-1 array of length M, the first K elements of which are the
+        integral approximations on the subintervals.
+    'elist'
+        A rank-1 array of length M, the first K elements of which are the
+        moduli of the absolute error estimates on the subintervals.
+    'iord'
+        A rank-1 integer array of length M, the first L elements of
+        which are pointers to the error estimates over the subintervals
+        with ``L=K`` if ``K<=M/2+2`` or ``L=M+1-K`` otherwise. Let I be the
+        sequence ``infodict['iord']`` and let E be the sequence
+        ``infodict['elist']``.  Then ``E[I[1]], ..., E[I[L]]`` forms a
+        decreasing sequence.
+
+    If the input argument points is provided (i.e., it is not None),
+    the following additional outputs are placed in the output
+    dictionary. Assume the points sequence is of length P.
+
+    'pts'
+        A rank-1 array of length P+2 containing the integration limits
+        and the break points of the intervals in ascending order.
+        This is an array giving the subintervals over which integration
+        will occur.
+    'level'
+        A rank-1 integer array of length M (=limit), containing the
+        subdivision levels of the subintervals, i.e., if (aa,bb) is a
+        subinterval of ``(pts[1], pts[2])`` where ``pts[0]`` and ``pts[2]``
+        are adjacent elements of ``infodict['pts']``, then (aa,bb) has level l
+        if ``|bb-aa| = |pts[2]-pts[1]| * 2**(-l)``.
+    'ndin'
+        A rank-1 integer array of length P+2. After the first integration
+        over the intervals (pts[1], pts[2]), the error estimates over some
+        of the intervals may have been increased artificially in order to
+        put their subdivision forward. This array has ones in slots
+        corresponding to the subintervals for which this happens.
+
+    **Weighting the integrand**
+
+    The input variables, *weight* and *wvar*, are used to weight the
+    integrand by a select list of functions. Different integration
+    methods are used to compute the integral with these weighting
+    functions, and these do not support specifying break points. The
+    possible values of weight and the corresponding weighting functions are.
+
+    ==========  ===================================   =====================
+    ``weight``  Weight function used                  ``wvar``
+    ==========  ===================================   =====================
+    'cos'       cos(w*x)                              wvar = w
+    'sin'       sin(w*x)                              wvar = w
+    'alg'       g(x) = ((x-a)**alpha)*((b-x)**beta)   wvar = (alpha, beta)
+    'alg-loga'  g(x)*log(x-a)                         wvar = (alpha, beta)
+    'alg-logb'  g(x)*log(b-x)                         wvar = (alpha, beta)
+    'alg-log'   g(x)*log(x-a)*log(b-x)                wvar = (alpha, beta)
+    'cauchy'    1/(x-c)                               wvar = c
+    ==========  ===================================   =====================
+
+    wvar holds the parameter w, (alpha, beta), or c depending on the weight
+    selected. In these expressions, a and b are the integration limits.
+
+    For the 'cos' and 'sin' weighting, additional inputs and outputs are
+    available.
+
+    For weighted integrals with finite integration limits, the integration
+    is performed using a Clenshaw-Curtis method, which uses Chebyshev moments.
+    For repeated calculations, these moments are saved in the output dictionary:
+
+    'momcom'
+        The maximum level of Chebyshev moments that have been computed,
+        i.e., if ``M_c`` is ``infodict['momcom']`` then the moments have been
+        computed for intervals of length ``|b-a| * 2**(-l)``,
+        ``l=0,1,...,M_c``.
+    'nnlog'
+        A rank-1 integer array of length M(=limit), containing the
+        subdivision levels of the subintervals, i.e., an element of this
+        array is equal to l if the corresponding subinterval is
+        ``|b-a|* 2**(-l)``.
+    'chebmo'
+        A rank-2 array of shape (25, maxp1) containing the computed
+        Chebyshev moments. These can be passed on to an integration
+        over the same interval by passing this array as the second
+        element of the sequence wopts and passing infodict['momcom'] as
+        the first element.
+
+    If one of the integration limits is infinite, then a Fourier integral is
+    computed (assuming w neq 0). If full_output is 1 and a numerical error
+    is encountered, besides the error message attached to the output tuple,
+    a dictionary is also appended to the output tuple which translates the
+    error codes in the array ``info['ierlst']`` to English messages. The
+    output information dictionary contains the following entries instead of
+    'last', 'alist', 'blist', 'rlist', and 'elist':
+
+    'lst'
+        The number of subintervals needed for the integration (call it ``K_f``).
+    'rslst'
+        A rank-1 array of length M_f=limlst, whose first ``K_f`` elements
+        contain the integral contribution over the interval
+        ``(a+(k-1)c, a+kc)`` where ``c = (2*floor(|w|) + 1) * pi / |w|``
+        and ``k=1,2,...,K_f``.
+    'erlst'
+        A rank-1 array of length ``M_f`` containing the error estimate
+        corresponding to the interval in the same position in
+        ``infodict['rslist']``.
+    'ierlst'
+        A rank-1 integer array of length ``M_f`` containing an error flag
+        corresponding to the interval in the same position in
+        ``infodict['rslist']``.  See the explanation dictionary (last entry
+        in the output tuple) for the meaning of the codes.
+
+
+    **Details of QUADPACK level routines**
+
+    `quad` calls routines from the FORTRAN library QUADPACK. This section
+    provides details on the conditions for each routine to be called and a
+    short description of each routine. The routine called depends on
+    `weight`, `points` and the integration limits `a` and `b`.
+
+    ================  ==============  ==========  =====================
+    QUADPACK routine  `weight`        `points`    infinite bounds
+    ================  ==============  ==========  =====================
+    qagse             None            No          No
+    qagie             None            No          Yes
+    qagpe             None            Yes         No
+    qawoe             'sin', 'cos'    No          No
+    qawfe             'sin', 'cos'    No          either `a` or `b`
+    qawse             'alg*'          No          No
+    qawce             'cauchy'        No          No
+    ================  ==============  ==========  =====================
+
+    The following provides a short description from [1]_ for each
+    routine.
+
+    qagse
+        is an integrator based on globally adaptive interval
+        subdivision in connection with extrapolation, which will
+        eliminate the effects of integrand singularities of
+        several types. The integration is performed using a 21-point Gauss-Kronrod 
+        quadrature within each subinterval.
+    qagie
+        handles integration over infinite intervals. The infinite range is
+        mapped onto a finite interval and subsequently the same strategy as
+        in ``QAGS`` is applied.
+    qagpe
+        serves the same purposes as QAGS, but also allows the
+        user to provide explicit information about the location
+        and type of trouble-spots i.e. the abscissae of internal
+        singularities, discontinuities and other difficulties of
+        the integrand function.
+    qawoe
+        is an integrator for the evaluation of
+        :math:`\\int^b_a \\cos(\\omega x)f(x)dx` or
+        :math:`\\int^b_a \\sin(\\omega x)f(x)dx`
+        over a finite interval [a,b], where :math:`\\omega` and :math:`f`
+        are specified by the user. The rule evaluation component is based
+        on the modified Clenshaw-Curtis technique
+
+        An adaptive subdivision scheme is used in connection
+        with an extrapolation procedure, which is a modification
+        of that in ``QAGS`` and allows the algorithm to deal with
+        singularities in :math:`f(x)`.
+    qawfe
+        calculates the Fourier transform
+        :math:`\\int^\\infty_a \\cos(\\omega x)f(x)dx` or
+        :math:`\\int^\\infty_a \\sin(\\omega x)f(x)dx`
+        for user-provided :math:`\\omega` and :math:`f`. The procedure of
+        ``QAWO`` is applied on successive finite intervals, and convergence
+        acceleration by means of the :math:`\\varepsilon`-algorithm is applied
+        to the series of integral approximations.
+    qawse
+        approximate :math:`\\int^b_a w(x)f(x)dx`, with :math:`a < b` where
+        :math:`w(x) = (x-a)^{\\alpha}(b-x)^{\\beta}v(x)` with
+        :math:`\\alpha,\\beta > -1`, where :math:`v(x)` may be one of the
+        following functions: :math:`1`, :math:`\\log(x-a)`, :math:`\\log(b-x)`,
+        :math:`\\log(x-a)\\log(b-x)`.
+
+        The user specifies :math:`\\alpha`, :math:`\\beta` and the type of the
+        function :math:`v`. A globally adaptive subdivision strategy is
+        applied, with modified Clenshaw-Curtis integration on those
+        subintervals which contain `a` or `b`.
+    qawce
+        compute :math:`\\int^b_a f(x) / (x-c)dx` where the integral must be
+        interpreted as a Cauchy principal value integral, for user specified
+        :math:`c` and :math:`f`. The strategy is globally adaptive. Modified
+        Clenshaw-Curtis integration is used on those intervals containing the
+        point :math:`x = c`.
+
+    **Integration of Complex Function of a Real Variable**
+
+    A complex valued function, :math:`f`, of a real variable can be written as
+    :math:`f = g + ih`.  Similarly, the integral of :math:`f` can be
+    written as
+
+    .. math::
+        \\int_a^b f(x) dx = \\int_a^b g(x) dx + i\\int_a^b h(x) dx
+
+    assuming that the integrals of :math:`g` and :math:`h` exist
+    over the interval :math:`[a,b]` [2]_. Therefore, ``quad`` integrates
+    complex-valued functions by integrating the real and imaginary components
+    separately.
+
+
+    References
+    ----------
+
+    .. [1] Piessens, Robert; de Doncker-Kapenga, Elise;
+           Überhuber, Christoph W.; Kahaner, David (1983).
+           QUADPACK: A subroutine package for automatic integration.
+           Springer-Verlag.
+           ISBN 978-3-540-12553-2.
+
+    .. [2] McCullough, Thomas; Phillips, Keith (1973).
+           Foundations of Analysis in the Complex Plane.
+           Holt Rinehart Winston.
+           ISBN 0-03-086370-8
+
+    Examples
+    --------
+    Calculate :math:`\\int^4_0 x^2 dx` and compare with an analytic result
+
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> x2 = lambda x: x**2
+    >>> integrate.quad(x2, 0, 4)
+    (21.333333333333332, 2.3684757858670003e-13)
+    >>> print(4**3 / 3.)  # analytical result
+    21.3333333333
+
+    Calculate :math:`\\int^\\infty_0 e^{-x} dx`
+
+    >>> invexp = lambda x: np.exp(-x)
+    >>> integrate.quad(invexp, 0, np.inf)
+    (1.0, 5.842605999138044e-11)
+
+    Calculate :math:`\\int^1_0 a x \\,dx` for :math:`a = 1, 3`
+
+    >>> f = lambda x, a: a*x
+    >>> y, err = integrate.quad(f, 0, 1, args=(1,))
+    >>> y
+    0.5
+    >>> y, err = integrate.quad(f, 0, 1, args=(3,))
+    >>> y
+    1.5
+
+    Calculate :math:`\\int^1_0 x^2 + y^2 dx` with ctypes, holding
+    y parameter as 1::
+
+        testlib.c =>
+            double func(int n, double args[n]){
+                return args[0]*args[0] + args[1]*args[1];}
+        compile to library testlib.*
+
+    ::
+
+       from scipy import integrate
+       import ctypes
+       lib = ctypes.CDLL('/home/.../testlib.*') #use absolute path
+       lib.func.restype = ctypes.c_double
+       lib.func.argtypes = (ctypes.c_int,ctypes.c_double)
+       integrate.quad(lib.func,0,1,(1))
+       #(1.3333333333333333, 1.4802973661668752e-14)
+       print((1.0**3/3.0 + 1.0) - (0.0**3/3.0 + 0.0)) #Analytic result
+       # 1.3333333333333333
+
+    Be aware that pulse shapes and other sharp features as compared to the
+    size of the integration interval may not be integrated correctly using
+    this method. A simplified example of this limitation is integrating a
+    y-axis reflected step function with many zero values within the integrals
+    bounds.
+
+    >>> y = lambda x: 1 if x<=0 else 0
+    >>> integrate.quad(y, -1, 1)
+    (1.0, 1.1102230246251565e-14)
+    >>> integrate.quad(y, -1, 100)
+    (1.0000000002199108, 1.0189464580163188e-08)
+    >>> integrate.quad(y, -1, 10000)
+    (0.0, 0.0)
+
+    """
+    if not isinstance(args, tuple):
+        args = (args,)
+
+    # check the limits of integration: \int_a^b, expect a < b
+    flip, a, b = b < a, min(a, b), max(a, b)
+
+    if complex_func:
+        def imfunc(x, *args):
+            return func(x, *args).imag
+
+        def refunc(x, *args):
+            return func(x, *args).real
+
+        re_retval = quad(refunc, a, b, args, full_output, epsabs,
+                         epsrel, limit, points, weight, wvar, wopts,
+                         maxp1, limlst, complex_func=False)
+        im_retval = quad(imfunc, a, b, args, full_output, epsabs,
+                         epsrel, limit, points, weight, wvar, wopts,
+                         maxp1, limlst, complex_func=False)
+        integral = re_retval[0] + 1j*im_retval[0]
+        error_estimate = re_retval[1] + 1j*im_retval[1]
+        retval = integral, error_estimate
+        if full_output:
+            msgexp = {}
+            msgexp["real"] = re_retval[2:]
+            msgexp["imag"] = im_retval[2:]
+            retval = retval + (msgexp,)
+
+        return retval
+
+    if weight is None:
+        retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,
+                       points)
+    else:
+        if points is not None:
+            msg = ("Break points cannot be specified when using weighted integrand.\n"
+                   "Continuing, ignoring specified points.")
+            warnings.warn(msg, IntegrationWarning, stacklevel=2)
+        retval = _quad_weight(func, a, b, args, full_output, epsabs, epsrel,
+                              limlst, limit, maxp1, weight, wvar, wopts)
+
+    if flip:
+        retval = (-retval[0],) + retval[1:]
+
+    ier = retval[-1]
+    if ier == 0:
+        return retval[:-1]
+
+    msgs = {80: "A Python error occurred possibly while calling the function.",
+             1: f"The maximum number of subdivisions ({limit}) has been achieved.\n  "
+                f"If increasing the limit yields no improvement it is advised to "
+                f"analyze \n  the integrand in order to determine the difficulties.  "
+                f"If the position of a \n  local difficulty can be determined "
+                f"(singularity, discontinuity) one will \n  probably gain from "
+                f"splitting up the interval and calling the integrator \n  on the "
+                f"subranges.  Perhaps a special-purpose integrator should be used.",
+             2: "The occurrence of roundoff error is detected, which prevents \n  "
+                "the requested tolerance from being achieved.  "
+                "The error may be \n  underestimated.",
+             3: "Extremely bad integrand behavior occurs at some points of the\n  "
+                "integration interval.",
+             4: "The algorithm does not converge.  Roundoff error is detected\n  "
+                "in the extrapolation table.  It is assumed that the requested "
+                "tolerance\n  cannot be achieved, and that the returned result "
+                "(if full_output = 1) is \n  the best which can be obtained.",
+             5: "The integral is probably divergent, or slowly convergent.",
+             6: "The input is invalid.",
+             7: "Abnormal termination of the routine.  The estimates for result\n  "
+                "and error are less reliable.  It is assumed that the requested "
+                "accuracy\n  has not been achieved.",
+            'unknown': "Unknown error."}
+
+    if weight in ['cos','sin'] and (b == np.inf or a == -np.inf):
+        msgs[1] = (
+            "The maximum number of cycles allowed has been achieved., e.e.\n  of "
+            "subintervals (a+(k-1)c, a+kc) where c = (2*int(abs(omega)+1))\n  "
+            "*pi/abs(omega), for k = 1, 2, ..., lst.  "
+            "One can allow more cycles by increasing the value of limlst.  "
+            "Look at info['ierlst'] with full_output=1."
+        )
+        msgs[4] = (
+            "The extrapolation table constructed for convergence acceleration\n  of "
+            "the series formed by the integral contributions over the cycles, \n  does "
+            "not converge to within the requested accuracy.  "
+            "Look at \n  info['ierlst'] with full_output=1."
+        )
+        msgs[7] = (
+            "Bad integrand behavior occurs within one or more of the cycles.\n  "
+            "Location and type of the difficulty involved can be determined from \n  "
+            "the vector info['ierlist'] obtained with full_output=1."
+        )
+        explain = {1: "The maximum number of subdivisions (= limit) has been \n  "
+                      "achieved on this cycle.",
+                   2: "The occurrence of roundoff error is detected and prevents\n  "
+                      "the tolerance imposed on this cycle from being achieved.",
+                   3: "Extremely bad integrand behavior occurs at some points of\n  "
+                      "this cycle.",
+                   4: "The integral over this cycle does not converge (to within the "
+                      "required accuracy) due to roundoff in the extrapolation "
+                      "procedure invoked on this cycle.  It is assumed that the result "
+                      "on this interval is the best which can be obtained.",
+                   5: "The integral over this cycle is probably divergent or "
+                      "slowly convergent."}
+
+    try:
+        msg = msgs[ier]
+    except KeyError:
+        msg = msgs['unknown']
+
+    if ier in [1,2,3,4,5,7]:
+        if full_output:
+            if weight in ['cos', 'sin'] and (b == np.inf or a == -np.inf):
+                return retval[:-1] + (msg, explain)
+            else:
+                return retval[:-1] + (msg,)
+        else:
+            warnings.warn(msg, IntegrationWarning, stacklevel=2)
+            return retval[:-1]
+
+    elif ier == 6:  # Forensic decision tree when QUADPACK throws ier=6
+        if epsabs <= 0:  # Small error tolerance - applies to all methods
+            if epsrel < max(50 * sys.float_info.epsilon, 5e-29):
+                msg = ("If 'epsabs'<=0, 'epsrel' must be greater than both"
+                       " 5e-29 and 50*(machine epsilon).")
+            elif weight in ['sin', 'cos'] and (abs(a) + abs(b) == np.inf):
+                msg = ("Sine or cosine weighted integrals with infinite domain"
+                       " must have 'epsabs'>0.")
+
+        elif weight is None:
+            if points is None:  # QAGSE/QAGIE
+                msg = ("Invalid 'limit' argument. There must be"
+                       " at least one subinterval")
+            else:  # QAGPE
+                if not (min(a, b) <= min(points) <= max(points) <= max(a, b)):
+                    msg = ("All break points in 'points' must lie within the"
+                           " integration limits.")
+                elif len(points) >= limit:
+                    msg = (f"Number of break points ({len(points):d}) "
+                           f"must be less than subinterval limit ({limit:d})")
+
+        else:
+            if maxp1 < 1:
+                msg = "Chebyshev moment limit maxp1 must be >=1."
+
+            elif weight in ('cos', 'sin') and abs(a+b) == np.inf:  # QAWFE
+                msg = "Cycle limit limlst must be >=3."
+
+            elif weight.startswith('alg'):  # QAWSE
+                if min(wvar) < -1:
+                    msg = "wvar parameters (alpha, beta) must both be >= -1."
+                if b < a:
+                    msg = "Integration limits a, b must satistfy a>> import numpy as np
+    >>> from scipy import integrate
+    >>> f = lambda y, x: x*y**2
+    >>> integrate.dblquad(f, 0, 2, 0, 1)
+        (0.6666666666666667, 7.401486830834377e-15)
+
+    Calculate :math:`\\int^{x=\\pi/4}_{x=0} \\int^{y=\\cos(x)}_{y=\\sin(x)} 1
+    \\,dy \\,dx`.
+
+    >>> f = lambda y, x: 1
+    >>> integrate.dblquad(f, 0, np.pi/4, np.sin, np.cos)
+        (0.41421356237309503, 1.1083280054755938e-14)
+
+    Calculate :math:`\\int^{x=1}_{x=0} \\int^{y=2-x}_{y=x} a x y \\,dy \\,dx`
+    for :math:`a=1, 3`.
+
+    >>> f = lambda y, x, a: a*x*y
+    >>> integrate.dblquad(f, 0, 1, lambda x: x, lambda x: 2-x, args=(1,))
+        (0.33333333333333337, 5.551115123125783e-15)
+    >>> integrate.dblquad(f, 0, 1, lambda x: x, lambda x: 2-x, args=(3,))
+        (0.9999999999999999, 1.6653345369377348e-14)
+
+    Compute the two-dimensional Gaussian Integral, which is the integral of the
+    Gaussian function :math:`f(x,y) = e^{-(x^{2} + y^{2})}`, over
+    :math:`(-\\infty,+\\infty)`. That is, compute the integral
+    :math:`\\iint^{+\\infty}_{-\\infty} e^{-(x^{2} + y^{2})} \\,dy\\,dx`.
+
+    >>> f = lambda x, y: np.exp(-(x ** 2 + y ** 2))
+    >>> integrate.dblquad(f, -np.inf, np.inf, -np.inf, np.inf)
+        (3.141592653589777, 2.5173086737433208e-08)
+
+    """
+
+    def temp_ranges(*args):
+        return [gfun(args[0]) if callable(gfun) else gfun,
+                hfun(args[0]) if callable(hfun) else hfun]
+
+    return nquad(func, [temp_ranges, [a, b]], args=args,
+            opts={"epsabs": epsabs, "epsrel": epsrel})
+
+
+def tplquad(func, a, b, gfun, hfun, qfun, rfun, args=(), epsabs=1.49e-8,
+            epsrel=1.49e-8):
+    """
+    Compute a triple (definite) integral.
+
+    Return the triple integral of ``func(z, y, x)`` from ``x = a..b``,
+    ``y = gfun(x)..hfun(x)``, and ``z = qfun(x,y)..rfun(x,y)``.
+
+    Parameters
+    ----------
+    func : function
+        A Python function or method of at least three variables in the
+        order (z, y, x).
+    a, b : float
+        The limits of integration in x: `a` < `b`
+    gfun : function or float
+        The lower boundary curve in y which is a function taking a single
+        floating point argument (x) and returning a floating point result
+        or a float indicating a constant boundary curve.
+    hfun : function or float
+        The upper boundary curve in y (same requirements as `gfun`).
+    qfun : function or float
+        The lower boundary surface in z.  It must be a function that takes
+        two floats in the order (x, y) and returns a float or a float
+        indicating a constant boundary surface.
+    rfun : function or float
+        The upper boundary surface in z. (Same requirements as `qfun`.)
+    args : tuple, optional
+        Extra arguments to pass to `func`.
+    epsabs : float, optional
+        Absolute tolerance passed directly to the innermost 1-D quadrature
+        integration. Default is 1.49e-8.
+    epsrel : float, optional
+        Relative tolerance of the innermost 1-D integrals. Default is 1.49e-8.
+
+    Returns
+    -------
+    y : float
+        The resultant integral.
+    abserr : float
+        An estimate of the error.
+
+    See Also
+    --------
+    quad : Adaptive quadrature using QUADPACK
+    fixed_quad : Fixed-order Gaussian quadrature
+    dblquad : Double integrals
+    nquad : N-dimensional integrals
+    romb : Integrators for sampled data
+    simpson : Integrators for sampled data
+    scipy.special : For coefficients and roots of orthogonal polynomials
+
+    Notes
+    -----
+    For valid results, the integral must converge; behavior for divergent
+    integrals is not guaranteed.
+
+    **Details of QUADPACK level routines**
+
+    `quad` calls routines from the FORTRAN library QUADPACK. This section
+    provides details on the conditions for each routine to be called and a
+    short description of each routine. For each level of integration, ``qagse``
+    is used for finite limits or ``qagie`` is used, if either limit (or both!)
+    are infinite. The following provides a short description from [1]_ for each
+    routine.
+
+    qagse
+        is an integrator based on globally adaptive interval
+        subdivision in connection with extrapolation, which will
+        eliminate the effects of integrand singularities of
+        several types. The integration is is performed using a 21-point Gauss-Kronrod 
+        quadrature within each subinterval.
+    qagie
+        handles integration over infinite intervals. The infinite range is
+        mapped onto a finite interval and subsequently the same strategy as
+        in ``QAGS`` is applied.
+
+    References
+    ----------
+
+    .. [1] Piessens, Robert; de Doncker-Kapenga, Elise;
+           Überhuber, Christoph W.; Kahaner, David (1983).
+           QUADPACK: A subroutine package for automatic integration.
+           Springer-Verlag.
+           ISBN 978-3-540-12553-2.
+
+    Examples
+    --------
+    Compute the triple integral of ``x * y * z``, over ``x`` ranging
+    from 1 to 2, ``y`` ranging from 2 to 3, ``z`` ranging from 0 to 1.
+    That is, :math:`\\int^{x=2}_{x=1} \\int^{y=3}_{y=2} \\int^{z=1}_{z=0} x y z
+    \\,dz \\,dy \\,dx`.
+
+    >>> import numpy as np
+    >>> from scipy import integrate
+    >>> f = lambda z, y, x: x*y*z
+    >>> integrate.tplquad(f, 1, 2, 2, 3, 0, 1)
+    (1.8749999999999998, 3.3246447942574074e-14)
+
+    Calculate :math:`\\int^{x=1}_{x=0} \\int^{y=1-2x}_{y=0}
+    \\int^{z=1-x-2y}_{z=0} x y z \\,dz \\,dy \\,dx`.
+    Note: `qfun`/`rfun` takes arguments in the order (x, y), even though ``f``
+    takes arguments in the order (z, y, x).
+
+    >>> f = lambda z, y, x: x*y*z
+    >>> integrate.tplquad(f, 0, 1, 0, lambda x: 1-2*x, 0, lambda x, y: 1-x-2*y)
+    (0.05416666666666668, 2.1774196738157757e-14)
+
+    Calculate :math:`\\int^{x=1}_{x=0} \\int^{y=1}_{y=0} \\int^{z=1}_{z=0}
+    a x y z \\,dz \\,dy \\,dx` for :math:`a=1, 3`.
+
+    >>> f = lambda z, y, x, a: a*x*y*z
+    >>> integrate.tplquad(f, 0, 1, 0, 1, 0, 1, args=(1,))
+        (0.125, 5.527033708952211e-15)
+    >>> integrate.tplquad(f, 0, 1, 0, 1, 0, 1, args=(3,))
+        (0.375, 1.6581101126856635e-14)
+
+    Compute the three-dimensional Gaussian Integral, which is the integral of
+    the Gaussian function :math:`f(x,y,z) = e^{-(x^{2} + y^{2} + z^{2})}`, over
+    :math:`(-\\infty,+\\infty)`. That is, compute the integral
+    :math:`\\iiint^{+\\infty}_{-\\infty} e^{-(x^{2} + y^{2} + z^{2})} \\,dz
+    \\,dy\\,dx`.
+
+    >>> f = lambda x, y, z: np.exp(-(x ** 2 + y ** 2 + z ** 2))
+    >>> integrate.tplquad(f, -np.inf, np.inf, -np.inf, np.inf, -np.inf, np.inf)
+        (5.568327996830833, 4.4619078828029765e-08)
+
+    """
+    # f(z, y, x)
+    # qfun/rfun(x, y)
+    # gfun/hfun(x)
+    # nquad will hand (y, x, t0, ...) to ranges0
+    # nquad will hand (x, t0, ...) to ranges1
+    # Only qfun / rfun is different API...
+
+    def ranges0(*args):
+        return [qfun(args[1], args[0]) if callable(qfun) else qfun,
+                rfun(args[1], args[0]) if callable(rfun) else rfun]
+
+    def ranges1(*args):
+        return [gfun(args[0]) if callable(gfun) else gfun,
+                hfun(args[0]) if callable(hfun) else hfun]
+
+    ranges = [ranges0, ranges1, [a, b]]
+    return nquad(func, ranges, args=args,
+            opts={"epsabs": epsabs, "epsrel": epsrel})
+
+
+def nquad(func, ranges, args=None, opts=None, full_output=False):
+    r"""
+    Integration over multiple variables.
+
+    Wraps `quad` to enable integration over multiple variables.
+    Various options allow improved integration of discontinuous functions, as
+    well as the use of weighted integration, and generally finer control of the
+    integration process.
+
+    Parameters
+    ----------
+    func : {callable, scipy.LowLevelCallable}
+        The function to be integrated. Has arguments of ``x0, ... xn``,
+        ``t0, ... tm``, where integration is carried out over ``x0, ... xn``,
+        which must be floats.  Where ``t0, ... tm`` are extra arguments
+        passed in args.
+        Function signature should be ``func(x0, x1, ..., xn, t0, t1, ..., tm)``.
+        Integration is carried out in order.  That is, integration over ``x0``
+        is the innermost integral, and ``xn`` is the outermost.
+
+        If the user desires improved integration performance, then `f` may
+        be a `scipy.LowLevelCallable` with one of the signatures::
+
+            double func(int n, double *xx)
+            double func(int n, double *xx, void *user_data)
+
+        where ``n`` is the number of variables and args.  The ``xx`` array
+        contains the coordinates and extra arguments. ``user_data`` is the data
+        contained in the `scipy.LowLevelCallable`.
+    ranges : iterable object
+        Each element of ranges may be either a sequence  of 2 numbers, or else
+        a callable that returns such a sequence. ``ranges[0]`` corresponds to
+        integration over x0, and so on. If an element of ranges is a callable,
+        then it will be called with all of the integration arguments available,
+        as well as any parametric arguments. e.g., if
+        ``func = f(x0, x1, x2, t0, t1)``, then ``ranges[0]`` may be defined as
+        either ``(a, b)`` or else as ``(a, b) = range0(x1, x2, t0, t1)``.
+    args : iterable object, optional
+        Additional arguments ``t0, ... tn``, required by ``func``, ``ranges``,
+        and ``opts``.
+    opts : iterable object or dict, optional
+        Options to be passed to `quad`. May be empty, a dict, or
+        a sequence of dicts or functions that return a dict. If empty, the
+        default options from scipy.integrate.quad are used. If a dict, the same
+        options are used for all levels of integraion. If a sequence, then each
+        element of the sequence corresponds to a particular integration. e.g.,
+        ``opts[0]`` corresponds to integration over ``x0``, and so on. If a
+        callable, the signature must be the same as for ``ranges``. The
+        available options together with their default values are:
+
+          - epsabs = 1.49e-08
+          - epsrel = 1.49e-08
+          - limit  = 50
+          - points = None
+          - weight = None
+          - wvar   = None
+          - wopts  = None
+
+        For more information on these options, see `quad`.
+
+    full_output : bool, optional
+        Partial implementation of ``full_output`` from scipy.integrate.quad.
+        The number of integrand function evaluations ``neval`` can be obtained
+        by setting ``full_output=True`` when calling nquad.
+
+    Returns
+    -------
+    result : float
+        The result of the integration.
+    abserr : float
+        The maximum of the estimates of the absolute error in the various
+        integration results.
+    out_dict : dict, optional
+        A dict containing additional information on the integration.
+
+    See Also
+    --------
+    quad : 1-D numerical integration
+    dblquad, tplquad : double and triple integrals
+    fixed_quad : fixed-order Gaussian quadrature
+
+    Notes
+    -----
+    For valid results, the integral must converge; behavior for divergent
+    integrals is not guaranteed.
+
+    **Details of QUADPACK level routines**
+
+    `nquad` calls routines from the FORTRAN library QUADPACK. This section
+    provides details on the conditions for each routine to be called and a
+    short description of each routine. The routine called depends on
+    `weight`, `points` and the integration limits `a` and `b`.
+
+    ================  ==============  ==========  =====================
+    QUADPACK routine  `weight`        `points`    infinite bounds
+    ================  ==============  ==========  =====================
+    qagse             None            No          No
+    qagie             None            No          Yes
+    qagpe             None            Yes         No
+    qawoe             'sin', 'cos'    No          No
+    qawfe             'sin', 'cos'    No          either `a` or `b`
+    qawse             'alg*'          No          No
+    qawce             'cauchy'        No          No
+    ================  ==============  ==========  =====================
+
+    The following provides a short description from [1]_ for each
+    routine.
+
+    qagse
+        is an integrator based on globally adaptive interval
+        subdivision in connection with extrapolation, which will
+        eliminate the effects of integrand singularities of
+        several types. The integration is is performed using a 21-point Gauss-Kronrod 
+        quadrature within each subinterval.
+    qagie
+        handles integration over infinite intervals. The infinite range is
+        mapped onto a finite interval and subsequently the same strategy as
+        in ``QAGS`` is applied.
+    qagpe
+        serves the same purposes as QAGS, but also allows the
+        user to provide explicit information about the location
+        and type of trouble-spots i.e. the abscissae of internal
+        singularities, discontinuities and other difficulties of
+        the integrand function.
+    qawoe
+        is an integrator for the evaluation of
+        :math:`\int^b_a \cos(\omega x)f(x)dx` or
+        :math:`\int^b_a \sin(\omega x)f(x)dx`
+        over a finite interval [a,b], where :math:`\omega` and :math:`f`
+        are specified by the user. The rule evaluation component is based
+        on the modified Clenshaw-Curtis technique
+
+        An adaptive subdivision scheme is used in connection
+        with an extrapolation procedure, which is a modification
+        of that in ``QAGS`` and allows the algorithm to deal with
+        singularities in :math:`f(x)`.
+    qawfe
+        calculates the Fourier transform
+        :math:`\int^\infty_a \cos(\omega x)f(x)dx` or
+        :math:`\int^\infty_a \sin(\omega x)f(x)dx`
+        for user-provided :math:`\omega` and :math:`f`. The procedure of
+        ``QAWO`` is applied on successive finite intervals, and convergence
+        acceleration by means of the :math:`\varepsilon`-algorithm is applied
+        to the series of integral approximations.
+    qawse
+        approximate :math:`\int^b_a w(x)f(x)dx`, with :math:`a < b` where
+        :math:`w(x) = (x-a)^{\alpha}(b-x)^{\beta}v(x)` with
+        :math:`\alpha,\beta > -1`, where :math:`v(x)` may be one of the
+        following functions: :math:`1`, :math:`\log(x-a)`, :math:`\log(b-x)`,
+        :math:`\log(x-a)\log(b-x)`.
+
+        The user specifies :math:`\alpha`, :math:`\beta` and the type of the
+        function :math:`v`. A globally adaptive subdivision strategy is
+        applied, with modified Clenshaw-Curtis integration on those
+        subintervals which contain `a` or `b`.
+    qawce
+        compute :math:`\int^b_a f(x) / (x-c)dx` where the integral must be
+        interpreted as a Cauchy principal value integral, for user specified
+        :math:`c` and :math:`f`. The strategy is globally adaptive. Modified
+        Clenshaw-Curtis integration is used on those intervals containing the
+        point :math:`x = c`.
+
+    References
+    ----------
+
+    .. [1] Piessens, Robert; de Doncker-Kapenga, Elise;
+           Überhuber, Christoph W.; Kahaner, David (1983).
+           QUADPACK: A subroutine package for automatic integration.
+           Springer-Verlag.
+           ISBN 978-3-540-12553-2.
+
+    Examples
+    --------
+    Calculate
+
+    .. math::
+
+        \int^{1}_{-0.15} \int^{0.8}_{0.13} \int^{1}_{-1} \int^{1}_{0}
+        f(x_0, x_1, x_2, x_3) \,dx_0 \,dx_1 \,dx_2 \,dx_3 ,
+
+    where
+
+    .. math::
+
+        f(x_0, x_1, x_2, x_3) = \begin{cases}
+          x_0^2+x_1 x_2-x_3^3+ \sin{x_0}+1 & (x_0-0.2 x_3-0.5-0.25 x_1 > 0) \\
+          x_0^2+x_1 x_2-x_3^3+ \sin{x_0}+0 & (x_0-0.2 x_3-0.5-0.25 x_1 \leq 0)
+        \end{cases} .
+
+    >>> import numpy as np
+    >>> from scipy import integrate
+    >>> func = lambda x0,x1,x2,x3 : x0**2 + x1*x2 - x3**3 + np.sin(x0) + (
+    ...                                 1 if (x0-.2*x3-.5-.25*x1>0) else 0)
+    >>> def opts0(*args, **kwargs):
+    ...     return {'points':[0.2*args[2] + 0.5 + 0.25*args[0]]}
+    >>> integrate.nquad(func, [[0,1], [-1,1], [.13,.8], [-.15,1]],
+    ...                 opts=[opts0,{},{},{}], full_output=True)
+    (1.5267454070738633, 2.9437360001402324e-14, {'neval': 388962})
+
+    Calculate
+
+    .. math::
+
+        \int^{t_0+t_1+1}_{t_0+t_1-1}
+        \int^{x_2+t_0^2 t_1^3+1}_{x_2+t_0^2 t_1^3-1}
+        \int^{t_0 x_1+t_1 x_2+1}_{t_0 x_1+t_1 x_2-1}
+        f(x_0,x_1, x_2,t_0,t_1)
+        \,dx_0 \,dx_1 \,dx_2,
+
+    where
+
+    .. math::
+
+        f(x_0, x_1, x_2, t_0, t_1) = \begin{cases}
+          x_0 x_2^2 + \sin{x_1}+2 & (x_0+t_1 x_1-t_0 > 0) \\
+          x_0 x_2^2 +\sin{x_1}+1 & (x_0+t_1 x_1-t_0 \leq 0)
+        \end{cases}
+
+    and :math:`(t_0, t_1) = (0, 1)` .
+
+    >>> def func2(x0, x1, x2, t0, t1):
+    ...     return x0*x2**2 + np.sin(x1) + 1 + (1 if x0+t1*x1-t0>0 else 0)
+    >>> def lim0(x1, x2, t0, t1):
+    ...     return [t0*x1 + t1*x2 - 1, t0*x1 + t1*x2 + 1]
+    >>> def lim1(x2, t0, t1):
+    ...     return [x2 + t0**2*t1**3 - 1, x2 + t0**2*t1**3 + 1]
+    >>> def lim2(t0, t1):
+    ...     return [t0 + t1 - 1, t0 + t1 + 1]
+    >>> def opts0(x1, x2, t0, t1):
+    ...     return {'points' : [t0 - t1*x1]}
+    >>> def opts1(x2, t0, t1):
+    ...     return {}
+    >>> def opts2(t0, t1):
+    ...     return {}
+    >>> integrate.nquad(func2, [lim0, lim1, lim2], args=(0,1),
+    ...                 opts=[opts0, opts1, opts2])
+    (36.099919226771625, 1.8546948553373528e-07)
+
+    """
+    depth = len(ranges)
+    ranges = [rng if callable(rng) else _RangeFunc(rng) for rng in ranges]
+    if args is None:
+        args = ()
+    if opts is None:
+        opts = [dict([])] * depth
+
+    if isinstance(opts, dict):
+        opts = [_OptFunc(opts)] * depth
+    else:
+        opts = [opt if callable(opt) else _OptFunc(opt) for opt in opts]
+    return _NQuad(func, ranges, opts, full_output).integrate(*args)
+
+
+class _RangeFunc:
+    def __init__(self, range_):
+        self.range_ = range_
+
+    def __call__(self, *args):
+        """Return stored value.
+
+        *args needed because range_ can be float or func, and is called with
+        variable number of parameters.
+        """
+        return self.range_
+
+
+class _OptFunc:
+    def __init__(self, opt):
+        self.opt = opt
+
+    def __call__(self, *args):
+        """Return stored dict."""
+        return self.opt
+
+
+class _NQuad:
+    def __init__(self, func, ranges, opts, full_output):
+        self.abserr = 0
+        self.func = func
+        self.ranges = ranges
+        self.opts = opts
+        self.maxdepth = len(ranges)
+        self.full_output = full_output
+        if self.full_output:
+            self.out_dict = {'neval': 0}
+
+    def integrate(self, *args, **kwargs):
+        depth = kwargs.pop('depth', 0)
+        if kwargs:
+            raise ValueError('unexpected kwargs')
+
+        # Get the integration range and options for this depth.
+        ind = -(depth + 1)
+        fn_range = self.ranges[ind]
+        low, high = fn_range(*args)
+        fn_opt = self.opts[ind]
+        opt = dict(fn_opt(*args))
+
+        if 'points' in opt:
+            opt['points'] = [x for x in opt['points'] if low <= x <= high]
+        if depth + 1 == self.maxdepth:
+            f = self.func
+        else:
+            f = partial(self.integrate, depth=depth+1)
+        quad_r = quad(f, low, high, args=args, full_output=self.full_output,
+                      **opt)
+        value = quad_r[0]
+        abserr = quad_r[1]
+        if self.full_output:
+            infodict = quad_r[2]
+            # The 'neval' parameter in full_output returns the total
+            # number of times the integrand function was evaluated.
+            # Therefore, only the innermost integration loop counts.
+            if depth + 1 == self.maxdepth:
+                self.out_dict['neval'] += infodict['neval']
+        self.abserr = max(self.abserr, abserr)
+        if depth > 0:
+            return value
+        else:
+            # Final result of N-D integration with error
+            if self.full_output:
+                return value, self.abserr, self.out_dict
+            else:
+                return value, self.abserr
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_quadrature.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_quadrature.py
new file mode 100644
index 0000000000000000000000000000000000000000..86d70feed7a40f6ebb2a75e9da43c5d7bc2b10d8
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_quadrature.py
@@ -0,0 +1,1336 @@
+import numpy as np
+import numpy.typing as npt
+import math
+import warnings
+from collections import namedtuple
+from collections.abc import Callable
+
+from scipy.special import roots_legendre
+from scipy.special import gammaln, logsumexp
+from scipy._lib._util import _rng_spawn
+from scipy._lib._array_api import _asarray, array_namespace, xp_result_type
+
+
+__all__ = ['fixed_quad', 'romb',
+           'trapezoid', 'simpson',
+           'cumulative_trapezoid', 'newton_cotes',
+           'qmc_quad', 'cumulative_simpson']
+
+
+def trapezoid(y, x=None, dx=1.0, axis=-1):
+    r"""
+    Integrate along the given axis using the composite trapezoidal rule.
+
+    If `x` is provided, the integration happens in sequence along its
+    elements - they are not sorted.
+
+    Integrate `y` (`x`) along each 1d slice on the given axis, compute
+    :math:`\int y(x) dx`.
+    When `x` is specified, this integrates along the parametric curve,
+    computing :math:`\int_t y(t) dt =
+    \int_t y(t) \left.\frac{dx}{dt}\right|_{x=x(t)} dt`.
+
+    Parameters
+    ----------
+    y : array_like
+        Input array to integrate.
+    x : array_like, optional
+        The sample points corresponding to the `y` values. If `x` is None,
+        the sample points are assumed to be evenly spaced `dx` apart. The
+        default is None.
+    dx : scalar, optional
+        The spacing between sample points when `x` is None. The default is 1.
+    axis : int, optional
+        The axis along which to integrate. The default is the last axis.
+
+    Returns
+    -------
+    trapezoid : float or ndarray
+        Definite integral of `y` = n-dimensional array as approximated along
+        a single axis by the trapezoidal rule. If `y` is a 1-dimensional array,
+        then the result is a float. If `n` is greater than 1, then the result
+        is an `n`-1 dimensional array.
+
+    See Also
+    --------
+    cumulative_trapezoid, simpson, romb
+
+    Notes
+    -----
+    Image [2]_ illustrates trapezoidal rule -- y-axis locations of points
+    will be taken from `y` array, by default x-axis distances between
+    points will be 1.0, alternatively they can be provided with `x` array
+    or with `dx` scalar.  Return value will be equal to combined area under
+    the red lines.
+
+    References
+    ----------
+    .. [1] Wikipedia page: https://en.wikipedia.org/wiki/Trapezoidal_rule
+
+    .. [2] Illustration image:
+           https://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png
+
+    Examples
+    --------
+    Use the trapezoidal rule on evenly spaced points:
+
+    >>> import numpy as np
+    >>> from scipy import integrate
+    >>> integrate.trapezoid([1, 2, 3])
+    4.0
+
+    The spacing between sample points can be selected by either the
+    ``x`` or ``dx`` arguments:
+
+    >>> integrate.trapezoid([1, 2, 3], x=[4, 6, 8])
+    8.0
+    >>> integrate.trapezoid([1, 2, 3], dx=2)
+    8.0
+
+    Using a decreasing ``x`` corresponds to integrating in reverse:
+
+    >>> integrate.trapezoid([1, 2, 3], x=[8, 6, 4])
+    -8.0
+
+    More generally ``x`` is used to integrate along a parametric curve. We can
+    estimate the integral :math:`\int_0^1 x^2 = 1/3` using:
+
+    >>> x = np.linspace(0, 1, num=50)
+    >>> y = x**2
+    >>> integrate.trapezoid(y, x)
+    0.33340274885464394
+
+    Or estimate the area of a circle, noting we repeat the sample which closes
+    the curve:
+
+    >>> theta = np.linspace(0, 2 * np.pi, num=1000, endpoint=True)
+    >>> integrate.trapezoid(np.cos(theta), x=np.sin(theta))
+    3.141571941375841
+
+    ``trapezoid`` can be applied along a specified axis to do multiple
+    computations in one call:
+
+    >>> a = np.arange(6).reshape(2, 3)
+    >>> a
+    array([[0, 1, 2],
+           [3, 4, 5]])
+    >>> integrate.trapezoid(a, axis=0)
+    array([1.5, 2.5, 3.5])
+    >>> integrate.trapezoid(a, axis=1)
+    array([2.,  8.])
+    """
+    xp = array_namespace(y)
+    y = _asarray(y, xp=xp, subok=True)
+    # Cannot just use the broadcasted arrays that are returned
+    # because trapezoid does not follow normal broadcasting rules
+    # cf. https://github.com/scipy/scipy/pull/21524#issuecomment-2354105942
+    result_dtype = xp_result_type(y, force_floating=True, xp=xp)
+    nd = y.ndim
+    slice1 = [slice(None)]*nd
+    slice2 = [slice(None)]*nd
+    slice1[axis] = slice(1, None)
+    slice2[axis] = slice(None, -1)
+    if x is None:
+        d = dx
+    else:
+        x = _asarray(x, xp=xp, subok=True)
+        if x.ndim == 1:
+            d = x[1:] - x[:-1]
+            # make d broadcastable to y
+            slice3 = [None] * nd
+            slice3[axis] = slice(None)
+            d = d[tuple(slice3)]
+        else:
+            # if x is n-D it should be broadcastable to y
+            x = xp.broadcast_to(x, y.shape)
+            d = x[tuple(slice1)] - x[tuple(slice2)]
+    try:
+        ret = xp.sum(
+            d * (y[tuple(slice1)] + y[tuple(slice2)]) / 2.0,
+            axis=axis, dtype=result_dtype
+        )
+    except ValueError:
+        # Operations didn't work, cast to ndarray
+        d = xp.asarray(d)
+        y = xp.asarray(y)
+        ret = xp.sum(
+            d * (y[tuple(slice1)] + y[tuple(slice2)]) / 2.0,
+            axis=axis, dtype=result_dtype
+        )
+    return ret
+
+
+def _cached_roots_legendre(n):
+    """
+    Cache roots_legendre results to speed up calls of the fixed_quad
+    function.
+    """
+    if n in _cached_roots_legendre.cache:
+        return _cached_roots_legendre.cache[n]
+
+    _cached_roots_legendre.cache[n] = roots_legendre(n)
+    return _cached_roots_legendre.cache[n]
+
+
+_cached_roots_legendre.cache = dict()
+
+
+def fixed_quad(func, a, b, args=(), n=5):
+    """
+    Compute a definite integral using fixed-order Gaussian quadrature.
+
+    Integrate `func` from `a` to `b` using Gaussian quadrature of
+    order `n`.
+
+    Parameters
+    ----------
+    func : callable
+        A Python function or method to integrate (must accept vector inputs).
+        If integrating a vector-valued function, the returned array must have
+        shape ``(..., len(x))``.
+    a : float
+        Lower limit of integration.
+    b : float
+        Upper limit of integration.
+    args : tuple, optional
+        Extra arguments to pass to function, if any.
+    n : int, optional
+        Order of quadrature integration. Default is 5.
+
+    Returns
+    -------
+    val : float
+        Gaussian quadrature approximation to the integral
+    none : None
+        Statically returned value of None
+
+    See Also
+    --------
+    quad : adaptive quadrature using QUADPACK
+    dblquad : double integrals
+    tplquad : triple integrals
+    romb : integrators for sampled data
+    simpson : integrators for sampled data
+    cumulative_trapezoid : cumulative integration for sampled data
+
+    Examples
+    --------
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> f = lambda x: x**8
+    >>> integrate.fixed_quad(f, 0.0, 1.0, n=4)
+    (0.1110884353741496, None)
+    >>> integrate.fixed_quad(f, 0.0, 1.0, n=5)
+    (0.11111111111111102, None)
+    >>> print(1/9.0)  # analytical result
+    0.1111111111111111
+
+    >>> integrate.fixed_quad(np.cos, 0.0, np.pi/2, n=4)
+    (0.9999999771971152, None)
+    >>> integrate.fixed_quad(np.cos, 0.0, np.pi/2, n=5)
+    (1.000000000039565, None)
+    >>> np.sin(np.pi/2)-np.sin(0)  # analytical result
+    1.0
+
+    """
+    x, w = _cached_roots_legendre(n)
+    x = np.real(x)
+    if np.isinf(a) or np.isinf(b):
+        raise ValueError("Gaussian quadrature is only available for "
+                         "finite limits.")
+    y = (b-a)*(x+1)/2.0 + a
+    return (b-a)/2.0 * np.sum(w*func(y, *args), axis=-1), None
+
+
+def tupleset(t, i, value):
+    l = list(t)
+    l[i] = value
+    return tuple(l)
+
+
+def cumulative_trapezoid(y, x=None, dx=1.0, axis=-1, initial=None):
+    """
+    Cumulatively integrate y(x) using the composite trapezoidal rule.
+
+    Parameters
+    ----------
+    y : array_like
+        Values to integrate.
+    x : array_like, optional
+        The coordinate to integrate along. If None (default), use spacing `dx`
+        between consecutive elements in `y`.
+    dx : float, optional
+        Spacing between elements of `y`. Only used if `x` is None.
+    axis : int, optional
+        Specifies the axis to cumulate. Default is -1 (last axis).
+    initial : scalar, optional
+        If given, insert this value at the beginning of the returned result.
+        0 or None are the only values accepted. Default is None, which means
+        `res` has one element less than `y` along the axis of integration.
+
+    Returns
+    -------
+    res : ndarray
+        The result of cumulative integration of `y` along `axis`.
+        If `initial` is None, the shape is such that the axis of integration
+        has one less value than `y`. If `initial` is given, the shape is equal
+        to that of `y`.
+
+    See Also
+    --------
+    numpy.cumsum, numpy.cumprod
+    cumulative_simpson : cumulative integration using Simpson's 1/3 rule
+    quad : adaptive quadrature using QUADPACK
+    fixed_quad : fixed-order Gaussian quadrature
+    dblquad : double integrals
+    tplquad : triple integrals
+    romb : integrators for sampled data
+
+    Examples
+    --------
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+
+    >>> x = np.linspace(-2, 2, num=20)
+    >>> y = x
+    >>> y_int = integrate.cumulative_trapezoid(y, x, initial=0)
+    >>> plt.plot(x, y_int, 'ro', x, y[0] + 0.5 * x**2, 'b-')
+    >>> plt.show()
+
+    """
+    y = np.asarray(y)
+    if y.shape[axis] == 0:
+        raise ValueError("At least one point is required along `axis`.")
+    if x is None:
+        d = dx
+    else:
+        x = np.asarray(x)
+        if x.ndim == 1:
+            d = np.diff(x)
+            # reshape to correct shape
+            shape = [1] * y.ndim
+            shape[axis] = -1
+            d = d.reshape(shape)
+        elif len(x.shape) != len(y.shape):
+            raise ValueError("If given, shape of x must be 1-D or the "
+                             "same as y.")
+        else:
+            d = np.diff(x, axis=axis)
+
+        if d.shape[axis] != y.shape[axis] - 1:
+            raise ValueError("If given, length of x along axis must be the "
+                             "same as y.")
+
+    nd = len(y.shape)
+    slice1 = tupleset((slice(None),)*nd, axis, slice(1, None))
+    slice2 = tupleset((slice(None),)*nd, axis, slice(None, -1))
+    res = np.cumsum(d * (y[slice1] + y[slice2]) / 2.0, axis=axis)
+
+    if initial is not None:
+        if initial != 0:
+            raise ValueError("`initial` must be `None` or `0`.")
+        if not np.isscalar(initial):
+            raise ValueError("`initial` parameter should be a scalar.")
+
+        shape = list(res.shape)
+        shape[axis] = 1
+        res = np.concatenate([np.full(shape, initial, dtype=res.dtype), res],
+                             axis=axis)
+
+    return res
+
+
+def _basic_simpson(y, start, stop, x, dx, axis):
+    nd = len(y.shape)
+    if start is None:
+        start = 0
+    step = 2
+    slice_all = (slice(None),)*nd
+    slice0 = tupleset(slice_all, axis, slice(start, stop, step))
+    slice1 = tupleset(slice_all, axis, slice(start+1, stop+1, step))
+    slice2 = tupleset(slice_all, axis, slice(start+2, stop+2, step))
+
+    if x is None:  # Even-spaced Simpson's rule.
+        result = np.sum(y[slice0] + 4.0*y[slice1] + y[slice2], axis=axis)
+        result *= dx / 3.0
+    else:
+        # Account for possibly different spacings.
+        #    Simpson's rule changes a bit.
+        h = np.diff(x, axis=axis)
+        sl0 = tupleset(slice_all, axis, slice(start, stop, step))
+        sl1 = tupleset(slice_all, axis, slice(start+1, stop+1, step))
+        h0 = h[sl0].astype(float, copy=False)
+        h1 = h[sl1].astype(float, copy=False)
+        hsum = h0 + h1
+        hprod = h0 * h1
+        h0divh1 = np.true_divide(h0, h1, out=np.zeros_like(h0), where=h1 != 0)
+        tmp = hsum/6.0 * (y[slice0] *
+                          (2.0 - np.true_divide(1.0, h0divh1,
+                                                out=np.zeros_like(h0divh1),
+                                                where=h0divh1 != 0)) +
+                          y[slice1] * (hsum *
+                                       np.true_divide(hsum, hprod,
+                                                      out=np.zeros_like(hsum),
+                                                      where=hprod != 0)) +
+                          y[slice2] * (2.0 - h0divh1))
+        result = np.sum(tmp, axis=axis)
+    return result
+
+
+def simpson(y, x=None, *, dx=1.0, axis=-1):
+    """
+    Integrate y(x) using samples along the given axis and the composite
+    Simpson's rule. If x is None, spacing of dx is assumed.
+
+    Parameters
+    ----------
+    y : array_like
+        Array to be integrated.
+    x : array_like, optional
+        If given, the points at which `y` is sampled.
+    dx : float, optional
+        Spacing of integration points along axis of `x`. Only used when
+        `x` is None. Default is 1.
+    axis : int, optional
+        Axis along which to integrate. Default is the last axis.
+
+    Returns
+    -------
+    float
+        The estimated integral computed with the composite Simpson's rule.
+
+    See Also
+    --------
+    quad : adaptive quadrature using QUADPACK
+    fixed_quad : fixed-order Gaussian quadrature
+    dblquad : double integrals
+    tplquad : triple integrals
+    romb : integrators for sampled data
+    cumulative_trapezoid : cumulative integration for sampled data
+    cumulative_simpson : cumulative integration using Simpson's 1/3 rule
+
+    Notes
+    -----
+    For an odd number of samples that are equally spaced the result is
+    exact if the function is a polynomial of order 3 or less. If
+    the samples are not equally spaced, then the result is exact only
+    if the function is a polynomial of order 2 or less.
+
+    References
+    ----------
+    .. [1] Cartwright, Kenneth V. Simpson's Rule Cumulative Integration with
+           MS Excel and Irregularly-spaced Data. Journal of Mathematical
+           Sciences and Mathematics Education. 12 (2): 1-9
+
+    Examples
+    --------
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> x = np.arange(0, 10)
+    >>> y = np.arange(0, 10)
+
+    >>> integrate.simpson(y, x=x)
+    40.5
+
+    >>> y = np.power(x, 3)
+    >>> integrate.simpson(y, x=x)
+    1640.5
+    >>> integrate.quad(lambda x: x**3, 0, 9)[0]
+    1640.25
+
+    """
+    y = np.asarray(y)
+    nd = len(y.shape)
+    N = y.shape[axis]
+    last_dx = dx
+    returnshape = 0
+    if x is not None:
+        x = np.asarray(x)
+        if len(x.shape) == 1:
+            shapex = [1] * nd
+            shapex[axis] = x.shape[0]
+            saveshape = x.shape
+            returnshape = 1
+            x = x.reshape(tuple(shapex))
+        elif len(x.shape) != len(y.shape):
+            raise ValueError("If given, shape of x must be 1-D or the "
+                             "same as y.")
+        if x.shape[axis] != N:
+            raise ValueError("If given, length of x along axis must be the "
+                             "same as y.")
+
+    if N % 2 == 0:
+        val = 0.0
+        result = 0.0
+        slice_all = (slice(None),) * nd
+
+        if N == 2:
+            # need at least 3 points in integration axis to form parabolic
+            # segment. If there are two points then any of 'avg', 'first',
+            # 'last' should give the same result.
+            slice1 = tupleset(slice_all, axis, -1)
+            slice2 = tupleset(slice_all, axis, -2)
+            if x is not None:
+                last_dx = x[slice1] - x[slice2]
+            val += 0.5 * last_dx * (y[slice1] + y[slice2])
+        else:
+            # use Simpson's rule on first intervals
+            result = _basic_simpson(y, 0, N-3, x, dx, axis)
+
+            slice1 = tupleset(slice_all, axis, -1)
+            slice2 = tupleset(slice_all, axis, -2)
+            slice3 = tupleset(slice_all, axis, -3)
+
+            h = np.asarray([dx, dx], dtype=np.float64)
+            if x is not None:
+                # grab the last two spacings from the appropriate axis
+                hm2 = tupleset(slice_all, axis, slice(-2, -1, 1))
+                hm1 = tupleset(slice_all, axis, slice(-1, None, 1))
+
+                diffs = np.float64(np.diff(x, axis=axis))
+                h = [np.squeeze(diffs[hm2], axis=axis),
+                     np.squeeze(diffs[hm1], axis=axis)]
+
+            # This is the correction for the last interval according to
+            # Cartwright.
+            # However, I used the equations given at
+            # https://en.wikipedia.org/wiki/Simpson%27s_rule#Composite_Simpson's_rule_for_irregularly_spaced_data
+            # A footnote on Wikipedia says:
+            # Cartwright 2017, Equation 8. The equation in Cartwright is
+            # calculating the first interval whereas the equations in the
+            # Wikipedia article are adjusting for the last integral. If the
+            # proper algebraic substitutions are made, the equation results in
+            # the values shown.
+            num = 2 * h[1] ** 2 + 3 * h[0] * h[1]
+            den = 6 * (h[1] + h[0])
+            alpha = np.true_divide(
+                num,
+                den,
+                out=np.zeros_like(den),
+                where=den != 0
+            )
+
+            num = h[1] ** 2 + 3.0 * h[0] * h[1]
+            den = 6 * h[0]
+            beta = np.true_divide(
+                num,
+                den,
+                out=np.zeros_like(den),
+                where=den != 0
+            )
+
+            num = 1 * h[1] ** 3
+            den = 6 * h[0] * (h[0] + h[1])
+            eta = np.true_divide(
+                num,
+                den,
+                out=np.zeros_like(den),
+                where=den != 0
+            )
+
+            result += alpha*y[slice1] + beta*y[slice2] - eta*y[slice3]
+
+        result += val
+    else:
+        result = _basic_simpson(y, 0, N-2, x, dx, axis)
+    if returnshape:
+        x = x.reshape(saveshape)
+    return result
+
+
+def _cumulatively_sum_simpson_integrals(
+    y: np.ndarray, 
+    dx: np.ndarray, 
+    integration_func: Callable[[np.ndarray, np.ndarray], np.ndarray],
+) -> np.ndarray:
+    """Calculate cumulative sum of Simpson integrals.
+    Takes as input the integration function to be used. 
+    The integration_func is assumed to return the cumulative sum using
+    composite Simpson's rule. Assumes the axis of summation is -1.
+    """
+    sub_integrals_h1 = integration_func(y, dx)
+    sub_integrals_h2 = integration_func(y[..., ::-1], dx[..., ::-1])[..., ::-1]
+    
+    shape = list(sub_integrals_h1.shape)
+    shape[-1] += 1
+    sub_integrals = np.empty(shape)
+    sub_integrals[..., :-1:2] = sub_integrals_h1[..., ::2]
+    sub_integrals[..., 1::2] = sub_integrals_h2[..., ::2]
+    # Integral over last subinterval can only be calculated from 
+    # formula for h2
+    sub_integrals[..., -1] = sub_integrals_h2[..., -1]
+    res = np.cumsum(sub_integrals, axis=-1)
+    return res
+
+
+def _cumulative_simpson_equal_intervals(y: np.ndarray, dx: np.ndarray) -> np.ndarray:
+    """Calculate the Simpson integrals for all h1 intervals assuming equal interval
+    widths. The function can also be used to calculate the integral for all
+    h2 intervals by reversing the inputs, `y` and `dx`.
+    """
+    d = dx[..., :-1]
+    f1 = y[..., :-2]
+    f2 = y[..., 1:-1]
+    f3 = y[..., 2:]
+
+    # Calculate integral over the subintervals (eqn (10) of Reference [2])
+    return d / 3 * (5 * f1 / 4 + 2 * f2 - f3 / 4)
+
+
+def _cumulative_simpson_unequal_intervals(y: np.ndarray, dx: np.ndarray) -> np.ndarray:
+    """Calculate the Simpson integrals for all h1 intervals assuming unequal interval
+    widths. The function can also be used to calculate the integral for all
+    h2 intervals by reversing the inputs, `y` and `dx`.
+    """
+    x21 = dx[..., :-1]
+    x32 = dx[..., 1:]
+    f1 = y[..., :-2]
+    f2 = y[..., 1:-1]
+    f3 = y[..., 2:]
+
+    x31 = x21 + x32
+    x21_x31 = x21/x31
+    x21_x32 = x21/x32
+    x21x21_x31x32 = x21_x31 * x21_x32
+
+    # Calculate integral over the subintervals (eqn (8) of Reference [2])
+    coeff1 = 3 - x21_x31
+    coeff2 = 3 + x21x21_x31x32 + x21_x31
+    coeff3 = -x21x21_x31x32
+
+    return x21/6 * (coeff1*f1 + coeff2*f2 + coeff3*f3)
+
+
+def _ensure_float_array(arr: npt.ArrayLike) -> np.ndarray:
+    arr = np.asarray(arr)
+    if np.issubdtype(arr.dtype, np.integer):
+        arr = arr.astype(float, copy=False)
+    return arr
+
+
+def cumulative_simpson(y, *, x=None, dx=1.0, axis=-1, initial=None):
+    r"""
+    Cumulatively integrate y(x) using the composite Simpson's 1/3 rule.
+    The integral of the samples at every point is calculated by assuming a 
+    quadratic relationship between each point and the two adjacent points.
+
+    Parameters
+    ----------
+    y : array_like
+        Values to integrate. Requires at least one point along `axis`. If two or fewer
+        points are provided along `axis`, Simpson's integration is not possible and the
+        result is calculated with `cumulative_trapezoid`.
+    x : array_like, optional
+        The coordinate to integrate along. Must have the same shape as `y` or
+        must be 1D with the same length as `y` along `axis`. `x` must also be
+        strictly increasing along `axis`.
+        If `x` is None (default), integration is performed using spacing `dx`
+        between consecutive elements in `y`.
+    dx : scalar or array_like, optional
+        Spacing between elements of `y`. Only used if `x` is None. Can either 
+        be a float, or an array with the same shape as `y`, but of length one along
+        `axis`. Default is 1.0.
+    axis : int, optional
+        Specifies the axis to integrate along. Default is -1 (last axis).
+    initial : scalar or array_like, optional
+        If given, insert this value at the beginning of the returned result,
+        and add it to the rest of the result. Default is None, which means no
+        value at ``x[0]`` is returned and `res` has one element less than `y`
+        along the axis of integration. Can either be a float, or an array with
+        the same shape as `y`, but of length one along `axis`.
+
+    Returns
+    -------
+    res : ndarray
+        The result of cumulative integration of `y` along `axis`.
+        If `initial` is None, the shape is such that the axis of integration
+        has one less value than `y`. If `initial` is given, the shape is equal
+        to that of `y`.
+
+    See Also
+    --------
+    numpy.cumsum
+    cumulative_trapezoid : cumulative integration using the composite 
+        trapezoidal rule
+    simpson : integrator for sampled data using the Composite Simpson's Rule
+
+    Notes
+    -----
+
+    .. versionadded:: 1.12.0
+
+    The composite Simpson's 1/3 method can be used to approximate the definite 
+    integral of a sampled input function :math:`y(x)` [1]_. The method assumes 
+    a quadratic relationship over the interval containing any three consecutive
+    sampled points.
+
+    Consider three consecutive points: 
+    :math:`(x_1, y_1), (x_2, y_2), (x_3, y_3)`.
+
+    Assuming a quadratic relationship over the three points, the integral over
+    the subinterval between :math:`x_1` and :math:`x_2` is given by formula
+    (8) of [2]_:
+    
+    .. math::
+        \int_{x_1}^{x_2} y(x) dx\ &= \frac{x_2-x_1}{6}\left[\
+        \left\{3-\frac{x_2-x_1}{x_3-x_1}\right\} y_1 + \
+        \left\{3 + \frac{(x_2-x_1)^2}{(x_3-x_2)(x_3-x_1)} + \
+        \frac{x_2-x_1}{x_3-x_1}\right\} y_2\\
+        - \frac{(x_2-x_1)^2}{(x_3-x_2)(x_3-x_1)} y_3\right]
+
+    The integral between :math:`x_2` and :math:`x_3` is given by swapping
+    appearances of :math:`x_1` and :math:`x_3`. The integral is estimated
+    separately for each subinterval and then cumulatively summed to obtain
+    the final result.
+    
+    For samples that are equally spaced, the result is exact if the function
+    is a polynomial of order three or less [1]_ and the number of subintervals
+    is even. Otherwise, the integral is exact for polynomials of order two or
+    less. 
+
+    References
+    ----------
+    .. [1] Wikipedia page: https://en.wikipedia.org/wiki/Simpson's_rule
+    .. [2] Cartwright, Kenneth V. Simpson's Rule Cumulative Integration with
+            MS Excel and Irregularly-spaced Data. Journal of Mathematical
+            Sciences and Mathematics Education. 12 (2): 1-9
+
+    Examples
+    --------
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-2, 2, num=20)
+    >>> y = x**2
+    >>> y_int = integrate.cumulative_simpson(y, x=x, initial=0)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, y_int, 'ro', x, x**3/3 - (x[0])**3/3, 'b-')
+    >>> ax.grid()
+    >>> plt.show()
+
+    The output of `cumulative_simpson` is similar to that of iteratively
+    calling `simpson` with successively higher upper limits of integration, but
+    not identical.
+
+    >>> def cumulative_simpson_reference(y, x):
+    ...     return np.asarray([integrate.simpson(y[:i], x=x[:i])
+    ...                        for i in range(2, len(y) + 1)])
+    >>>
+    >>> rng = np.random.default_rng(354673834679465)
+    >>> x, y = rng.random(size=(2, 10))
+    >>> x.sort()
+    >>>
+    >>> res = integrate.cumulative_simpson(y, x=x)
+    >>> ref = cumulative_simpson_reference(y, x)
+    >>> equal = np.abs(res - ref) < 1e-15
+    >>> equal  # not equal when `simpson` has even number of subintervals
+    array([False,  True, False,  True, False,  True, False,  True,  True])
+
+    This is expected: because `cumulative_simpson` has access to more
+    information than `simpson`, it can typically produce more accurate
+    estimates of the underlying integral over subintervals.
+
+    """
+    y = _ensure_float_array(y)
+
+    # validate `axis` and standardize to work along the last axis
+    original_y = y
+    original_shape = y.shape
+    try:
+        y = np.swapaxes(y, axis, -1)
+    except IndexError as e:
+        message = f"`axis={axis}` is not valid for `y` with `y.ndim={y.ndim}`."
+        raise ValueError(message) from e
+    if y.shape[-1] < 3:
+        res = cumulative_trapezoid(original_y, x, dx=dx, axis=axis, initial=None)
+        res = np.swapaxes(res, axis, -1)
+
+    elif x is not None:
+        x = _ensure_float_array(x)
+        message = ("If given, shape of `x` must be the same as `y` or 1-D with "
+                   "the same length as `y` along `axis`.")
+        if not (x.shape == original_shape
+                or (x.ndim == 1 and len(x) == original_shape[axis])):
+            raise ValueError(message)
+
+        x = np.broadcast_to(x, y.shape) if x.ndim == 1 else np.swapaxes(x, axis, -1)
+        dx = np.diff(x, axis=-1)
+        if np.any(dx <= 0):
+            raise ValueError("Input x must be strictly increasing.")
+        res = _cumulatively_sum_simpson_integrals(
+            y, dx, _cumulative_simpson_unequal_intervals
+        )
+
+    else:
+        dx = _ensure_float_array(dx)
+        final_dx_shape = tupleset(original_shape, axis, original_shape[axis] - 1)
+        alt_input_dx_shape = tupleset(original_shape, axis, 1)
+        message = ("If provided, `dx` must either be a scalar or have the same "
+                   "shape as `y` but with only 1 point along `axis`.")
+        if not (dx.ndim == 0 or dx.shape == alt_input_dx_shape):
+            raise ValueError(message)
+        dx = np.broadcast_to(dx, final_dx_shape)
+        dx = np.swapaxes(dx, axis, -1)
+        res = _cumulatively_sum_simpson_integrals(
+            y, dx, _cumulative_simpson_equal_intervals
+        )
+
+    if initial is not None:
+        initial = _ensure_float_array(initial)
+        alt_initial_input_shape = tupleset(original_shape, axis, 1)
+        message = ("If provided, `initial` must either be a scalar or have the "
+                   "same shape as `y` but with only 1 point along `axis`.")
+        if not (initial.ndim == 0 or initial.shape == alt_initial_input_shape):
+            raise ValueError(message)
+        initial = np.broadcast_to(initial, alt_initial_input_shape)
+        initial = np.swapaxes(initial, axis, -1)
+
+        res += initial
+        res = np.concatenate((initial, res), axis=-1)
+
+    res = np.swapaxes(res, -1, axis)
+    return res
+
+
+def romb(y, dx=1.0, axis=-1, show=False):
+    """
+    Romberg integration using samples of a function.
+
+    Parameters
+    ----------
+    y : array_like
+        A vector of ``2**k + 1`` equally-spaced samples of a function.
+    dx : float, optional
+        The sample spacing. Default is 1.
+    axis : int, optional
+        The axis along which to integrate. Default is -1 (last axis).
+    show : bool, optional
+        When `y` is a single 1-D array, then if this argument is True
+        print the table showing Richardson extrapolation from the
+        samples. Default is False.
+
+    Returns
+    -------
+    romb : ndarray
+        The integrated result for `axis`.
+
+    See Also
+    --------
+    quad : adaptive quadrature using QUADPACK
+    fixed_quad : fixed-order Gaussian quadrature
+    dblquad : double integrals
+    tplquad : triple integrals
+    simpson : integrators for sampled data
+    cumulative_trapezoid : cumulative integration for sampled data
+
+    Examples
+    --------
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> x = np.arange(10, 14.25, 0.25)
+    >>> y = np.arange(3, 12)
+
+    >>> integrate.romb(y)
+    56.0
+
+    >>> y = np.sin(np.power(x, 2.5))
+    >>> integrate.romb(y)
+    -0.742561336672229
+
+    >>> integrate.romb(y, show=True)
+    Richardson Extrapolation Table for Romberg Integration
+    ======================================================
+    -0.81576
+     4.63862  6.45674
+    -1.10581 -3.02062 -3.65245
+    -2.57379 -3.06311 -3.06595 -3.05664
+    -1.34093 -0.92997 -0.78776 -0.75160 -0.74256
+    ======================================================
+    -0.742561336672229  # may vary
+
+    """
+    y = np.asarray(y)
+    nd = len(y.shape)
+    Nsamps = y.shape[axis]
+    Ninterv = Nsamps-1
+    n = 1
+    k = 0
+    while n < Ninterv:
+        n <<= 1
+        k += 1
+    if n != Ninterv:
+        raise ValueError("Number of samples must be one plus a "
+                         "non-negative power of 2.")
+
+    R = {}
+    slice_all = (slice(None),) * nd
+    slice0 = tupleset(slice_all, axis, 0)
+    slicem1 = tupleset(slice_all, axis, -1)
+    h = Ninterv * np.asarray(dx, dtype=float)
+    R[(0, 0)] = (y[slice0] + y[slicem1])/2.0*h
+    slice_R = slice_all
+    start = stop = step = Ninterv
+    for i in range(1, k+1):
+        start >>= 1
+        slice_R = tupleset(slice_R, axis, slice(start, stop, step))
+        step >>= 1
+        R[(i, 0)] = 0.5*(R[(i-1, 0)] + h*y[slice_R].sum(axis=axis))
+        for j in range(1, i+1):
+            prev = R[(i, j-1)]
+            R[(i, j)] = prev + (prev-R[(i-1, j-1)]) / ((1 << (2*j))-1)
+        h /= 2.0
+
+    if show:
+        if not np.isscalar(R[(0, 0)]):
+            print("*** Printing table only supported for integrals" +
+                  " of a single data set.")
+        else:
+            try:
+                precis = show[0]
+            except (TypeError, IndexError):
+                precis = 5
+            try:
+                width = show[1]
+            except (TypeError, IndexError):
+                width = 8
+            formstr = f"%{width}.{precis}f"
+
+            title = "Richardson Extrapolation Table for Romberg Integration"
+            print(title, "=" * len(title), sep="\n", end="\n")
+            for i in range(k+1):
+                for j in range(i+1):
+                    print(formstr % R[(i, j)], end=" ")
+                print()
+            print("=" * len(title))
+
+    return R[(k, k)]
+
+
+# Coefficients for Newton-Cotes quadrature
+#
+# These are the points being used
+#  to construct the local interpolating polynomial
+#  a are the weights for Newton-Cotes integration
+#  B is the error coefficient.
+#  error in these coefficients grows as N gets larger.
+#  or as samples are closer and closer together
+
+# You can use maxima to find these rational coefficients
+#  for equally spaced data using the commands
+#  a(i,N) := (integrate(product(r-j,j,0,i-1) * product(r-j,j,i+1,N),r,0,N)
+#             / ((N-i)! * i!) * (-1)^(N-i));
+#  Be(N) := N^(N+2)/(N+2)! * (N/(N+3) - sum((i/N)^(N+2)*a(i,N),i,0,N));
+#  Bo(N) := N^(N+1)/(N+1)! * (N/(N+2) - sum((i/N)^(N+1)*a(i,N),i,0,N));
+#  B(N) := (if (mod(N,2)=0) then Be(N) else Bo(N));
+#
+# pre-computed for equally-spaced weights
+#
+# num_a, den_a, int_a, num_B, den_B = _builtincoeffs[N]
+#
+#  a = num_a*array(int_a)/den_a
+#  B = num_B*1.0 / den_B
+#
+#  integrate(f(x),x,x_0,x_N) = dx*sum(a*f(x_i)) + B*(dx)^(2k+3) f^(2k+2)(x*)
+#    where k = N // 2
+#
+_builtincoeffs = {
+    1: (1,2,[1,1],-1,12),
+    2: (1,3,[1,4,1],-1,90),
+    3: (3,8,[1,3,3,1],-3,80),
+    4: (2,45,[7,32,12,32,7],-8,945),
+    5: (5,288,[19,75,50,50,75,19],-275,12096),
+    6: (1,140,[41,216,27,272,27,216,41],-9,1400),
+    7: (7,17280,[751,3577,1323,2989,2989,1323,3577,751],-8183,518400),
+    8: (4,14175,[989,5888,-928,10496,-4540,10496,-928,5888,989],
+        -2368,467775),
+    9: (9,89600,[2857,15741,1080,19344,5778,5778,19344,1080,
+                 15741,2857], -4671, 394240),
+    10: (5,299376,[16067,106300,-48525,272400,-260550,427368,
+                   -260550,272400,-48525,106300,16067],
+         -673175, 163459296),
+    11: (11,87091200,[2171465,13486539,-3237113, 25226685,-9595542,
+                      15493566,15493566,-9595542,25226685,-3237113,
+                      13486539,2171465], -2224234463, 237758976000),
+    12: (1, 5255250, [1364651,9903168,-7587864,35725120,-51491295,
+                      87516288,-87797136,87516288,-51491295,35725120,
+                      -7587864,9903168,1364651], -3012, 875875),
+    13: (13, 402361344000,[8181904909, 56280729661, -31268252574,
+                           156074417954,-151659573325,206683437987,
+                           -43111992612,-43111992612,206683437987,
+                           -151659573325,156074417954,-31268252574,
+                           56280729661,8181904909], -2639651053,
+         344881152000),
+    14: (7, 2501928000, [90241897,710986864,-770720657,3501442784,
+                         -6625093363,12630121616,-16802270373,19534438464,
+                         -16802270373,12630121616,-6625093363,3501442784,
+                         -770720657,710986864,90241897], -3740727473,
+         1275983280000)
+    }
+
+
+def newton_cotes(rn, equal=0):
+    r"""
+    Return weights and error coefficient for Newton-Cotes integration.
+
+    Suppose we have (N+1) samples of f at the positions
+    x_0, x_1, ..., x_N. Then an N-point Newton-Cotes formula for the
+    integral between x_0 and x_N is:
+
+    :math:`\int_{x_0}^{x_N} f(x)dx = \Delta x \sum_{i=0}^{N} a_i f(x_i)
+    + B_N (\Delta x)^{N+2} f^{N+1} (\xi)`
+
+    where :math:`\xi \in [x_0,x_N]`
+    and :math:`\Delta x = \frac{x_N-x_0}{N}` is the average samples spacing.
+
+    If the samples are equally-spaced and N is even, then the error
+    term is :math:`B_N (\Delta x)^{N+3} f^{N+2}(\xi)`.
+
+    Parameters
+    ----------
+    rn : int
+        The integer order for equally-spaced data or the relative positions of
+        the samples with the first sample at 0 and the last at N, where N+1 is
+        the length of `rn`. N is the order of the Newton-Cotes integration.
+    equal : int, optional
+        Set to 1 to enforce equally spaced data.
+
+    Returns
+    -------
+    an : ndarray
+        1-D array of weights to apply to the function at the provided sample
+        positions.
+    B : float
+        Error coefficient.
+
+    Notes
+    -----
+    Normally, the Newton-Cotes rules are used on smaller integration
+    regions and a composite rule is used to return the total integral.
+
+    Examples
+    --------
+    Compute the integral of sin(x) in [0, :math:`\pi`]:
+
+    >>> from scipy.integrate import newton_cotes
+    >>> import numpy as np
+    >>> def f(x):
+    ...     return np.sin(x)
+    >>> a = 0
+    >>> b = np.pi
+    >>> exact = 2
+    >>> for N in [2, 4, 6, 8, 10]:
+    ...     x = np.linspace(a, b, N + 1)
+    ...     an, B = newton_cotes(N, 1)
+    ...     dx = (b - a) / N
+    ...     quad = dx * np.sum(an * f(x))
+    ...     error = abs(quad - exact)
+    ...     print('{:2d}  {:10.9f}  {:.5e}'.format(N, quad, error))
+    ...
+     2   2.094395102   9.43951e-02
+     4   1.998570732   1.42927e-03
+     6   2.000017814   1.78136e-05
+     8   1.999999835   1.64725e-07
+    10   2.000000001   1.14677e-09
+
+    """
+    try:
+        N = len(rn)-1
+        if equal:
+            rn = np.arange(N+1)
+        elif np.all(np.diff(rn) == 1):
+            equal = 1
+    except Exception:
+        N = rn
+        rn = np.arange(N+1)
+        equal = 1
+
+    if equal and N in _builtincoeffs:
+        na, da, vi, nb, db = _builtincoeffs[N]
+        an = na * np.array(vi, dtype=float) / da
+        return an, float(nb)/db
+
+    if (rn[0] != 0) or (rn[-1] != N):
+        raise ValueError("The sample positions must start at 0"
+                         " and end at N")
+    yi = rn / float(N)
+    ti = 2 * yi - 1
+    nvec = np.arange(N+1)
+    C = ti ** nvec[:, np.newaxis]
+    Cinv = np.linalg.inv(C)
+    # improve precision of result
+    for i in range(2):
+        Cinv = 2*Cinv - Cinv.dot(C).dot(Cinv)
+    vec = 2.0 / (nvec[::2]+1)
+    ai = Cinv[:, ::2].dot(vec) * (N / 2.)
+
+    if (N % 2 == 0) and equal:
+        BN = N/(N+3.)
+        power = N+2
+    else:
+        BN = N/(N+2.)
+        power = N+1
+
+    BN = BN - np.dot(yi**power, ai)
+    p1 = power+1
+    fac = power*math.log(N) - gammaln(p1)
+    fac = math.exp(fac)
+    return ai, BN*fac
+
+
+def _qmc_quad_iv(func, a, b, n_points, n_estimates, qrng, log):
+
+    # lazy import to avoid issues with partially-initialized submodule
+    if not hasattr(qmc_quad, 'qmc'):
+        from scipy import stats
+        qmc_quad.stats = stats
+    else:
+        stats = qmc_quad.stats
+
+    if not callable(func):
+        message = "`func` must be callable."
+        raise TypeError(message)
+
+    # a, b will be modified, so copy. Oh well if it's copied twice.
+    a = np.atleast_1d(a).copy()
+    b = np.atleast_1d(b).copy()
+    a, b = np.broadcast_arrays(a, b)
+    dim = a.shape[0]
+
+    try:
+        func((a + b) / 2)
+    except Exception as e:
+        message = ("`func` must evaluate the integrand at points within "
+                   "the integration range; e.g. `func( (a + b) / 2)` "
+                   "must return the integrand at the centroid of the "
+                   "integration volume.")
+        raise ValueError(message) from e
+
+    try:
+        func(np.array([a, b]).T)
+        vfunc = func
+    except Exception as e:
+        message = ("Exception encountered when attempting vectorized call to "
+                   f"`func`: {e}. For better performance, `func` should "
+                   "accept two-dimensional array `x` with shape `(len(a), "
+                   "n_points)` and return an array of the integrand value at "
+                   "each of the `n_points.")
+        warnings.warn(message, stacklevel=3)
+
+        def vfunc(x):
+            return np.apply_along_axis(func, axis=-1, arr=x)
+
+    n_points_int = np.int64(n_points)
+    if n_points != n_points_int:
+        message = "`n_points` must be an integer."
+        raise TypeError(message)
+
+    n_estimates_int = np.int64(n_estimates)
+    if n_estimates != n_estimates_int:
+        message = "`n_estimates` must be an integer."
+        raise TypeError(message)
+
+    if qrng is None:
+        qrng = stats.qmc.Halton(dim)
+    elif not isinstance(qrng, stats.qmc.QMCEngine):
+        message = "`qrng` must be an instance of scipy.stats.qmc.QMCEngine."
+        raise TypeError(message)
+
+    if qrng.d != a.shape[0]:
+        message = ("`qrng` must be initialized with dimensionality equal to "
+                   "the number of variables in `a`, i.e., "
+                   "`qrng.random().shape[-1]` must equal `a.shape[0]`.")
+        raise ValueError(message)
+
+    rng_seed = getattr(qrng, 'rng_seed', None)
+    rng = stats._qmc.check_random_state(rng_seed)
+
+    if log not in {True, False}:
+        message = "`log` must be boolean (`True` or `False`)."
+        raise TypeError(message)
+
+    return (vfunc, a, b, n_points_int, n_estimates_int, qrng, rng, log, stats)
+
+
+QMCQuadResult = namedtuple('QMCQuadResult', ['integral', 'standard_error'])
+
+
+def qmc_quad(func, a, b, *, n_estimates=8, n_points=1024, qrng=None,
+             log=False):
+    """
+    Compute an integral in N-dimensions using Quasi-Monte Carlo quadrature.
+
+    Parameters
+    ----------
+    func : callable
+        The integrand. Must accept a single argument ``x``, an array which
+        specifies the point(s) at which to evaluate the scalar-valued
+        integrand, and return the value(s) of the integrand.
+        For efficiency, the function should be vectorized to accept an array of
+        shape ``(d, n_points)``, where ``d`` is the number of variables (i.e.
+        the dimensionality of the function domain) and `n_points` is the number
+        of quadrature points, and return an array of shape ``(n_points,)``,
+        the integrand at each quadrature point.
+    a, b : array-like
+        One-dimensional arrays specifying the lower and upper integration
+        limits, respectively, of each of the ``d`` variables.
+    n_estimates, n_points : int, optional
+        `n_estimates` (default: 8) statistically independent QMC samples, each
+        of `n_points` (default: 1024) points, will be generated by `qrng`.
+        The total number of points at which the integrand `func` will be
+        evaluated is ``n_points * n_estimates``. See Notes for details.
+    qrng : `~scipy.stats.qmc.QMCEngine`, optional
+        An instance of the QMCEngine from which to sample QMC points.
+        The QMCEngine must be initialized to a number of dimensions ``d``
+        corresponding with the number of variables ``x1, ..., xd`` passed to
+        `func`.
+        The provided QMCEngine is used to produce the first integral estimate.
+        If `n_estimates` is greater than one, additional QMCEngines are
+        spawned from the first (with scrambling enabled, if it is an option.)
+        If a QMCEngine is not provided, the default `scipy.stats.qmc.Halton`
+        will be initialized with the number of dimensions determine from
+        the length of `a`.
+    log : boolean, default: False
+        When set to True, `func` returns the log of the integrand, and
+        the result object contains the log of the integral.
+
+    Returns
+    -------
+    result : object
+        A result object with attributes:
+
+        integral : float
+            The estimate of the integral.
+        standard_error :
+            The error estimate. See Notes for interpretation.
+
+    Notes
+    -----
+    Values of the integrand at each of the `n_points` points of a QMC sample
+    are used to produce an estimate of the integral. This estimate is drawn
+    from a population of possible estimates of the integral, the value of
+    which we obtain depends on the particular points at which the integral
+    was evaluated. We perform this process `n_estimates` times, each time
+    evaluating the integrand at different scrambled QMC points, effectively
+    drawing i.i.d. random samples from the population of integral estimates.
+    The sample mean :math:`m` of these integral estimates is an
+    unbiased estimator of the true value of the integral, and the standard
+    error of the mean :math:`s` of these estimates may be used to generate
+    confidence intervals using the t distribution with ``n_estimates - 1``
+    degrees of freedom. Perhaps counter-intuitively, increasing `n_points`
+    while keeping the total number of function evaluation points
+    ``n_points * n_estimates`` fixed tends to reduce the actual error, whereas
+    increasing `n_estimates` tends to decrease the error estimate.
+
+    Examples
+    --------
+    QMC quadrature is particularly useful for computing integrals in higher
+    dimensions. An example integrand is the probability density function
+    of a multivariate normal distribution.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> dim = 8
+    >>> mean = np.zeros(dim)
+    >>> cov = np.eye(dim)
+    >>> def func(x):
+    ...     # `multivariate_normal` expects the _last_ axis to correspond with
+    ...     # the dimensionality of the space, so `x` must be transposed
+    ...     return stats.multivariate_normal.pdf(x.T, mean, cov)
+
+    To compute the integral over the unit hypercube:
+
+    >>> from scipy.integrate import qmc_quad
+    >>> a = np.zeros(dim)
+    >>> b = np.ones(dim)
+    >>> rng = np.random.default_rng()
+    >>> qrng = stats.qmc.Halton(d=dim, seed=rng)
+    >>> n_estimates = 8
+    >>> res = qmc_quad(func, a, b, n_estimates=n_estimates, qrng=qrng)
+    >>> res.integral, res.standard_error
+    (0.00018429555666024108, 1.0389431116001344e-07)
+
+    A two-sided, 99% confidence interval for the integral may be estimated
+    as:
+
+    >>> t = stats.t(df=n_estimates-1, loc=res.integral,
+    ...             scale=res.standard_error)
+    >>> t.interval(0.99)
+    (0.0001839319802536469, 0.00018465913306683527)
+
+    Indeed, the value reported by `scipy.stats.multivariate_normal` is
+    within this range.
+
+    >>> stats.multivariate_normal.cdf(b, mean, cov, lower_limit=a)
+    0.00018430867675187443
+
+    """
+    args = _qmc_quad_iv(func, a, b, n_points, n_estimates, qrng, log)
+    func, a, b, n_points, n_estimates, qrng, rng, log, stats = args
+
+    def sum_product(integrands, dA, log=False):
+        if log:
+            return logsumexp(integrands) + np.log(dA)
+        else:
+            return np.sum(integrands * dA)
+
+    def mean(estimates, log=False):
+        if log:
+            return logsumexp(estimates) - np.log(n_estimates)
+        else:
+            return np.mean(estimates)
+
+    def std(estimates, m=None, ddof=0, log=False):
+        m = m or mean(estimates, log)
+        if log:
+            estimates, m = np.broadcast_arrays(estimates, m)
+            temp = np.vstack((estimates, m + np.pi * 1j))
+            diff = logsumexp(temp, axis=0)
+            return np.real(0.5 * (logsumexp(2 * diff)
+                                  - np.log(n_estimates - ddof)))
+        else:
+            return np.std(estimates, ddof=ddof)
+
+    def sem(estimates, m=None, s=None, log=False):
+        m = m or mean(estimates, log)
+        s = s or std(estimates, m, ddof=1, log=log)
+        if log:
+            return s - 0.5*np.log(n_estimates)
+        else:
+            return s / np.sqrt(n_estimates)
+
+    # The sign of the integral depends on the order of the limits. Fix this by
+    # ensuring that lower bounds are indeed lower and setting sign of resulting
+    # integral manually
+    if np.any(a == b):
+        message = ("A lower limit was equal to an upper limit, so the value "
+                   "of the integral is zero by definition.")
+        warnings.warn(message, stacklevel=2)
+        return QMCQuadResult(-np.inf if log else 0, 0)
+
+    i_swap = b < a
+    sign = (-1)**(i_swap.sum(axis=-1))  # odd # of swaps -> negative
+    a[i_swap], b[i_swap] = b[i_swap], a[i_swap]
+
+    A = np.prod(b - a)
+    dA = A / n_points
+
+    estimates = np.zeros(n_estimates)
+    rngs = _rng_spawn(qrng.rng, n_estimates)
+    for i in range(n_estimates):
+        # Generate integral estimate
+        sample = qrng.random(n_points)
+        # The rationale for transposing is that this allows users to easily
+        # unpack `x` into separate variables, if desired. This is consistent
+        # with the `xx` array passed into the `scipy.integrate.nquad` `func`.
+        x = stats.qmc.scale(sample, a, b).T  # (n_dim, n_points)
+        integrands = func(x)
+        estimates[i] = sum_product(integrands, dA, log)
+
+        # Get a new, independently-scrambled QRNG for next time
+        qrng = type(qrng)(seed=rngs[i], **qrng._init_quad)
+
+    integral = mean(estimates, log)
+    standard_error = sem(estimates, m=integral, log=log)
+    integral = integral + np.pi*1j if (log and sign < 0) else integral*sign
+    return QMCQuadResult(integral, standard_error)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_tanhsinh.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_tanhsinh.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3cb94fc65435c4529dfafcc71cd20e141033c2a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_tanhsinh.py
@@ -0,0 +1,1385 @@
+# mypy: disable-error-code="attr-defined"
+import math
+import numpy as np
+from scipy import special
+import scipy._lib._elementwise_iterative_method as eim
+from scipy._lib._util import _RichResult
+from scipy._lib._array_api import (array_namespace, xp_copy, xp_ravel,
+                                   xp_promote)
+
+
+__all__ = ['nsum']
+
+
+# todo:
+#  figure out warning situation
+#  address https://github.com/scipy/scipy/pull/18650#discussion_r1233032521
+#  without `minweight`, we are also suppressing infinities within the interval.
+#    Is that OK? If so, we can probably get rid of `status=3`.
+#  Add heuristic to stop when improvement is too slow / antithrashing
+#  support singularities? interval subdivision? this feature will be added
+#    eventually, but do we adjust the interface now?
+#  When doing log-integration, should the tolerances control the error of the
+#    log-integral or the error of the integral?  The trouble is that `log`
+#    inherently looses some precision so it may not be possible to refine
+#    the integral further. Example: 7th moment of stats.f(15, 20)
+#  respect function evaluation limit?
+#  make public?
+
+
+def tanhsinh(f, a, b, *, args=(), log=False, maxlevel=None, minlevel=2,
+             atol=None, rtol=None, preserve_shape=False, callback=None):
+    """Evaluate a convergent integral numerically using tanh-sinh quadrature.
+
+    In practice, tanh-sinh quadrature achieves quadratic convergence for
+    many integrands: the number of accurate *digits* scales roughly linearly
+    with the number of function evaluations [1]_.
+
+    Either or both of the limits of integration may be infinite, and
+    singularities at the endpoints are acceptable. Divergent integrals and
+    integrands with non-finite derivatives or singularities within an interval
+    are out of scope, but the latter may be evaluated be calling `tanhsinh` on
+    each sub-interval separately.
+
+    Parameters
+    ----------
+    f : callable
+        The function to be integrated. The signature must be::
+
+            f(xi: ndarray, *argsi) -> ndarray
+
+        where each element of ``xi`` is a finite real number and ``argsi`` is a tuple,
+        which may contain an arbitrary number of arrays that are broadcastable
+        with ``xi``. `f` must be an elementwise function: see documentation of parameter
+        `preserve_shape` for details. It must not mutate the array ``xi`` or the arrays
+        in ``argsi``.
+        If ``f`` returns a value with complex dtype when evaluated at
+        either endpoint, subsequent arguments ``x`` will have complex dtype
+        (but zero imaginary part).
+    a, b : float array_like
+        Real lower and upper limits of integration. Must be broadcastable with one
+        another and with arrays in `args`. Elements may be infinite.
+    args : tuple of array_like, optional
+        Additional positional array arguments to be passed to `f`. Arrays
+        must be broadcastable with one another and the arrays of `a` and `b`.
+        If the callable for which the root is desired requires arguments that are
+        not broadcastable with `x`, wrap that callable with `f` such that `f`
+        accepts only `x` and broadcastable ``*args``.
+    log : bool, default: False
+        Setting to True indicates that `f` returns the log of the integrand
+        and that `atol` and `rtol` are expressed as the logs of the absolute
+        and relative errors. In this case, the result object will contain the
+        log of the integral and error. This is useful for integrands for which
+        numerical underflow or overflow would lead to inaccuracies.
+        When ``log=True``, the integrand (the exponential of `f`) must be real,
+        but it may be negative, in which case the log of the integrand is a
+        complex number with an imaginary part that is an odd multiple of π.
+    maxlevel : int, default: 10
+        The maximum refinement level of the algorithm.
+
+        At the zeroth level, `f` is called once, performing 16 function
+        evaluations. At each subsequent level, `f` is called once more,
+        approximately doubling the number of function evaluations that have
+        been performed. Accordingly, for many integrands, each successive level
+        will double the number of accurate digits in the result (up to the
+        limits of floating point precision).
+
+        The algorithm will terminate after completing level `maxlevel` or after
+        another termination condition is satisfied, whichever comes first.
+    minlevel : int, default: 2
+        The level at which to begin iteration (default: 2). This does not
+        change the total number of function evaluations or the abscissae at
+        which the function is evaluated; it changes only the *number of times*
+        `f` is called. If ``minlevel=k``, then the integrand is evaluated at
+        all abscissae from levels ``0`` through ``k`` in a single call.
+        Note that if `minlevel` exceeds `maxlevel`, the provided `minlevel` is
+        ignored, and `minlevel` is set equal to `maxlevel`.
+    atol, rtol : float, optional
+        Absolute termination tolerance (default: 0) and relative termination
+        tolerance (default: ``eps**0.75``, where ``eps`` is the precision of
+        the result dtype), respectively. Must be non-negative and finite if
+        `log` is False, and must be expressed as the log of a non-negative and
+        finite number if `log` is True. Iteration will stop when
+        ``res.error < atol`` or  ``res.error < res.integral * rtol``.
+    preserve_shape : bool, default: False
+        In the following, "arguments of `f`" refers to the array ``xi`` and
+        any arrays within ``argsi``. Let ``shape`` be the broadcasted shape
+        of `a`, `b`, and all elements of `args` (which is conceptually
+        distinct from ``xi` and ``argsi`` passed into `f`).
+
+        - When ``preserve_shape=False`` (default), `f` must accept arguments
+          of *any* broadcastable shapes.
+
+        - When ``preserve_shape=True``, `f` must accept arguments of shape
+          ``shape`` *or* ``shape + (n,)``, where ``(n,)`` is the number of
+          abscissae at which the function is being evaluated.
+
+        In either case, for each scalar element ``xi[j]`` within ``xi``, the array
+        returned by `f` must include the scalar ``f(xi[j])`` at the same index.
+        Consequently, the shape of the output is always the shape of the input
+        ``xi``.
+
+        See Examples.
+
+    callback : callable, optional
+        An optional user-supplied function to be called before the first
+        iteration and after each iteration.
+        Called as ``callback(res)``, where ``res`` is a ``_RichResult``
+        similar to that returned by `tanhsinh` (but containing the
+        current iterate's values of all variables). If `callback` raises a
+        ``StopIteration``, the algorithm will terminate immediately and
+        `tanhsinh` will return a result object. `callback` must not mutate
+        `res` or its attributes.
+
+    Returns
+    -------
+    res : _RichResult
+        An object similar to an instance of `scipy.optimize.OptimizeResult` with the
+        following attributes. (The descriptions are written as though the values will
+        be scalars; however, if `f` returns an array, the outputs will be
+        arrays of the same shape.)
+
+        success : bool array
+            ``True`` when the algorithm terminated successfully (status ``0``).
+            ``False`` otherwise.
+        status : int array
+            An integer representing the exit status of the algorithm.
+
+            ``0`` : The algorithm converged to the specified tolerances.
+            ``-1`` : (unused)
+            ``-2`` : The maximum number of iterations was reached.
+            ``-3`` : A non-finite value was encountered.
+            ``-4`` : Iteration was terminated by `callback`.
+            ``1`` : The algorithm is proceeding normally (in `callback` only).
+
+        integral : float array
+            An estimate of the integral.
+        error : float array
+            An estimate of the error. Only available if level two or higher
+            has been completed; otherwise NaN.
+        maxlevel : int array
+            The maximum refinement level used.
+        nfev : int array
+            The number of points at which `f` was evaluated.
+
+    See Also
+    --------
+    quad
+
+    Notes
+    -----
+    Implements the algorithm as described in [1]_ with minor adaptations for
+    finite-precision arithmetic, including some described by [2]_ and [3]_. The
+    tanh-sinh scheme was originally introduced in [4]_.
+
+    Two error estimation schemes are described in [1]_ Section 5: one attempts to
+    detect and exploit quadratic convergence; the other simply compares the integral
+    estimates at successive levels. While neither is theoretically rigorous or
+    conservative, both work well in practice. Our error estimate uses the minimum of
+    these two schemes with a lower bound of ``eps * res.integral``.
+
+    Due to floating-point error in the abscissae, the function may be evaluated
+    at the endpoints of the interval during iterations, but the values returned by
+    the function at the endpoints will be ignored.
+
+    References
+    ----------
+    .. [1] Bailey, David H., Karthik Jeyabalan, and Xiaoye S. Li. "A comparison of
+           three high-precision quadrature schemes." Experimental Mathematics 14.3
+           (2005): 317-329.
+    .. [2] Vanherck, Joren, Bart Sorée, and Wim Magnus. "Tanh-sinh quadrature for
+           single and multiple integration using floating-point arithmetic."
+           arXiv preprint arXiv:2007.15057 (2020).
+    .. [3] van Engelen, Robert A.  "Improving the Double Exponential Quadrature
+           Tanh-Sinh, Sinh-Sinh and Exp-Sinh Formulas."
+           https://www.genivia.com/files/qthsh.pdf
+    .. [4] Takahasi, Hidetosi, and Masatake Mori. "Double exponential formulas for
+           numerical integration." Publications of the Research Institute for
+           Mathematical Sciences 9.3 (1974): 721-741.
+
+    Examples
+    --------
+    Evaluate the Gaussian integral:
+
+    >>> import numpy as np
+    >>> from scipy.integrate import tanhsinh
+    >>> def f(x):
+    ...     return np.exp(-x**2)
+    >>> res = tanhsinh(f, -np.inf, np.inf)
+    >>> res.integral  # true value is np.sqrt(np.pi), 1.7724538509055159
+    1.7724538509055159
+    >>> res.error  # actual error is 0
+    4.0007963937534104e-16
+
+    The value of the Gaussian function (bell curve) is nearly zero for
+    arguments sufficiently far from zero, so the value of the integral
+    over a finite interval is nearly the same.
+
+    >>> tanhsinh(f, -20, 20).integral
+    1.772453850905518
+
+    However, with unfavorable integration limits, the integration scheme
+    may not be able to find the important region.
+
+    >>> tanhsinh(f, -np.inf, 1000).integral
+    4.500490856616431
+
+    In such cases, or when there are singularities within the interval,
+    break the integral into parts with endpoints at the important points.
+
+    >>> tanhsinh(f, -np.inf, 0).integral + tanhsinh(f, 0, 1000).integral
+    1.772453850905404
+
+    For integration involving very large or very small magnitudes, use
+    log-integration. (For illustrative purposes, the following example shows a
+    case in which both regular and log-integration work, but for more extreme
+    limits of integration, log-integration would avoid the underflow
+    experienced when evaluating the integral normally.)
+
+    >>> res = tanhsinh(f, 20, 30, rtol=1e-10)
+    >>> res.integral, res.error
+    (4.7819613911309014e-176, 4.670364401645202e-187)
+    >>> def log_f(x):
+    ...     return -x**2
+    >>> res = tanhsinh(log_f, 20, 30, log=True, rtol=np.log(1e-10))
+    >>> np.exp(res.integral), np.exp(res.error)
+    (4.7819613911306924e-176, 4.670364401645093e-187)
+
+    The limits of integration and elements of `args` may be broadcastable
+    arrays, and integration is performed elementwise.
+
+    >>> from scipy import stats
+    >>> dist = stats.gausshyper(13.8, 3.12, 2.51, 5.18)
+    >>> a, b = dist.support()
+    >>> x = np.linspace(a, b, 100)
+    >>> res = tanhsinh(dist.pdf, a, x)
+    >>> ref = dist.cdf(x)
+    >>> np.allclose(res.integral, ref)
+    True
+
+    By default, `preserve_shape` is False, and therefore the callable
+    `f` may be called with arrays of any broadcastable shapes.
+    For example:
+
+    >>> shapes = []
+    >>> def f(x, c):
+    ...    shape = np.broadcast_shapes(x.shape, c.shape)
+    ...    shapes.append(shape)
+    ...    return np.sin(c*x)
+    >>>
+    >>> c = [1, 10, 30, 100]
+    >>> res = tanhsinh(f, 0, 1, args=(c,), minlevel=1)
+    >>> shapes
+    [(4,), (4, 34), (4, 32), (3, 64), (2, 128), (1, 256)]
+
+    To understand where these shapes are coming from - and to better
+    understand how `tanhsinh` computes accurate results - note that
+    higher values of ``c`` correspond with higher frequency sinusoids.
+    The higher frequency sinusoids make the integrand more complicated,
+    so more function evaluations are required to achieve the target
+    accuracy:
+
+    >>> res.nfev
+    array([ 67, 131, 259, 515], dtype=int32)
+
+    The initial ``shape``, ``(4,)``, corresponds with evaluating the
+    integrand at a single abscissa and all four frequencies; this is used
+    for input validation and to determine the size and dtype of the arrays
+    that store results. The next shape corresponds with evaluating the
+    integrand at an initial grid of abscissae and all four frequencies.
+    Successive calls to the function double the total number of abscissae at
+    which the function has been evaluated. However, in later function
+    evaluations, the integrand is evaluated at fewer frequencies because
+    the corresponding integral has already converged to the required
+    tolerance. This saves function evaluations to improve performance, but
+    it requires the function to accept arguments of any shape.
+
+    "Vector-valued" integrands, such as those written for use with
+    `scipy.integrate.quad_vec`, are unlikely to satisfy this requirement.
+    For example, consider
+
+    >>> def f(x):
+    ...    return [x, np.sin(10*x), np.cos(30*x), x*np.sin(100*x)**2]
+
+    This integrand is not compatible with `tanhsinh` as written; for instance,
+    the shape of the output will not be the same as the shape of ``x``. Such a
+    function *could* be converted to a compatible form with the introduction of
+    additional parameters, but this would be inconvenient. In such cases,
+    a simpler solution would be to use `preserve_shape`.
+
+    >>> shapes = []
+    >>> def f(x):
+    ...     shapes.append(x.shape)
+    ...     x0, x1, x2, x3 = x
+    ...     return [x0, np.sin(10*x1), np.cos(30*x2), x3*np.sin(100*x3)]
+    >>>
+    >>> a = np.zeros(4)
+    >>> res = tanhsinh(f, a, 1, preserve_shape=True)
+    >>> shapes
+    [(4,), (4, 66), (4, 64), (4, 128), (4, 256)]
+
+    Here, the broadcasted shape of `a` and `b` is ``(4,)``. With
+    ``preserve_shape=True``, the function may be called with argument
+    ``x`` of shape ``(4,)`` or ``(4, n)``, and this is what we observe.
+
+    """
+    maxfun = None  # unused right now
+    (f, a, b, log, maxfun, maxlevel, minlevel,
+     atol, rtol, args, preserve_shape, callback, xp) = _tanhsinh_iv(
+        f, a, b, log, maxfun, maxlevel, minlevel, atol,
+        rtol, args, preserve_shape, callback)
+
+    # Initialization
+    # `eim._initialize` does several important jobs, including
+    # ensuring that limits, each of the `args`, and the output of `f`
+    # broadcast correctly and are of consistent types. To save a function
+    # evaluation, I pass the midpoint of the integration interval. This comes
+    # at a cost of some gymnastics to ensure that the midpoint has the right
+    # shape and dtype. Did you know that 0d and >0d arrays follow different
+    # type promotion rules?
+    with np.errstate(over='ignore', invalid='ignore', divide='ignore'):
+        c = xp.reshape((xp_ravel(a) + xp_ravel(b))/2, a.shape)
+        inf_a, inf_b = xp.isinf(a), xp.isinf(b)
+        c[inf_a] = b[inf_a] - 1.  # takes care of infinite a
+        c[inf_b] = a[inf_b] + 1.  # takes care of infinite b
+        c[inf_a & inf_b] = 0.  # takes care of infinite a and b
+        temp = eim._initialize(f, (c,), args, complex_ok=True,
+                               preserve_shape=preserve_shape, xp=xp)
+    f, xs, fs, args, shape, dtype, xp = temp
+    a = xp_ravel(xp.astype(xp.broadcast_to(a, shape), dtype))
+    b = xp_ravel(xp.astype(xp.broadcast_to(b, shape), dtype))
+
+    # Transform improper integrals
+    a, b, a0, negative, abinf, ainf, binf = _transform_integrals(a, b, xp)
+
+    # Define variables we'll need
+    nit, nfev = 0, 1  # one function evaluation performed above
+    zero = -xp.inf if log else 0
+    pi = xp.asarray(xp.pi, dtype=dtype)[()]
+    maxiter = maxlevel - minlevel + 1
+    eps = xp.finfo(dtype).eps
+    if rtol is None:
+        rtol = 0.75*math.log(eps) if log else eps**0.75
+
+    Sn = xp_ravel(xp.full(shape, zero, dtype=dtype))  # latest integral estimate
+    Sn[xp.isnan(a) | xp.isnan(b) | xp.isnan(fs[0])] = xp.nan
+    Sk = xp.reshape(xp.empty_like(Sn), (-1, 1))[:, 0:0]  # all integral estimates
+    aerr = xp_ravel(xp.full(shape, xp.nan, dtype=dtype))  # absolute error
+    status = xp_ravel(xp.full(shape, eim._EINPROGRESS, dtype=xp.int32))
+    h0 = _get_base_step(dtype, xp)
+    h0 = xp.real(h0) # base step
+
+    # For term `d4` of error estimate ([1] Section 5), we need to keep the
+    # most extreme abscissae and corresponding `fj`s, `wj`s in Euler-Maclaurin
+    # sum. Here, we initialize these variables.
+    xr0 = xp_ravel(xp.full(shape, -xp.inf, dtype=dtype))
+    fr0 = xp_ravel(xp.full(shape, xp.nan, dtype=dtype))
+    wr0 = xp_ravel(xp.zeros(shape, dtype=dtype))
+    xl0 = xp_ravel(xp.full(shape, xp.inf, dtype=dtype))
+    fl0 = xp_ravel(xp.full(shape, xp.nan, dtype=dtype))
+    wl0 = xp_ravel(xp.zeros(shape, dtype=dtype))
+    d4 = xp_ravel(xp.zeros(shape, dtype=dtype))
+
+    work = _RichResult(
+        Sn=Sn, Sk=Sk, aerr=aerr, h=h0, log=log, dtype=dtype, pi=pi, eps=eps,
+        a=xp.reshape(a, (-1, 1)), b=xp.reshape(b, (-1, 1)),  # integration limits
+        n=minlevel, nit=nit, nfev=nfev, status=status,  # iter/eval counts
+        xr0=xr0, fr0=fr0, wr0=wr0, xl0=xl0, fl0=fl0, wl0=wl0, d4=d4,  # err est
+        ainf=ainf, binf=binf, abinf=abinf, a0=xp.reshape(a0, (-1, 1)),  # transforms
+        # Store the xjc/wj pair cache in an object so they can't get compressed
+        # Using RichResult to allow dot notation, but a dictionary would suffice
+        pair_cache=_RichResult(xjc=None, wj=None, indices=[0], h0=None))  # pair cache
+
+    # Constant scalars don't need to be put in `work` unless they need to be
+    # passed outside `tanhsinh`. Examples: atol, rtol, h0, minlevel.
+
+    # Correspondence between terms in the `work` object and the result
+    res_work_pairs = [('status', 'status'), ('integral', 'Sn'),
+                      ('error', 'aerr'), ('nit', 'nit'), ('nfev', 'nfev')]
+
+    def pre_func_eval(work):
+        # Determine abscissae at which to evaluate `f`
+        work.h = h0 / 2**work.n
+        xjc, wj = _get_pairs(work.n, h0, dtype=work.dtype,
+                             inclusive=(work.n == minlevel), xp=xp, work=work)
+        work.xj, work.wj = _transform_to_limits(xjc, wj, work.a, work.b, xp)
+
+        # Perform abscissae substitutions for infinite limits of integration
+        xj = xp_copy(work.xj)
+        xj[work.abinf] = xj[work.abinf] / (1 - xp.real(xj[work.abinf])**2)
+        xj[work.binf] = 1/xj[work.binf] - 1 + work.a0[work.binf]
+        xj[work.ainf] *= -1
+        return xj
+
+    def post_func_eval(x, fj, work):
+        # Weight integrand as required by substitutions for infinite limits
+        if work.log:
+            fj[work.abinf] += (xp.log(1 + work.xj[work.abinf]**2)
+                               - 2*xp.log(1 - work.xj[work.abinf]**2))
+            fj[work.binf] -= 2 * xp.log(work.xj[work.binf])
+        else:
+            fj[work.abinf] *= ((1 + work.xj[work.abinf]**2) /
+                               (1 - work.xj[work.abinf]**2)**2)
+            fj[work.binf] *= work.xj[work.binf]**-2.
+
+        # Estimate integral with Euler-Maclaurin Sum
+        fjwj, Sn = _euler_maclaurin_sum(fj, work, xp)
+        if work.Sk.shape[-1]:
+            Snm1 = work.Sk[:, -1]
+            Sn = (special.logsumexp(xp.stack([Snm1 - math.log(2), Sn]), axis=0) if log
+                  else Snm1 / 2 + Sn)
+
+        work.fjwj = fjwj
+        work.Sn = Sn
+
+    def check_termination(work):
+        """Terminate due to convergence or encountering non-finite values"""
+        stop = xp.zeros(work.Sn.shape, dtype=bool)
+
+        # Terminate before first iteration if integration limits are equal
+        if work.nit == 0:
+            i = xp_ravel(work.a == work.b)  # ravel singleton dimension
+            zero = xp.asarray(-xp.inf if log else 0.)
+            zero = xp.full(work.Sn.shape, zero, dtype=Sn.dtype)
+            zero[xp.isnan(Sn)] = xp.nan
+            work.Sn[i] = zero[i]
+            work.aerr[i] = zero[i]
+            work.status[i] = eim._ECONVERGED
+            stop[i] = True
+        else:
+            # Terminate if convergence criterion is met
+            rerr, aerr = _estimate_error(work, xp)
+            i = (rerr < rtol) | (aerr < atol)
+            work.aerr =  xp.reshape(xp.astype(aerr, work.dtype), work.Sn.shape)
+            work.status[i] = eim._ECONVERGED
+            stop[i] = True
+
+        # Terminate if integral estimate becomes invalid
+        if log:
+            Sn_real = xp.real(work.Sn)
+            Sn_pos_inf = xp.isinf(Sn_real) & (Sn_real > 0)
+            i = (Sn_pos_inf | xp.isnan(work.Sn)) & ~stop
+        else:
+            i = ~xp.isfinite(work.Sn) & ~stop
+        work.status[i] = eim._EVALUEERR
+        stop[i] = True
+
+        return stop
+
+    def post_termination_check(work):
+        work.n += 1
+        work.Sk = xp.concat((work.Sk, work.Sn[:, xp.newaxis]), axis=-1)
+        return
+
+    def customize_result(res, shape):
+        # If the integration limits were such that b < a, we reversed them
+        # to perform the calculation, and the final result needs to be negated.
+        if log and xp.any(negative):
+            res['integral'] = res['integral'] + negative * xp.pi * 1.0j
+        else:
+            res['integral'][negative] *= -1
+
+        # For this algorithm, it seems more appropriate to report the maximum
+        # level rather than the number of iterations in which it was performed.
+        res['maxlevel'] = minlevel + res['nit'] - 1
+        res['maxlevel'][res['nit'] == 0] = -1
+        del res['nit']
+        return shape
+
+    # Suppress all warnings initially, since there are many places in the code
+    # for which this is expected behavior.
+    with np.errstate(over='ignore', invalid='ignore', divide='ignore'):
+        res = eim._loop(work, callback, shape, maxiter, f, args, dtype, pre_func_eval,
+                        post_func_eval, check_termination, post_termination_check,
+                        customize_result, res_work_pairs, xp, preserve_shape)
+    return res
+
+
+def _get_base_step(dtype, xp):
+    # Compute the base step length for the provided dtype. Theoretically, the
+    # Euler-Maclaurin sum is infinite, but it gets cut off when either the
+    # weights underflow or the abscissae cannot be distinguished from the
+    # limits of integration. The latter happens to occur first for float32 and
+    # float64, and it occurs when `xjc` (the abscissa complement)
+    # in `_compute_pair` underflows. We can solve for the argument `tmax` at
+    # which it will underflow using [2] Eq. 13.
+    fmin = 4*xp.finfo(dtype).smallest_normal  # stay a little away from the limit
+    tmax = math.asinh(math.log(2/fmin - 1) / xp.pi)
+
+    # Based on this, we can choose a base step size `h` for level 0.
+    # The number of function evaluations will be `2 + m*2^(k+1)`, where `k` is
+    # the level and `m` is an integer we get to choose. I choose
+    # m = _N_BASE_STEPS = `8` somewhat arbitrarily, but a rationale is that a
+    # power of 2 makes floating point arithmetic more predictable. It also
+    # results in a base step size close to `1`, which is what [1] uses (and I
+    # used here until I found [2] and these ideas settled).
+    h0 = tmax / _N_BASE_STEPS
+    return xp.asarray(h0, dtype=dtype)[()]
+
+
+_N_BASE_STEPS = 8
+
+
+def _compute_pair(k, h0, xp):
+    # Compute the abscissa-weight pairs for each level k. See [1] page 9.
+
+    # For now, we compute and store in 64-bit precision. If higher-precision
+    # data types become better supported, it would be good to compute these
+    # using the highest precision available. Or, once there is an Array API-
+    # compatible arbitrary precision array, we can compute at the required
+    # precision.
+
+    # "....each level k of abscissa-weight pairs uses h = 2 **-k"
+    # We adapt to floating point arithmetic using ideas of [2].
+    h = h0 / 2**k
+    max = _N_BASE_STEPS * 2**k
+
+    # For iterations after the first, "....the integrand function needs to be
+    # evaluated only at the odd-indexed abscissas at each level."
+    j = xp.arange(max+1) if k == 0 else xp.arange(1, max+1, 2)
+    jh = j * h
+
+    # "In this case... the weights wj = u1/cosh(u2)^2, where..."
+    pi_2 = xp.pi / 2
+    u1 = pi_2*xp.cosh(jh)
+    u2 = pi_2*xp.sinh(jh)
+    # Denominators get big here. Overflow then underflow doesn't need warning.
+    # with np.errstate(under='ignore', over='ignore'):
+    wj = u1 / xp.cosh(u2)**2
+    # "We actually store 1-xj = 1/(...)."
+    xjc = 1 / (xp.exp(u2) * xp.cosh(u2))  # complement of xj = xp.tanh(u2)
+
+    # When level k == 0, the zeroth xj corresponds with xj = 0. To simplify
+    # code, the function will be evaluated there twice; each gets half weight.
+    wj[0] = wj[0] / 2 if k == 0 else wj[0]
+
+    return xjc, wj  # store at full precision
+
+
+def _pair_cache(k, h0, xp, work):
+    # Cache the abscissa-weight pairs up to a specified level.
+    # Abscissae and weights of consecutive levels are concatenated.
+    # `index` records the indices that correspond with each level:
+    # `xjc[index[k]:index[k+1]` extracts the level `k` abscissae.
+    if not isinstance(h0, type(work.pair_cache.h0)) or h0 != work.pair_cache.h0:
+        work.pair_cache.xjc = xp.empty(0)
+        work.pair_cache.wj = xp.empty(0)
+        work.pair_cache.indices = [0]
+
+    xjcs = [work.pair_cache.xjc]
+    wjs = [work.pair_cache.wj]
+
+    for i in range(len(work.pair_cache.indices)-1, k + 1):
+        xjc, wj = _compute_pair(i, h0, xp)
+        xjcs.append(xjc)
+        wjs.append(wj)
+        work.pair_cache.indices.append(work.pair_cache.indices[-1] + xjc.shape[0])
+
+    work.pair_cache.xjc = xp.concat(xjcs)
+    work.pair_cache.wj = xp.concat(wjs)
+    work.pair_cache.h0 = h0
+
+
+def _get_pairs(k, h0, inclusive, dtype, xp, work):
+    # Retrieve the specified abscissa-weight pairs from the cache
+    # If `inclusive`, return all up to and including the specified level
+    if (len(work.pair_cache.indices) <= k+2
+        or not isinstance (h0, type(work.pair_cache.h0))
+        or h0 != work.pair_cache.h0):
+            _pair_cache(k, h0, xp, work)
+
+    xjc = work.pair_cache.xjc
+    wj = work.pair_cache.wj
+    indices = work.pair_cache.indices
+
+    start = 0 if inclusive else indices[k]
+    end = indices[k+1]
+
+    return xp.astype(xjc[start:end], dtype), xp.astype(wj[start:end], dtype)
+
+
+def _transform_to_limits(xjc, wj, a, b, xp):
+    # Transform integral according to user-specified limits. This is just
+    # math that follows from the fact that the standard limits are (-1, 1).
+    # Note: If we had stored xj instead of xjc, we would have
+    # xj = alpha * xj + beta, where beta = (a + b)/2
+    alpha = (b - a) / 2
+    xj = xp.concat((-alpha * xjc + b, alpha * xjc + a), axis=-1)
+    wj = wj*alpha  # arguments get broadcasted, so we can't use *=
+    wj = xp.concat((wj, wj), axis=-1)
+
+    # Points at the boundaries can be generated due to finite precision
+    # arithmetic, but these function values aren't supposed to be included in
+    # the Euler-Maclaurin sum. Ideally we wouldn't evaluate the function at
+    # these points; however, we can't easily filter out points since this
+    # function is vectorized. Instead, zero the weights.
+    # Note: values may have complex dtype, but have zero imaginary part
+    xj_real, a_real, b_real = xp.real(xj), xp.real(a), xp.real(b)
+    invalid = (xj_real <= a_real) | (xj_real >= b_real)
+    wj[invalid] = 0
+    return xj, wj
+
+
+def _euler_maclaurin_sum(fj, work, xp):
+    # Perform the Euler-Maclaurin Sum, [1] Section 4
+
+    # The error estimate needs to know the magnitude of the last term
+    # omitted from the Euler-Maclaurin sum. This is a bit involved because
+    # it may have been computed at a previous level. I sure hope it's worth
+    # all the trouble.
+    xr0, fr0, wr0 = work.xr0, work.fr0, work.wr0
+    xl0, fl0, wl0 = work.xl0, work.fl0, work.wl0
+
+    # It is much more convenient to work with the transposes of our work
+    # variables here.
+    xj, fj, wj = work.xj.T, fj.T, work.wj.T
+    n_x, n_active = xj.shape  # number of abscissae, number of active elements
+
+    # We'll work with the left and right sides separately
+    xr, xl = xp_copy(xp.reshape(xj, (2, n_x // 2, n_active)))  # this gets modified
+    fr, fl = xp.reshape(fj, (2, n_x // 2, n_active))
+    wr, wl = xp.reshape(wj, (2, n_x // 2, n_active))
+
+    invalid_r = ~xp.isfinite(fr) | (wr == 0)
+    invalid_l = ~xp.isfinite(fl) | (wl == 0)
+
+    # integer index of the maximum abscissa at this level
+    xr[invalid_r] = -xp.inf
+    ir = xp.argmax(xp.real(xr), axis=0, keepdims=True)
+    # abscissa, function value, and weight at this index
+    ### Not Array API Compatible... yet ###
+    xr_max = xp.take_along_axis(xr, ir, axis=0)[0]
+    fr_max = xp.take_along_axis(fr, ir, axis=0)[0]
+    wr_max = xp.take_along_axis(wr, ir, axis=0)[0]
+    # boolean indices at which maximum abscissa at this level exceeds
+    # the incumbent maximum abscissa (from all previous levels)
+    # note: abscissa may have complex dtype, but will have zero imaginary part
+    j = xp.real(xr_max) > xp.real(xr0)
+    # Update record of the incumbent abscissa, function value, and weight
+    xr0[j] = xr_max[j]
+    fr0[j] = fr_max[j]
+    wr0[j] = wr_max[j]
+
+    # integer index of the minimum abscissa at this level
+    xl[invalid_l] = xp.inf
+    il = xp.argmin(xp.real(xl), axis=0, keepdims=True)
+    # abscissa, function value, and weight at this index
+    xl_min = xp.take_along_axis(xl, il, axis=0)[0]
+    fl_min = xp.take_along_axis(fl, il, axis=0)[0]
+    wl_min = xp.take_along_axis(wl, il, axis=0)[0]
+    # boolean indices at which minimum abscissa at this level is less than
+    # the incumbent minimum abscissa (from all previous levels)
+    # note: abscissa may have complex dtype, but will have zero imaginary part
+    j = xp.real(xl_min) < xp.real(xl0)
+    # Update record of the incumbent abscissa, function value, and weight
+    xl0[j] = xl_min[j]
+    fl0[j] = fl_min[j]
+    wl0[j] = wl_min[j]
+    fj = fj.T
+
+    # Compute the error estimate `d4` - the magnitude of the leftmost or
+    # rightmost term, whichever is greater.
+    flwl0 = fl0 + xp.log(wl0) if work.log else fl0 * wl0  # leftmost term
+    frwr0 = fr0 + xp.log(wr0) if work.log else fr0 * wr0  # rightmost term
+    magnitude = xp.real if work.log else xp.abs
+    work.d4 = xp.maximum(magnitude(flwl0), magnitude(frwr0))
+
+    # There are two approaches to dealing with function values that are
+    # numerically infinite due to approaching a singularity - zero them, or
+    # replace them with the function value at the nearest non-infinite point.
+    # [3] pg. 22 suggests the latter, so let's do that given that we have the
+    # information.
+    fr0b = xp.broadcast_to(fr0[xp.newaxis, :], fr.shape)
+    fl0b = xp.broadcast_to(fl0[xp.newaxis, :], fl.shape)
+    fr[invalid_r] = fr0b[invalid_r]
+    fl[invalid_l] = fl0b[invalid_l]
+
+    # When wj is zero, log emits a warning
+    # with np.errstate(divide='ignore'):
+    fjwj = fj + xp.log(work.wj) if work.log else fj * work.wj
+
+    # update integral estimate
+    Sn = (special.logsumexp(fjwj + xp.log(work.h), axis=-1) if work.log
+          else xp.sum(fjwj, axis=-1) * work.h)
+
+    work.xr0, work.fr0, work.wr0 = xr0, fr0, wr0
+    work.xl0, work.fl0, work.wl0 = xl0, fl0, wl0
+
+    return fjwj, Sn
+
+
+def _estimate_error(work, xp):
+    # Estimate the error according to [1] Section 5
+
+    if work.n == 0 or work.nit == 0:
+        # The paper says to use "one" as the error before it can be calculated.
+        # NaN seems to be more appropriate.
+        nan = xp.full_like(work.Sn, xp.nan)
+        return nan, nan
+
+    indices = work.pair_cache.indices
+
+    n_active = work.Sn.shape[0]  # number of active elements
+    axis_kwargs = dict(axis=-1, keepdims=True)
+
+    # With a jump start (starting at level higher than 0), we haven't
+    # explicitly calculated the integral estimate at lower levels. But we have
+    # all the function value-weight products, so we can compute the
+    # lower-level estimates.
+    if work.Sk.shape[-1] == 0:
+        h = 2 * work.h  # step size at this level
+        n_x = indices[work.n]  # number of abscissa up to this level
+        # The right and left fjwj terms from all levels are concatenated along
+        # the last axis. Get out only the terms up to this level.
+        fjwj_rl = xp.reshape(work.fjwj, (n_active, 2, -1))
+        fjwj = xp.reshape(fjwj_rl[:, :, :n_x], (n_active, 2*n_x))
+        # Compute the Euler-Maclaurin sum at this level
+        Snm1 = (special.logsumexp(fjwj, **axis_kwargs) + xp.log(h) if work.log
+                else xp.sum(fjwj, **axis_kwargs) * h)
+        work.Sk = xp.concat((Snm1, work.Sk), axis=-1)
+
+    if work.n == 1:
+        nan = xp.full_like(work.Sn, xp.nan)
+        return nan, nan
+
+    # The paper says not to calculate the error for n<=2, but it's not clear
+    # about whether it starts at level 0 or level 1. We start at level 0, so
+    # why not compute the error beginning in level 2?
+    if work.Sk.shape[-1] < 2:
+        h = 4 * work.h  # step size at this level
+        n_x = indices[work.n-1]  # number of abscissa up to this level
+        # The right and left fjwj terms from all levels are concatenated along
+        # the last axis. Get out only the terms up to this level.
+        fjwj_rl = xp.reshape(work.fjwj, (work.Sn.shape[0], 2, -1))
+        fjwj = xp.reshape(fjwj_rl[..., :n_x], (n_active, 2*n_x))
+        # Compute the Euler-Maclaurin sum at this level
+        Snm2 = (special.logsumexp(fjwj, **axis_kwargs) + xp.log(h) if work.log
+                else xp.sum(fjwj, **axis_kwargs) * h)
+        work.Sk = xp.concat((Snm2, work.Sk), axis=-1)
+
+    Snm2 = work.Sk[..., -2]
+    Snm1 = work.Sk[..., -1]
+
+    e1 = xp.asarray(work.eps)[()]
+
+    if work.log:
+        log_e1 = xp.log(e1)
+        # Currently, only real integrals are supported in log-scale. All
+        # complex values have imaginary part in increments of pi*j, which just
+        # carries sign information of the original integral, so use of
+        # `xp.real` here is equivalent to absolute value in real scale.
+        d1 = xp.real(special.logsumexp(xp.stack([work.Sn, Snm1 + work.pi*1j]), axis=0))
+        d2 = xp.real(special.logsumexp(xp.stack([work.Sn, Snm2 + work.pi*1j]), axis=0))
+        d3 = log_e1 + xp.max(xp.real(work.fjwj), axis=-1)
+        d4 = work.d4
+        d5 = log_e1 + xp.real(work.Sn)
+        temp = xp.where(d1 > -xp.inf, d1 ** 2 / d2, -xp.inf)
+        ds = xp.stack([temp, 2 * d1, d3, d4])
+        aerr = xp.clip(xp.max(ds, axis=0), d5, d1)
+        rerr = aerr - xp.real(work.Sn)
+    else:
+        # Note: explicit computation of log10 of each of these is unnecessary.
+        d1 = xp.abs(work.Sn - Snm1)
+        d2 = xp.abs(work.Sn - Snm2)
+        d3 = e1 * xp.max(xp.abs(work.fjwj), axis=-1)
+        d4 = work.d4
+        d5 = e1 * xp.abs(work.Sn)
+        temp = xp.where(d1 > 0, d1**(xp.log(d1)/xp.log(d2)), 0)
+        ds = xp.stack([temp, d1**2, d3, d4])
+        aerr = xp.clip(xp.max(ds, axis=0), d5, d1)
+        rerr = aerr/xp.abs(work.Sn)
+
+    return rerr, aerr
+
+
+def _transform_integrals(a, b, xp):
+    # Transform integrals to a form with finite a <= b
+    # For b == a (even infinite), we ensure that the limits remain equal
+    # For b < a, we reverse the limits and will multiply the final result by -1
+    # For infinite limit on the right, we use the substitution x = 1/t - 1 + a
+    # For infinite limit on the left, we substitute x = -x and treat as above
+    # For infinite limits, we substitute x = t / (1-t**2)
+    ab_same = (a == b)
+    a[ab_same], b[ab_same] = 1, 1
+
+    # `a, b` may have complex dtype but have zero imaginary part
+    negative = xp.real(b) < xp.real(a)
+    a[negative], b[negative] = b[negative], a[negative]
+
+    abinf = xp.isinf(a) & xp.isinf(b)
+    a[abinf], b[abinf] = -1, 1
+
+    ainf = xp.isinf(a)
+    a[ainf], b[ainf] = -b[ainf], -a[ainf]
+
+    binf = xp.isinf(b)
+    a0 = xp_copy(a)
+    a[binf], b[binf] = 0, 1
+
+    return a, b, a0, negative, abinf, ainf, binf
+
+
+def _tanhsinh_iv(f, a, b, log, maxfun, maxlevel, minlevel,
+                 atol, rtol, args, preserve_shape, callback):
+    # Input validation and standardization
+
+    xp = array_namespace(a, b)
+    a, b = xp_promote(a, b, broadcast=True, force_floating=True, xp=xp)
+
+    message = '`f` must be callable.'
+    if not callable(f):
+        raise ValueError(message)
+
+    message = 'All elements of `a` and `b` must be real numbers.'
+    if (xp.isdtype(a.dtype, 'complex floating')
+            or xp.isdtype(b.dtype, 'complex floating')):
+        raise ValueError(message)
+
+    message = '`log` must be True or False.'
+    if log not in {True, False}:
+        raise ValueError(message)
+    log = bool(log)
+
+    if atol is None:
+        atol = -xp.inf if log else 0
+
+    rtol_temp = rtol if rtol is not None else 0.
+
+    # using NumPy for convenience here; these are just floats, not arrays
+    params = np.asarray([atol, rtol_temp, 0.])
+    message = "`atol` and `rtol` must be real numbers."
+    if not np.issubdtype(params.dtype, np.floating):
+        raise ValueError(message)
+
+    if log:
+        message = '`atol` and `rtol` may not be positive infinity.'
+        if np.any(np.isposinf(params)):
+            raise ValueError(message)
+    else:
+        message = '`atol` and `rtol` must be non-negative and finite.'
+        if np.any(params < 0) or np.any(np.isinf(params)):
+            raise ValueError(message)
+    atol = params[0]
+    rtol = rtol if rtol is None else params[1]
+
+    BIGINT = float(2**62)
+    if maxfun is None and maxlevel is None:
+        maxlevel = 10
+
+    maxfun = BIGINT if maxfun is None else maxfun
+    maxlevel = BIGINT if maxlevel is None else maxlevel
+
+    message = '`maxfun`, `maxlevel`, and `minlevel` must be integers.'
+    params = np.asarray([maxfun, maxlevel, minlevel])
+    if not (np.issubdtype(params.dtype, np.number)
+            and np.all(np.isreal(params))
+            and np.all(params.astype(np.int64) == params)):
+        raise ValueError(message)
+    message = '`maxfun`, `maxlevel`, and `minlevel` must be non-negative.'
+    if np.any(params < 0):
+        raise ValueError(message)
+    maxfun, maxlevel, minlevel = params.astype(np.int64)
+    minlevel = min(minlevel, maxlevel)
+
+    if not np.iterable(args):
+        args = (args,)
+    args = (xp.asarray(arg) for arg in args)
+
+    message = '`preserve_shape` must be True or False.'
+    if preserve_shape not in {True, False}:
+        raise ValueError(message)
+
+    if callback is not None and not callable(callback):
+        raise ValueError('`callback` must be callable.')
+
+    return (f, a, b, log, maxfun, maxlevel, minlevel,
+            atol, rtol, args, preserve_shape, callback, xp)
+
+
+def _nsum_iv(f, a, b, step, args, log, maxterms, tolerances):
+    # Input validation and standardization
+
+    xp = array_namespace(a, b, step)
+    a, b, step = xp_promote(a, b, step, broadcast=True, force_floating=True, xp=xp)
+
+    message = '`f` must be callable.'
+    if not callable(f):
+        raise ValueError(message)
+
+    message = 'All elements of `a`, `b`, and `step` must be real numbers.'
+    if not xp.isdtype(a.dtype, ('integral', 'real floating')):
+        raise ValueError(message)
+
+    valid_b = b >= a  # NaNs will be False
+    valid_step = xp.isfinite(step) & (step > 0)
+    valid_abstep = valid_b & valid_step
+
+    message = '`log` must be True or False.'
+    if log not in {True, False}:
+        raise ValueError(message)
+
+    tolerances = {} if tolerances is None else tolerances
+
+    atol = tolerances.get('atol', None)
+    if atol is None:
+        atol = -xp.inf if log else 0
+
+    rtol = tolerances.get('rtol', None)
+    rtol_temp = rtol if rtol is not None else 0.
+
+    # using NumPy for convenience here; these are just floats, not arrays
+    params = np.asarray([atol, rtol_temp, 0.])
+    message = "`atol` and `rtol` must be real numbers."
+    if not np.issubdtype(params.dtype, np.floating):
+        raise ValueError(message)
+
+    if log:
+        message = '`atol`, `rtol` may not be positive infinity or NaN.'
+        if np.any(np.isposinf(params) | np.isnan(params)):
+            raise ValueError(message)
+    else:
+        message = '`atol`, and `rtol` must be non-negative and finite.'
+        if np.any((params < 0) | (~np.isfinite(params))):
+            raise ValueError(message)
+    atol = params[0]
+    rtol = rtol if rtol is None else params[1]
+
+    maxterms_int = int(maxterms)
+    if maxterms_int != maxterms or maxterms < 0:
+        message = "`maxterms` must be a non-negative integer."
+        raise ValueError(message)
+
+    if not np.iterable(args):
+        args = (args,)
+
+    return f, a, b, step, valid_abstep, args, log, maxterms_int, atol, rtol, xp
+
+
+def nsum(f, a, b, *, step=1, args=(), log=False, maxterms=int(2**20), tolerances=None):
+    r"""Evaluate a convergent finite or infinite series.
+
+    For finite `a` and `b`, this evaluates::
+
+        f(a + np.arange(n)*step).sum()
+
+    where ``n = int((b - a) / step) + 1``, where `f` is smooth, positive, and
+    unimodal. The number of terms in the sum may be very large or infinite,
+    in which case a partial sum is evaluated directly and the remainder is
+    approximated using integration.
+
+    Parameters
+    ----------
+    f : callable
+        The function that evaluates terms to be summed. The signature must be::
+
+            f(x: ndarray, *args) -> ndarray
+
+        where each element of ``x`` is a finite real and ``args`` is a tuple,
+        which may contain an arbitrary number of arrays that are broadcastable
+        with ``x``.
+
+        `f` must be an elementwise function: each element ``f(x)[i]``
+        must equal ``f(x[i])`` for all indices ``i``. It must not mutate the
+        array ``x`` or the arrays in ``args``, and it must return NaN where
+        the argument is NaN.
+
+        `f` must represent a smooth, positive, unimodal function of `x` defined at
+        *all reals* between `a` and `b`.
+    a, b : float array_like
+        Real lower and upper limits of summed terms. Must be broadcastable.
+        Each element of `a` must be less than the corresponding element in `b`.
+    step : float array_like
+        Finite, positive, real step between summed terms. Must be broadcastable
+        with `a` and `b`. Note that the number of terms included in the sum will
+        be ``floor((b - a) / step)`` + 1; adjust `b` accordingly to ensure
+        that ``f(b)`` is included if intended.
+    args : tuple of array_like, optional
+        Additional positional arguments to be passed to `f`. Must be arrays
+        broadcastable with `a`, `b`, and `step`. If the callable to be summed
+        requires arguments that are not broadcastable with `a`, `b`, and `step`,
+        wrap that callable with `f` such that `f` accepts only `x` and
+        broadcastable ``*args``. See Examples.
+    log : bool, default: False
+        Setting to True indicates that `f` returns the log of the terms
+        and that `atol` and `rtol` are expressed as the logs of the absolute
+        and relative errors. In this case, the result object will contain the
+        log of the sum and error. This is useful for summands for which
+        numerical underflow or overflow would lead to inaccuracies.
+    maxterms : int, default: 2**20
+        The maximum number of terms to evaluate for direct summation.
+        Additional function evaluations may be performed for input
+        validation and integral evaluation.
+    atol, rtol : float, optional
+        Absolute termination tolerance (default: 0) and relative termination
+        tolerance (default: ``eps**0.5``, where ``eps`` is the precision of
+        the result dtype), respectively. Must be non-negative
+        and finite if `log` is False, and must be expressed as the log of a
+        non-negative and finite number if `log` is True.
+
+    Returns
+    -------
+    res : _RichResult
+        An object similar to an instance of `scipy.optimize.OptimizeResult` with the
+        following attributes. (The descriptions are written as though the values will
+        be scalars; however, if `f` returns an array, the outputs will be
+        arrays of the same shape.)
+
+        success : bool
+            ``True`` when the algorithm terminated successfully (status ``0``);
+            ``False`` otherwise.
+        status : int array
+            An integer representing the exit status of the algorithm.
+
+            - ``0`` : The algorithm converged to the specified tolerances.
+            - ``-1`` : Element(s) of `a`, `b`, or `step` are invalid
+            - ``-2`` : Numerical integration reached its iteration limit;
+              the sum may be divergent.
+            - ``-3`` : A non-finite value was encountered.
+            - ``-4`` : The magnitude of the last term of the partial sum exceeds
+              the tolerances, so the error estimate exceeds the tolerances.
+              Consider increasing `maxterms` or loosening `tolerances`.
+              Alternatively, the callable may not be unimodal, or the limits of
+              summation may be too far from the function maximum. Consider
+              increasing `maxterms` or breaking the sum into pieces.
+
+        sum : float array
+            An estimate of the sum.
+        error : float array
+            An estimate of the absolute error, assuming all terms are non-negative,
+            the function is computed exactly, and direct summation is accurate to
+            the precision of the result dtype.
+        nfev : int array
+            The number of points at which `f` was evaluated.
+
+    See Also
+    --------
+    mpmath.nsum
+
+    Notes
+    -----
+    The method implemented for infinite summation is related to the integral
+    test for convergence of an infinite series: assuming `step` size 1 for
+    simplicity of exposition, the sum of a monotone decreasing function is bounded by
+
+    .. math::
+
+        \int_u^\infty f(x) dx \leq \sum_{k=u}^\infty f(k) \leq \int_u^\infty f(x) dx + f(u)
+
+    Let :math:`a` represent  `a`, :math:`n` represent `maxterms`, :math:`\epsilon_a`
+    represent `atol`, and :math:`\epsilon_r` represent `rtol`.
+    The implementation first evaluates the integral :math:`S_l=\int_a^\infty f(x) dx`
+    as a lower bound of the infinite sum. Then, it seeks a value :math:`c > a` such
+    that :math:`f(c) < \epsilon_a + S_l \epsilon_r`, if it exists; otherwise,
+    let :math:`c = a + n`. Then the infinite sum is approximated as
+
+    .. math::
+
+        \sum_{k=a}^{c-1} f(k) + \int_c^\infty f(x) dx + f(c)/2
+
+    and the reported error is :math:`f(c)/2` plus the error estimate of
+    numerical integration. Note that the integral approximations may require
+    evaluation of the function at points besides those that appear in the sum,
+    so `f` must be a continuous and monotonically decreasing function defined
+    for all reals within the integration interval. However, due to the nature
+    of the integral approximation, the shape of the function between points
+    that appear in the sum has little effect. If there is not a natural
+    extension of the function to all reals, consider using linear interpolation,
+    which is easy to evaluate and preserves monotonicity.
+
+    The approach described above is generalized for non-unit
+    `step` and finite `b` that is too large for direct evaluation of the sum,
+    i.e. ``b - a + 1 > maxterms``. It is further generalized to unimodal
+    functions by directly summing terms surrounding the maximum.
+    This strategy may fail:
+
+    - If the left limit is finite and the maximum is far from it.
+    - If the right limit is finite and the maximum is far from it.
+    - If both limits are finite and the maximum is far from the origin.
+
+    In these cases, accuracy may be poor, and `nsum` may return status code ``4``.
+
+    Although the callable `f` must be non-negative and unimodal,
+    `nsum` can be used to evaluate more general forms of series. For instance, to
+    evaluate an alternating series, pass a callable that returns the difference
+    between pairs of adjacent terms, and adjust `step` accordingly. See Examples.
+
+    References
+    ----------
+    .. [1] Wikipedia. "Integral test for convergence."
+           https://en.wikipedia.org/wiki/Integral_test_for_convergence
+
+    Examples
+    --------
+    Compute the infinite sum of the reciprocals of squared integers.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import nsum
+    >>> res = nsum(lambda k: 1/k**2, 1, np.inf)
+    >>> ref = np.pi**2/6  # true value
+    >>> res.error  # estimated error
+    np.float64(7.448762306416137e-09)
+    >>> (res.sum - ref)/ref  # true error
+    np.float64(-1.839871898894426e-13)
+    >>> res.nfev  # number of points at which callable was evaluated
+    np.int32(8561)
+
+    Compute the infinite sums of the reciprocals of integers raised to powers ``p``,
+    where ``p`` is an array.
+
+    >>> from scipy import special
+    >>> p = np.arange(3, 10)
+    >>> res = nsum(lambda k, p: 1/k**p, 1, np.inf, maxterms=1e3, args=(p,))
+    >>> ref = special.zeta(p, 1)
+    >>> np.allclose(res.sum, ref)
+    True
+
+    Evaluate the alternating harmonic series.
+
+    >>> res = nsum(lambda x: 1/x - 1/(x+1), 1, np.inf, step=2)
+    >>> res.sum, res.sum - np.log(2)  # result, difference vs analytical sum
+    (np.float64(0.6931471805598691), np.float64(-7.616129948928574e-14))
+
+    """ # noqa: E501
+    # Potential future work:
+    # - improve error estimate of `_direct` sum
+    # - add other methods for convergence acceleration (Richardson, epsilon)
+    # - support negative monotone increasing functions?
+    # - b < a / negative step?
+    # - complex-valued function?
+    # - check for violations of monotonicity?
+
+    # Function-specific input validation / standardization
+    tmp = _nsum_iv(f, a, b, step, args, log, maxterms, tolerances)
+    f, a, b, step, valid_abstep, args, log, maxterms, atol, rtol, xp = tmp
+
+    # Additional elementwise algorithm input validation / standardization
+    tmp = eim._initialize(f, (a,), args, complex_ok=False, xp=xp)
+    f, xs, fs, args, shape, dtype, xp = tmp
+
+    # Finish preparing `a`, `b`, and `step` arrays
+    a = xs[0]
+    b = xp.astype(xp_ravel(xp.broadcast_to(b, shape)), dtype)
+    step = xp.astype(xp_ravel(xp.broadcast_to(step, shape)), dtype)
+    valid_abstep = xp_ravel(xp.broadcast_to(valid_abstep, shape))
+    nterms = xp.floor((b - a) / step)
+    finite_terms = xp.isfinite(nterms)
+    b[finite_terms] = a[finite_terms] + nterms[finite_terms]*step[finite_terms]
+
+    # Define constants
+    eps = xp.finfo(dtype).eps
+    zero = xp.asarray(-xp.inf if log else 0, dtype=dtype)[()]
+    if rtol is None:
+        rtol = 0.5*math.log(eps) if log else eps**0.5
+    constants = (dtype, log, eps, zero, rtol, atol, maxterms)
+
+    # Prepare result arrays
+    S = xp.empty_like(a)
+    E = xp.empty_like(a)
+    status = xp.zeros(len(a), dtype=xp.int32)
+    nfev = xp.ones(len(a), dtype=xp.int32)  # one function evaluation above
+
+    # Branch for direct sum evaluation / integral approximation / invalid input
+    i0 = ~valid_abstep                     # invalid
+    i0b = b < a                            # zero
+    i1 = (nterms + 1 <= maxterms) & ~i0    # direct sum evaluation
+    i2 = xp.isfinite(a) & ~i1 & ~i0        # infinite sum to the right
+    i3 = xp.isfinite(b) & ~i2 & ~i1 & ~i0  # infinite sum to the left
+    i4 = ~i3 & ~i2 & ~i1 & ~i0             # infinite sum on both sides
+
+    if xp.any(i0):
+        S[i0], E[i0] = xp.nan, xp.nan
+        status[i0] = -1
+
+        S[i0b], E[i0b] = zero, zero
+        status[i0b] = 0
+
+    if xp.any(i1):
+        args_direct = [arg[i1] for arg in args]
+        tmp = _direct(f, a[i1], b[i1], step[i1], args_direct, constants, xp)
+        S[i1], E[i1] = tmp[:-1]
+        nfev[i1] += tmp[-1]
+        status[i1] = -3 * xp.asarray(~xp.isfinite(S[i1]), dtype=xp.int32)
+
+    if xp.any(i2):
+        args_indirect = [arg[i2] for arg in args]
+        tmp = _integral_bound(f, a[i2], b[i2], step[i2],
+                              args_indirect, constants, xp)
+        S[i2], E[i2], status[i2] = tmp[:-1]
+        nfev[i2] += tmp[-1]
+
+    if xp.any(i3):
+        args_indirect = [arg[i3] for arg in args]
+        def _f(x, *args): return f(-x, *args)
+        tmp = _integral_bound(_f, -b[i3], -a[i3], step[i3],
+                              args_indirect, constants, xp)
+        S[i3], E[i3], status[i3] = tmp[:-1]
+        nfev[i3] += tmp[-1]
+
+    if xp.any(i4):
+        args_indirect = [arg[i4] for arg in args]
+
+        # There are two obvious high-level strategies:
+        # - Do two separate half-infinite sums (e.g. from -inf to 0 and 1 to inf)
+        # - Make a callable that returns f(x) + f(-x) and do a single half-infinite sum
+        # I thought the latter would have about half the overhead, so I went that way.
+        # Then there are two ways of ensuring that f(0) doesn't get counted twice.
+        # - Evaluate the sum from 1 to inf and add f(0)
+        # - Evaluate the sum from 0 to inf and subtract f(0)
+        # - Evaluate the sum from 0 to inf, but apply a weight of 0.5 when `x = 0`
+        # The last option has more overhead, but is simpler to implement correctly
+        # (especially getting the status message right)
+        if log:
+            def _f(x, *args):
+                log_factor = xp.where(x==0, math.log(0.5), 0)
+                out = xp.stack([f(x, *args), f(-x, *args)], axis=0)
+                return special.logsumexp(out, axis=0) + log_factor
+
+        else:
+            def _f(x, *args):
+                factor = xp.where(x==0, 0.5, 1)
+                return (f(x, *args) + f(-x, *args)) * factor
+
+        zero = xp.zeros_like(a[i4])
+        tmp = _integral_bound(_f, zero, b[i4], step[i4], args_indirect, constants, xp)
+        S[i4], E[i4], status[i4] = tmp[:-1]
+        nfev[i4] += 2*tmp[-1]
+
+    # Return results
+    S, E = S.reshape(shape)[()], E.reshape(shape)[()]
+    status, nfev = status.reshape(shape)[()], nfev.reshape(shape)[()]
+    return _RichResult(sum=S, error=E, status=status, success=status == 0,
+                       nfev=nfev)
+
+
+def _direct(f, a, b, step, args, constants, xp, inclusive=True):
+    # Directly evaluate the sum.
+
+    # When used in the context of distributions, `args` would contain the
+    # distribution parameters. We have broadcasted for simplicity, but we could
+    # reduce function evaluations when distribution parameters are the same but
+    # sum limits differ. Roughly:
+    # - compute the function at all points between min(a) and max(b),
+    # - compute the cumulative sum,
+    # - take the difference between elements of the cumulative sum
+    #   corresponding with b and a.
+    # This is left to future enhancement
+
+    dtype, log, eps, zero, _, _, _ = constants
+
+    # To allow computation in a single vectorized call, find the maximum number
+    # of points (over all slices) at which the function needs to be evaluated.
+    # Note: if `inclusive` is `True`, then we want `1` more term in the sum.
+    # I didn't think it was great style to use `True` as `1` in Python, so I
+    # explicitly converted it to an `int` before using it.
+    inclusive_adjustment = int(inclusive)
+    steps = xp.round((b - a) / step) + inclusive_adjustment
+    # Equivalently, steps = xp.round((b - a) / step) + inclusive
+    max_steps = int(xp.max(steps))
+
+    # In each slice, the function will be evaluated at the same number of points,
+    # but excessive points (those beyond the right sum limit `b`) are replaced
+    # with NaN to (potentially) reduce the time of these unnecessary calculations.
+    # Use a new last axis for these calculations for consistency with other
+    # elementwise algorithms.
+    a2, b2, step2 = a[:, xp.newaxis], b[:, xp.newaxis], step[:, xp.newaxis]
+    args2 = [arg[:, xp.newaxis] for arg in args]
+    ks = a2 + xp.arange(max_steps, dtype=dtype) * step2
+    i_nan = ks >= (b2 + inclusive_adjustment*step2/2)
+    ks[i_nan] = xp.nan
+    fs = f(ks, *args2)
+
+    # The function evaluated at NaN is NaN, and NaNs are zeroed in the sum.
+    # In some cases it may be faster to loop over slices than to vectorize
+    # like this. This is an optimization that can be added later.
+    fs[i_nan] = zero
+    nfev = max_steps - i_nan.sum(axis=-1)
+    S = special.logsumexp(fs, axis=-1) if log else xp.sum(fs, axis=-1)
+    # Rough, non-conservative error estimate. See gh-19667 for improvement ideas.
+    E = xp.real(S) + math.log(eps) if log else eps * abs(S)
+    return S, E, nfev
+
+
+def _integral_bound(f, a, b, step, args, constants, xp):
+    # Estimate the sum with integral approximation
+    dtype, log, _, _, rtol, atol, maxterms = constants
+    log2 = xp.asarray(math.log(2), dtype=dtype)
+
+    # Get a lower bound on the sum and compute effective absolute tolerance
+    lb = tanhsinh(f, a, b, args=args, atol=atol, rtol=rtol, log=log)
+    tol = xp.broadcast_to(xp.asarray(atol), lb.integral.shape)
+    if log:
+        tol = special.logsumexp(xp.stack((tol, rtol + lb.integral)), axis=0)
+    else:
+        tol = tol + rtol*lb.integral
+    i_skip = lb.status == -3  # avoid unnecessary f_evals if integral is divergent
+    tol[i_skip] = xp.nan
+    status = lb.status
+
+    # As in `_direct`, we'll need a temporary new axis for points
+    # at which to evaluate the function. Append axis at the end for
+    # consistency with other elementwise algorithms.
+    a2 = a[..., xp.newaxis]
+    step2 = step[..., xp.newaxis]
+    args2 = [arg[..., xp.newaxis] for arg in args]
+
+    # Find the location of a term that is less than the tolerance (if possible)
+    log2maxterms = math.floor(math.log2(maxterms)) if maxterms else 0
+    n_steps = xp.concat((2**xp.arange(0, log2maxterms), xp.asarray([maxterms])))
+    n_steps = xp.astype(n_steps, dtype)
+    nfev = len(n_steps) * 2
+    ks = a2 + n_steps * step2
+    fks = f(ks, *args2)
+    fksp1 = f(ks + step2, *args2)  # check that the function is decreasing
+    fk_insufficient = (fks > tol[:, xp.newaxis]) | (fksp1 > fks)
+    n_fk_insufficient = xp.sum(fk_insufficient, axis=-1)
+    nt = xp.minimum(n_fk_insufficient, n_steps.shape[-1]-1)
+    n_steps = n_steps[nt]
+
+    # If `maxterms` is insufficient (i.e. either the magnitude of the last term of the
+    # partial sum exceeds the tolerance or the function is not decreasing), finish the
+    # calculation, but report nonzero status. (Improvement: separate the status codes
+    # for these two cases.)
+    i_fk_insufficient = (n_fk_insufficient == nfev//2)
+
+    # Directly evaluate the sum up to this term
+    k = a + n_steps * step
+    left, left_error, left_nfev = _direct(f, a, k, step, args,
+                                          constants, xp, inclusive=False)
+    left_is_pos_inf = xp.isinf(left) & (left > 0)
+    i_skip |= left_is_pos_inf  # if sum is infinite, no sense in continuing
+    status[left_is_pos_inf] = -3
+    k[i_skip] = xp.nan
+
+    # Use integration to estimate the remaining sum
+    # Possible optimization for future work: if there were no terms less than
+    # the tolerance, there is no need to compute the integral to better accuracy.
+    # Something like:
+    # atol = xp.maximum(atol, xp.minimum(fk/2 - fb/2))
+    # rtol = xp.maximum(rtol, xp.minimum((fk/2 - fb/2)/left))
+    # where `fk`/`fb` are currently calculated below.
+    right = tanhsinh(f, k, b, args=args, atol=atol, rtol=rtol, log=log)
+
+    # Calculate the full estimate and error from the pieces
+    fk = fks[xp.arange(len(fks)), nt]
+
+    # fb = f(b, *args), but some functions return NaN at infinity.
+    # instead of 0 like they must (for the sum to be convergent).
+    fb = xp.full_like(fk, -xp.inf) if log else xp.zeros_like(fk)
+    i = xp.isfinite(b)
+    if xp.any(i):  # better not call `f` with empty arrays
+        fb[i] = f(b[i], *[arg[i] for arg in args])
+    nfev = nfev + xp.asarray(i, dtype=left_nfev.dtype)
+
+    if log:
+        log_step = xp.log(step)
+        S_terms = (left, right.integral - log_step, fk - log2, fb - log2)
+        S = special.logsumexp(xp.stack(S_terms), axis=0)
+        E_terms = (left_error, right.error - log_step, fk-log2, fb-log2+xp.pi*1j)
+        E = xp.real(special.logsumexp(xp.stack(E_terms), axis=0))
+    else:
+        S = left + right.integral/step + fk/2 + fb/2
+        E = left_error + right.error/step + fk/2 - fb/2
+    status[~i_skip] = right.status[~i_skip]
+
+    status[(status == 0) & i_fk_insufficient] = -4
+    return S, E, status, left_nfev + right.nfev + nfev + lb.nfev
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_test_multivariate.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_test_multivariate.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..d98a4a7990936e16dffece99c88dad16225095d8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_test_multivariate.cpython-312-x86_64-linux-gnu.so differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_test_odeint_banded.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_test_odeint_banded.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..3e03d8081647faec735b6d65bc1ebe5a30fbe2a7
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_test_odeint_banded.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:8262fc06a56cee7b5417f660131f435a35262c7ab6cd19947490346f7e7a2bc9
+size 520681
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_vode.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_vode.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..c48f401d17d76b984d3d08dcb79c90d9b1f2dcd6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/_vode.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:dad907422f261f219b5498288130906176a10ee0bc56b916cee4d9d867bd53e4
+size 570081
diff --git a/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/dop.py b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/dop.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf67a9a35b7d2959c2617aadc5638b577a45b9b5
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/scipy/integrate/dop.py
@@ -0,0 +1,15 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__: list[str] = []
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="integrate", module="dop",
+                                   private_modules=["_dop"], all=__all__,
+                                   attribute=name)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk-2.35.2.dist-info/licenses/LICENSE b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk-2.35.2.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..016323bd8da88e224808bebf892dabc485c85387
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk-2.35.2.dist-info/licenses/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2018 Functional Software, Inc. dba Sentry
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f480dc7cc72243904cf271866d9b9306c72a255b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/_compat.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/_compat.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dca16bfcdbf2942528fd21b6c8bef0a62b89d7df
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/_compat.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/_init_implementation.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/_init_implementation.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b4700549ec954fd4706be136f6b784128de26dcd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/_init_implementation.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/_log_batcher.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/_log_batcher.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..68883103662be3880d29e09e11fd1b102e569975
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/_log_batcher.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/_lru_cache.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/_lru_cache.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6701731ef31bfa02d266391bd2e03d529abcf79d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/_lru_cache.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/_queue.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/_queue.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..31c078ec28d215d24a4aa53853a1c6e43c2a4518
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/_queue.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/_types.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/_types.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e2584f6bf506ec2315c05e8dba9214028e3dc643
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/_types.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/_werkzeug.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/_werkzeug.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d12df29df23a730e6224bb727005852185ee3da1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/_werkzeug.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/api.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/api.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4a13b0997cb7c5cc98d138ba5cc2b3813803ad91
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/api.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/attachments.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/attachments.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6de6c11eb5f1956b8aca3b8ceb2109f344e72ae5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/attachments.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/client.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/client.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..12aa7bce27916952ab4de74df6a223c03927a7ae
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/client.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/consts.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/consts.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4966960c1240518bd86c033d6047bc4a57292b71
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/consts.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/debug.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/debug.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..47229e6e10ed5c5c1ab239133d3ee48339e9efce
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/debug.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/envelope.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/envelope.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..42436507253c909af8cbdaeb7459ceadc7187174
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/envelope.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/feature_flags.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/feature_flags.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..71827a3d4e6cba01a9acae87029b940e7519c3b6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/feature_flags.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/hub.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/hub.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aeba8888c81d20e42b437e88497e176a64a30143
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/hub.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/logger.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/logger.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cb071eda76cdf4a57be1b89d81bf749222aca0ca
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/logger.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/metrics.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/metrics.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1687e82e9d329ed1b6a6083a898025bb01789401
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/metrics.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/monitor.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/monitor.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9f632090f0200f471d63c36ae57e1d70ef3087b3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/monitor.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/scope.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/scope.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fc54758c5cda1bc261f064c58f1e0e37dc67b64b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/scope.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/scrubber.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/scrubber.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2bde5562b0ff54ec5b641cdab84205455ac5ce87
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/scrubber.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/serializer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/serializer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b1aec708cb7cb5dcece2fe2b9293072ae58ae6d2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/serializer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/session.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/session.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ce8964db5b244885ce0a3c000e6c869e08ea543
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/session.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/sessions.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/sessions.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..91256ee3e0e6310d010280df27dc69dbe883a052
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/sessions.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/spotlight.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/spotlight.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3b6650e7ce1ef69d1514e27b074c7c7d175ff806
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/spotlight.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/tracing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/tracing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..16c1eedec53d0e45fbd30a6b55645d1fd673ff1e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/tracing.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/tracing_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/tracing_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7b40a5cd3e7bf3dd1f0a0b100403abc4d5e30125
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/tracing_utils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/transport.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/transport.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..127d66c335f34bc7272c415a70a36cc3f668c383
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/transport.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/types.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/types.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9da295d69cf566e7453c9c2a440d6f7f402d74b3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/types.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..35ee03f983f60fe0da5a71e836bab1e22429c952
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/utils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/worker.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/worker.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a4d1e882ffab700da8792fcae75bbd4acb7d3f95
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/__pycache__/worker.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/ai/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/ai/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/ai/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/ai/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bc2270f30406316263745c5408ad1f3d83e01a3e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/ai/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/ai/__pycache__/monitoring.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/ai/__pycache__/monitoring.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..79a91771ff0d519c14ef26fd72ca696ab8d97d25
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/ai/__pycache__/monitoring.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/ai/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/ai/__pycache__/utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6840a140d04b0eb0cd9e54f81c4a39d2aa6578f5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/ai/__pycache__/utils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/ai/monitoring.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/ai/monitoring.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3f372c3ba3a797a098263184ae9087fcb6572de
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/ai/monitoring.py
@@ -0,0 +1,135 @@
+import inspect
+from functools import wraps
+
+from sentry_sdk.consts import SPANDATA
+import sentry_sdk.utils
+from sentry_sdk import start_span
+from sentry_sdk.tracing import Span
+from sentry_sdk.utils import ContextVar
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Optional, Callable, Any
+
+_ai_pipeline_name = ContextVar("ai_pipeline_name", default=None)
+
+
+def set_ai_pipeline_name(name):
+    # type: (Optional[str]) -> None
+    _ai_pipeline_name.set(name)
+
+
+def get_ai_pipeline_name():
+    # type: () -> Optional[str]
+    return _ai_pipeline_name.get()
+
+
+def ai_track(description, **span_kwargs):
+    # type: (str, Any) -> Callable[..., Any]
+    def decorator(f):
+        # type: (Callable[..., Any]) -> Callable[..., Any]
+        def sync_wrapped(*args, **kwargs):
+            # type: (Any, Any) -> Any
+            curr_pipeline = _ai_pipeline_name.get()
+            op = span_kwargs.pop("op", "ai.run" if curr_pipeline else "ai.pipeline")
+
+            with start_span(name=description, op=op, **span_kwargs) as span:
+                for k, v in kwargs.pop("sentry_tags", {}).items():
+                    span.set_tag(k, v)
+                for k, v in kwargs.pop("sentry_data", {}).items():
+                    span.set_data(k, v)
+                if curr_pipeline:
+                    span.set_data(SPANDATA.GEN_AI_PIPELINE_NAME, curr_pipeline)
+                    return f(*args, **kwargs)
+                else:
+                    _ai_pipeline_name.set(description)
+                    try:
+                        res = f(*args, **kwargs)
+                    except Exception as e:
+                        event, hint = sentry_sdk.utils.event_from_exception(
+                            e,
+                            client_options=sentry_sdk.get_client().options,
+                            mechanism={"type": "ai_monitoring", "handled": False},
+                        )
+                        sentry_sdk.capture_event(event, hint=hint)
+                        raise e from None
+                    finally:
+                        _ai_pipeline_name.set(None)
+                    return res
+
+        async def async_wrapped(*args, **kwargs):
+            # type: (Any, Any) -> Any
+            curr_pipeline = _ai_pipeline_name.get()
+            op = span_kwargs.pop("op", "ai.run" if curr_pipeline else "ai.pipeline")
+
+            with start_span(name=description, op=op, **span_kwargs) as span:
+                for k, v in kwargs.pop("sentry_tags", {}).items():
+                    span.set_tag(k, v)
+                for k, v in kwargs.pop("sentry_data", {}).items():
+                    span.set_data(k, v)
+                if curr_pipeline:
+                    span.set_data(SPANDATA.GEN_AI_PIPELINE_NAME, curr_pipeline)
+                    return await f(*args, **kwargs)
+                else:
+                    _ai_pipeline_name.set(description)
+                    try:
+                        res = await f(*args, **kwargs)
+                    except Exception as e:
+                        event, hint = sentry_sdk.utils.event_from_exception(
+                            e,
+                            client_options=sentry_sdk.get_client().options,
+                            mechanism={"type": "ai_monitoring", "handled": False},
+                        )
+                        sentry_sdk.capture_event(event, hint=hint)
+                        raise e from None
+                    finally:
+                        _ai_pipeline_name.set(None)
+                    return res
+
+        if inspect.iscoroutinefunction(f):
+            return wraps(f)(async_wrapped)
+        else:
+            return wraps(f)(sync_wrapped)
+
+    return decorator
+
+
+def record_token_usage(
+    span,
+    input_tokens=None,
+    input_tokens_cached=None,
+    output_tokens=None,
+    output_tokens_reasoning=None,
+    total_tokens=None,
+):
+    # type: (Span, Optional[int], Optional[int], Optional[int], Optional[int], Optional[int]) -> None
+
+    # TODO: move pipeline name elsewhere
+    ai_pipeline_name = get_ai_pipeline_name()
+    if ai_pipeline_name:
+        span.set_data(SPANDATA.GEN_AI_PIPELINE_NAME, ai_pipeline_name)
+
+    if input_tokens is not None:
+        span.set_data(SPANDATA.GEN_AI_USAGE_INPUT_TOKENS, input_tokens)
+
+    if input_tokens_cached is not None:
+        span.set_data(
+            SPANDATA.GEN_AI_USAGE_INPUT_TOKENS_CACHED,
+            input_tokens_cached,
+        )
+
+    if output_tokens is not None:
+        span.set_data(SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS, output_tokens)
+
+    if output_tokens_reasoning is not None:
+        span.set_data(
+            SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS_REASONING,
+            output_tokens_reasoning,
+        )
+
+    if total_tokens is None and input_tokens is not None and output_tokens is not None:
+        total_tokens = input_tokens + output_tokens
+
+    if total_tokens is not None:
+        span.set_data(SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS, total_tokens)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/ai/utils.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/ai/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf52cba6e8dbcc4d903dce9bc84fed342d1628ad
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/ai/utils.py
@@ -0,0 +1,36 @@
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+
+from sentry_sdk.tracing import Span
+from sentry_sdk.utils import logger
+
+
+def _normalize_data(data, unpack=True):
+    # type: (Any, bool) -> Any
+
+    # convert pydantic data (e.g. OpenAI v1+) to json compatible format
+    if hasattr(data, "model_dump"):
+        try:
+            return data.model_dump()
+        except Exception as e:
+            logger.warning("Could not convert pydantic data to JSON: %s", e)
+            return data
+    if isinstance(data, list):
+        if unpack and len(data) == 1:
+            return _normalize_data(data[0], unpack=unpack)  # remove empty dimensions
+        return list(_normalize_data(x, unpack=unpack) for x in data)
+    if isinstance(data, dict):
+        return {k: _normalize_data(v, unpack=unpack) for (k, v) in data.items()}
+
+    return data
+
+
+def set_data_normalized(span, key, value, unpack=True):
+    # type: (Span, str, Any, bool) -> None
+    normalized = _normalize_data(value, unpack=unpack)
+    if isinstance(normalized, (int, float, bool, str)):
+        span.set_data(key, normalized)
+    else:
+        span.set_data(key, str(normalized))
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f748aaecb6b36b2d837493d5533691d8058124f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/__init__.py
@@ -0,0 +1,10 @@
+from sentry_sdk.crons.api import capture_checkin
+from sentry_sdk.crons.consts import MonitorStatus
+from sentry_sdk.crons.decorator import monitor
+
+
+__all__ = [
+    "capture_checkin",
+    "MonitorStatus",
+    "monitor",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..93acd139a8cab2a5476164a68845309a2fa7f0df
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/__pycache__/api.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/__pycache__/api.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85f0f15987d2e889bf0e3ed5b0b0d08a9999fcfa
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/__pycache__/api.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/__pycache__/consts.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/__pycache__/consts.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d0b9b3e4f8f64b35b1a20a97bb9fc97a3c051f0a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/__pycache__/consts.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/__pycache__/decorator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/__pycache__/decorator.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8571b2f764d18dc17f672cf2f8cf9d9a20c20979
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/__pycache__/decorator.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/api.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..b67e5961c80a7ac251cc4e7bf0b968e7d4560041
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/api.py
@@ -0,0 +1,62 @@
+import uuid
+
+import sentry_sdk
+from sentry_sdk.utils import logger
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Optional
+    from sentry_sdk._types import Event, MonitorConfig
+
+
+def _create_check_in_event(
+    monitor_slug=None,  # type: Optional[str]
+    check_in_id=None,  # type: Optional[str]
+    status=None,  # type: Optional[str]
+    duration_s=None,  # type: Optional[float]
+    monitor_config=None,  # type: Optional[MonitorConfig]
+):
+    # type: (...) -> Event
+    options = sentry_sdk.get_client().options
+    check_in_id = check_in_id or uuid.uuid4().hex  # type: str
+
+    check_in = {
+        "type": "check_in",
+        "monitor_slug": monitor_slug,
+        "check_in_id": check_in_id,
+        "status": status,
+        "duration": duration_s,
+        "environment": options.get("environment", None),
+        "release": options.get("release", None),
+    }  # type: Event
+
+    if monitor_config:
+        check_in["monitor_config"] = monitor_config
+
+    return check_in
+
+
+def capture_checkin(
+    monitor_slug=None,  # type: Optional[str]
+    check_in_id=None,  # type: Optional[str]
+    status=None,  # type: Optional[str]
+    duration=None,  # type: Optional[float]
+    monitor_config=None,  # type: Optional[MonitorConfig]
+):
+    # type: (...) -> str
+    check_in_event = _create_check_in_event(
+        monitor_slug=monitor_slug,
+        check_in_id=check_in_id,
+        status=status,
+        duration_s=duration,
+        monitor_config=monitor_config,
+    )
+
+    sentry_sdk.capture_event(check_in_event)
+
+    logger.debug(
+        f"[Crons] Captured check-in ({check_in_event.get('check_in_id')}): {check_in_event.get('monitor_slug')} -> {check_in_event.get('status')}"
+    )
+
+    return check_in_event["check_in_id"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/consts.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/consts.py
new file mode 100644
index 0000000000000000000000000000000000000000..be686b4539439d33aa6d3f1391d2179e93d45bcf
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/consts.py
@@ -0,0 +1,4 @@
+class MonitorStatus:
+    IN_PROGRESS = "in_progress"
+    OK = "ok"
+    ERROR = "error"
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/decorator.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/decorator.py
new file mode 100644
index 0000000000000000000000000000000000000000..9af00e61c0675772a7ac7480c388acb5d7a0e5ee
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/crons/decorator.py
@@ -0,0 +1,135 @@
+from functools import wraps
+from inspect import iscoroutinefunction
+
+from sentry_sdk.crons import capture_checkin
+from sentry_sdk.crons.consts import MonitorStatus
+from sentry_sdk.utils import now
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from collections.abc import Awaitable, Callable
+    from types import TracebackType
+    from typing import (
+        Any,
+        Optional,
+        ParamSpec,
+        Type,
+        TypeVar,
+        Union,
+        cast,
+        overload,
+    )
+    from sentry_sdk._types import MonitorConfig
+
+    P = ParamSpec("P")
+    R = TypeVar("R")
+
+
+class monitor:  # noqa: N801
+    """
+    Decorator/context manager to capture checkin events for a monitor.
+
+    Usage (as decorator):
+    ```
+    import sentry_sdk
+
+    app = Celery()
+
+    @app.task
+    @sentry_sdk.monitor(monitor_slug='my-fancy-slug')
+    def test(arg):
+        print(arg)
+    ```
+
+    This does not have to be used with Celery, but if you do use it with celery,
+    put the `@sentry_sdk.monitor` decorator below Celery's `@app.task` decorator.
+
+    Usage (as context manager):
+    ```
+    import sentry_sdk
+
+    def test(arg):
+        with sentry_sdk.monitor(monitor_slug='my-fancy-slug'):
+            print(arg)
+    ```
+    """
+
+    def __init__(self, monitor_slug=None, monitor_config=None):
+        # type: (Optional[str], Optional[MonitorConfig]) -> None
+        self.monitor_slug = monitor_slug
+        self.monitor_config = monitor_config
+
+    def __enter__(self):
+        # type: () -> None
+        self.start_timestamp = now()
+        self.check_in_id = capture_checkin(
+            monitor_slug=self.monitor_slug,
+            status=MonitorStatus.IN_PROGRESS,
+            monitor_config=self.monitor_config,
+        )
+
+    def __exit__(self, exc_type, exc_value, traceback):
+        # type: (Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]) -> None
+        duration_s = now() - self.start_timestamp
+
+        if exc_type is None and exc_value is None and traceback is None:
+            status = MonitorStatus.OK
+        else:
+            status = MonitorStatus.ERROR
+
+        capture_checkin(
+            monitor_slug=self.monitor_slug,
+            check_in_id=self.check_in_id,
+            status=status,
+            duration=duration_s,
+            monitor_config=self.monitor_config,
+        )
+
+    if TYPE_CHECKING:
+
+        @overload
+        def __call__(self, fn):
+            # type: (Callable[P, Awaitable[Any]]) -> Callable[P, Awaitable[Any]]
+            # Unfortunately, mypy does not give us any reliable way to type check the
+            # return value of an Awaitable (i.e. async function) for this overload,
+            # since calling iscouroutinefunction narrows the type to Callable[P, Awaitable[Any]].
+            ...
+
+        @overload
+        def __call__(self, fn):
+            # type: (Callable[P, R]) -> Callable[P, R]
+            ...
+
+    def __call__(
+        self,
+        fn,  # type: Union[Callable[P, R], Callable[P, Awaitable[Any]]]
+    ):
+        # type: (...) -> Union[Callable[P, R], Callable[P, Awaitable[Any]]]
+        if iscoroutinefunction(fn):
+            return self._async_wrapper(fn)
+
+        else:
+            if TYPE_CHECKING:
+                fn = cast("Callable[P, R]", fn)
+            return self._sync_wrapper(fn)
+
+    def _async_wrapper(self, fn):
+        # type: (Callable[P, Awaitable[Any]]) -> Callable[P, Awaitable[Any]]
+        @wraps(fn)
+        async def inner(*args: "P.args", **kwargs: "P.kwargs"):
+            # type: (...) -> R
+            with self:
+                return await fn(*args, **kwargs)
+
+        return inner
+
+    def _sync_wrapper(self, fn):
+        # type: (Callable[P, R]) -> Callable[P, R]
+        @wraps(fn)
+        def inner(*args: "P.args", **kwargs: "P.kwargs"):
+            # type: (...) -> R
+            with self:
+                return fn(*args, **kwargs)
+
+        return inner
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2eadd523da6ce4f985059891ec5029f4e91d03b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__init__.py
@@ -0,0 +1,295 @@
+from abc import ABC, abstractmethod
+from threading import Lock
+
+from sentry_sdk.utils import logger
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from collections.abc import Sequence
+    from typing import Callable
+    from typing import Dict
+    from typing import Iterator
+    from typing import List
+    from typing import Optional
+    from typing import Set
+    from typing import Type
+    from typing import Union
+
+
+_DEFAULT_FAILED_REQUEST_STATUS_CODES = frozenset(range(500, 600))
+
+
+_installer_lock = Lock()
+
+# Set of all integration identifiers we have attempted to install
+_processed_integrations = set()  # type: Set[str]
+
+# Set of all integration identifiers we have actually installed
+_installed_integrations = set()  # type: Set[str]
+
+
+def _generate_default_integrations_iterator(
+    integrations,  # type: List[str]
+    auto_enabling_integrations,  # type: List[str]
+):
+    # type: (...) -> Callable[[bool], Iterator[Type[Integration]]]
+
+    def iter_default_integrations(with_auto_enabling_integrations):
+        # type: (bool) -> Iterator[Type[Integration]]
+        """Returns an iterator of the default integration classes:"""
+        from importlib import import_module
+
+        if with_auto_enabling_integrations:
+            all_import_strings = integrations + auto_enabling_integrations
+        else:
+            all_import_strings = integrations
+
+        for import_string in all_import_strings:
+            try:
+                module, cls = import_string.rsplit(".", 1)
+                yield getattr(import_module(module), cls)
+            except (DidNotEnable, SyntaxError) as e:
+                logger.debug(
+                    "Did not import default integration %s: %s", import_string, e
+                )
+
+    if isinstance(iter_default_integrations.__doc__, str):
+        for import_string in integrations:
+            iter_default_integrations.__doc__ += "\n- `{}`".format(import_string)
+
+    return iter_default_integrations
+
+
+_DEFAULT_INTEGRATIONS = [
+    # stdlib/base runtime integrations
+    "sentry_sdk.integrations.argv.ArgvIntegration",
+    "sentry_sdk.integrations.atexit.AtexitIntegration",
+    "sentry_sdk.integrations.dedupe.DedupeIntegration",
+    "sentry_sdk.integrations.excepthook.ExcepthookIntegration",
+    "sentry_sdk.integrations.logging.LoggingIntegration",
+    "sentry_sdk.integrations.modules.ModulesIntegration",
+    "sentry_sdk.integrations.stdlib.StdlibIntegration",
+    "sentry_sdk.integrations.threading.ThreadingIntegration",
+]
+
+_AUTO_ENABLING_INTEGRATIONS = [
+    "sentry_sdk.integrations.aiohttp.AioHttpIntegration",
+    "sentry_sdk.integrations.anthropic.AnthropicIntegration",
+    "sentry_sdk.integrations.ariadne.AriadneIntegration",
+    "sentry_sdk.integrations.arq.ArqIntegration",
+    "sentry_sdk.integrations.asyncpg.AsyncPGIntegration",
+    "sentry_sdk.integrations.boto3.Boto3Integration",
+    "sentry_sdk.integrations.bottle.BottleIntegration",
+    "sentry_sdk.integrations.celery.CeleryIntegration",
+    "sentry_sdk.integrations.chalice.ChaliceIntegration",
+    "sentry_sdk.integrations.clickhouse_driver.ClickhouseDriverIntegration",
+    "sentry_sdk.integrations.cohere.CohereIntegration",
+    "sentry_sdk.integrations.django.DjangoIntegration",
+    "sentry_sdk.integrations.falcon.FalconIntegration",
+    "sentry_sdk.integrations.fastapi.FastApiIntegration",
+    "sentry_sdk.integrations.flask.FlaskIntegration",
+    "sentry_sdk.integrations.gql.GQLIntegration",
+    "sentry_sdk.integrations.graphene.GrapheneIntegration",
+    "sentry_sdk.integrations.httpx.HttpxIntegration",
+    "sentry_sdk.integrations.huey.HueyIntegration",
+    "sentry_sdk.integrations.huggingface_hub.HuggingfaceHubIntegration",
+    "sentry_sdk.integrations.langchain.LangchainIntegration",
+    "sentry_sdk.integrations.litestar.LitestarIntegration",
+    "sentry_sdk.integrations.loguru.LoguruIntegration",
+    "sentry_sdk.integrations.openai.OpenAIIntegration",
+    "sentry_sdk.integrations.pymongo.PyMongoIntegration",
+    "sentry_sdk.integrations.pyramid.PyramidIntegration",
+    "sentry_sdk.integrations.quart.QuartIntegration",
+    "sentry_sdk.integrations.redis.RedisIntegration",
+    "sentry_sdk.integrations.rq.RqIntegration",
+    "sentry_sdk.integrations.sanic.SanicIntegration",
+    "sentry_sdk.integrations.sqlalchemy.SqlalchemyIntegration",
+    "sentry_sdk.integrations.starlette.StarletteIntegration",
+    "sentry_sdk.integrations.starlite.StarliteIntegration",
+    "sentry_sdk.integrations.strawberry.StrawberryIntegration",
+    "sentry_sdk.integrations.tornado.TornadoIntegration",
+]
+
+iter_default_integrations = _generate_default_integrations_iterator(
+    integrations=_DEFAULT_INTEGRATIONS,
+    auto_enabling_integrations=_AUTO_ENABLING_INTEGRATIONS,
+)
+
+del _generate_default_integrations_iterator
+
+
+_MIN_VERSIONS = {
+    "aiohttp": (3, 4),
+    "anthropic": (0, 16),
+    "ariadne": (0, 20),
+    "arq": (0, 23),
+    "asyncpg": (0, 23),
+    "beam": (2, 12),
+    "boto3": (1, 12),  # botocore
+    "bottle": (0, 12),
+    "celery": (4, 4, 7),
+    "chalice": (1, 16, 0),
+    "clickhouse_driver": (0, 2, 0),
+    "cohere": (5, 4, 0),
+    "django": (1, 8),
+    "dramatiq": (1, 9),
+    "falcon": (1, 4),
+    "fastapi": (0, 79, 0),
+    "flask": (1, 1, 4),
+    "gql": (3, 4, 1),
+    "graphene": (3, 3),
+    "grpc": (1, 32, 0),  # grpcio
+    "huggingface_hub": (0, 22),
+    "langchain": (0, 0, 210),
+    "launchdarkly": (9, 8, 0),
+    "loguru": (0, 7, 0),
+    "openai": (1, 0, 0),
+    "openai_agents": (0, 0, 19),
+    "openfeature": (0, 7, 1),
+    "quart": (0, 16, 0),
+    "ray": (2, 7, 0),
+    "requests": (2, 0, 0),
+    "rq": (0, 6),
+    "sanic": (0, 8),
+    "sqlalchemy": (1, 2),
+    "starlette": (0, 16),
+    "starlite": (1, 48),
+    "statsig": (0, 55, 3),
+    "strawberry": (0, 209, 5),
+    "tornado": (6, 0),
+    "typer": (0, 15),
+    "unleash": (6, 0, 1),
+}
+
+
+def setup_integrations(
+    integrations,
+    with_defaults=True,
+    with_auto_enabling_integrations=False,
+    disabled_integrations=None,
+):
+    # type: (Sequence[Integration], bool, bool, Optional[Sequence[Union[type[Integration], Integration]]]) -> Dict[str, Integration]
+    """
+    Given a list of integration instances, this installs them all.
+
+    When `with_defaults` is set to `True` all default integrations are added
+    unless they were already provided before.
+
+    `disabled_integrations` takes precedence over `with_defaults` and
+    `with_auto_enabling_integrations`.
+    """
+    integrations = dict(
+        (integration.identifier, integration) for integration in integrations or ()
+    )
+
+    logger.debug("Setting up integrations (with default = %s)", with_defaults)
+
+    # Integrations that will not be enabled
+    disabled_integrations = [
+        integration if isinstance(integration, type) else type(integration)
+        for integration in disabled_integrations or []
+    ]
+
+    # Integrations that are not explicitly set up by the user.
+    used_as_default_integration = set()
+
+    if with_defaults:
+        for integration_cls in iter_default_integrations(
+            with_auto_enabling_integrations
+        ):
+            if integration_cls.identifier not in integrations:
+                instance = integration_cls()
+                integrations[instance.identifier] = instance
+                used_as_default_integration.add(instance.identifier)
+
+    for identifier, integration in integrations.items():
+        with _installer_lock:
+            if identifier not in _processed_integrations:
+                if type(integration) in disabled_integrations:
+                    logger.debug("Ignoring integration %s", identifier)
+                else:
+                    logger.debug(
+                        "Setting up previously not enabled integration %s", identifier
+                    )
+                    try:
+                        type(integration).setup_once()
+                    except DidNotEnable as e:
+                        if identifier not in used_as_default_integration:
+                            raise
+
+                        logger.debug(
+                            "Did not enable default integration %s: %s", identifier, e
+                        )
+                    else:
+                        _installed_integrations.add(identifier)
+
+                _processed_integrations.add(identifier)
+
+    integrations = {
+        identifier: integration
+        for identifier, integration in integrations.items()
+        if identifier in _installed_integrations
+    }
+
+    for identifier in integrations:
+        logger.debug("Enabling integration %s", identifier)
+
+    return integrations
+
+
+def _check_minimum_version(integration, version, package=None):
+    # type: (type[Integration], Optional[tuple[int, ...]], Optional[str]) -> None
+    package = package or integration.identifier
+
+    if version is None:
+        raise DidNotEnable(f"Unparsable {package} version.")
+
+    min_version = _MIN_VERSIONS.get(integration.identifier)
+    if min_version is None:
+        return
+
+    if version < min_version:
+        raise DidNotEnable(
+            f"Integration only supports {package} {'.'.join(map(str, min_version))} or newer."
+        )
+
+
+class DidNotEnable(Exception):  # noqa: N818
+    """
+    The integration could not be enabled due to a trivial user error like
+    `flask` not being installed for the `FlaskIntegration`.
+
+    This exception is silently swallowed for default integrations, but reraised
+    for explicitly enabled integrations.
+    """
+
+
+class Integration(ABC):
+    """Baseclass for all integrations.
+
+    To accept options for an integration, implement your own constructor that
+    saves those options on `self`.
+    """
+
+    install = None
+    """Legacy method, do not implement."""
+
+    identifier = None  # type: str
+    """String unique ID of integration type"""
+
+    @staticmethod
+    @abstractmethod
+    def setup_once():
+        # type: () -> None
+        """
+        Initialize the integration.
+
+        This function is only called once, ever. Configuration is not available
+        at this point, so the only thing to do here is to hook into exception
+        handlers, and perhaps do monkeypatches.
+
+        Inside those hooks `Integration.current` can be used to access the
+        instance again.
+        """
+        pass
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b5ffb76cadd60d1777fee4a51f75e26be58bd4a2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/_asgi_common.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/_asgi_common.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3d50796ef43ad7e5cb00d7efd3f95a811593d9a4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/_asgi_common.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/_wsgi_common.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/_wsgi_common.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e8cdd27cf08392a3427da247fd324c759fb52ff2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/_wsgi_common.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/aiohttp.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/aiohttp.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..90e4153ba7a468246208c91ceb394f52a1116ac0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/aiohttp.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/anthropic.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/anthropic.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bb2c50fbca3638291a1d658fbbb9641b0ed467de
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/anthropic.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/argv.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/argv.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..462af7542f04222133f6b251d2493c2867e46575
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/argv.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/ariadne.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/ariadne.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e62e60b793028f8c46a8f158a08483f2ba03d8cc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/ariadne.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/arq.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/arq.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c8371ec74d51aec459d8ffae4c2d27bb6084c17e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/arq.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/asgi.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/asgi.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9d6db7b773496db8c83e0c1cc203339c1d8ba64f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/asgi.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/asyncio.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/asyncio.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..91b12f0337b5fc09f64b06765642d4aef608a54a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/asyncio.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/asyncpg.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/asyncpg.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f27bdaa782ae52a91a8d117a5c11476ef287fc4e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/asyncpg.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/atexit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/atexit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eca9dad5856cad6b0eab60d94b9f66e670310afb
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/atexit.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/aws_lambda.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/aws_lambda.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9e8be0a3fad273f9cd0d49d9f6e2b79da3a4a8b7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/aws_lambda.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/beam.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/beam.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c4ee35ac95105cc3fe0fed2238afb2b16ab9b61c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/beam.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/boto3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/boto3.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9cee10952e5b9497616b4a6e7bd163e73ef9d470
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/boto3.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/bottle.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/bottle.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..039604f1dab5528bfba73d2f4357914e6fb42157
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/bottle.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/chalice.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/chalice.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dfdb288e01b6bca3dd72e6e07d322a026881029a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/chalice.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/clickhouse_driver.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/clickhouse_driver.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f1eb39693496acd8ec5d5e0347fd2d20754cb0f0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/clickhouse_driver.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/cloud_resource_context.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/cloud_resource_context.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..52a4d089586bc76de275925bb06fdb0ed937e9a5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/cloud_resource_context.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/cohere.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/cohere.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3b798d9777e5268c013517fef1be7841bd391a14
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/cohere.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/dedupe.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/dedupe.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cc3bdbe617d2feafdfe8424c7bc89bac46144675
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/dedupe.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/dramatiq.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/dramatiq.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b98c3d75bb3b023503d3a0fae8729f1eceeb92d7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/dramatiq.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/excepthook.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/excepthook.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3eb4f05fa7493d1697ec45f08f59a543acf16e4c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/excepthook.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/executing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/executing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..467d9cc961c4b6450fcb89816c02365e141250e9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/executing.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/falcon.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/falcon.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a08f71dc985ac28393ccc110d3a5d7e209cdbdf8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/falcon.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/fastapi.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/fastapi.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0fc1370679cdec4696592dd8250a28180fa1376c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/fastapi.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/flask.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/flask.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..143d34efb395f4f11b8a7c13002e367151724631
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/flask.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/gcp.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/gcp.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9c048bee002eff04d3fad73726c81551d87c4a3c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/gcp.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/gnu_backtrace.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/gnu_backtrace.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2fe8d777584ba258e825541c588661bcc58fae98
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/gnu_backtrace.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/gql.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/gql.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..95c00c85d3a11770e541be97885f360d055b141f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/gql.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/graphene.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/graphene.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6ec4723bc727d5560f23b6cf8649d7c86df46347
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/graphene.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/httpx.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/httpx.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..327e6358835ebc06d2d0d00edbd7fccef312a3cb
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/httpx.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/huey.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/huey.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2bf54e8cbef35e449b553cc6eea4fd5e8703f86c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/huey.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/huggingface_hub.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/huggingface_hub.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a03d1fcf05a26ebadff4417b5e6c05e32bdd9f59
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/huggingface_hub.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/langchain.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/langchain.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2c515a71b894961258203efe29409a19f56dee50
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/langchain.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/launchdarkly.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/launchdarkly.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..301d8bb6840ccaa6e8667f8ec7a0f97ffa9fa2e6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/launchdarkly.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/litestar.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/litestar.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a9fae4a83446011fe1442d94c47a689418dd9c10
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/litestar.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/logging.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/logging.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..10b51e641592fad6f423eb4195fb832484208062
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/logging.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/loguru.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/loguru.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb8926bf81f6dc6332d15eddef53f8cc4b0655b7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/loguru.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/modules.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/modules.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..638a5f2b5c9dacf682fadfcfec4c1f4dfa7e3b04
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/modules.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/openai.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/openai.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e2ebcea7c3792f00cbe6a0ab4fe6dcf1cce9410
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/openai.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/openfeature.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/openfeature.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c9e0b9495306a6912669e94d165930d7eb798721
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/openfeature.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/pure_eval.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/pure_eval.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a618339f5af842329c58a2c817b64d3eb85746f2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/pure_eval.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/pymongo.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/pymongo.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b468b13d8f7a62478b9c693f570fc9225c5c2464
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/pymongo.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/pyramid.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/pyramid.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..96428df4f89af0b8be64686dfb1930831a7b1ea5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/pyramid.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/quart.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/quart.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5b2cf7a172bbb9889f5669a0360bf14e6b301d3b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/quart.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/ray.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/ray.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..009c3f0a5d4ec1dde91cf68cfa15ac4fdf979375
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/ray.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/rq.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/rq.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..63cf8a0fe7223f6da777604ef630dbe9d0360969
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/rq.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/rust_tracing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/rust_tracing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a3885e1c16ef880a6b268275d9a14cb9c08adad8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/rust_tracing.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/sanic.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/sanic.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..22586532a8840b869c394fc4af7d87384b51ba49
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/sanic.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/serverless.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/serverless.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c16e7fecc69850e4bf77dd58d1191bd634bfef0f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/serverless.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/socket.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/socket.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5b3fd524375c1aa840fa94432c5b7c57c4b6c8be
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/socket.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/sqlalchemy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/sqlalchemy.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c6652c5fdedf0ab501bea878cad85e7e532d6a93
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/sqlalchemy.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/starlette.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/starlette.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3297991a2a22917af6457e5d41c8f283aad6f7ff
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/starlette.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/starlite.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/starlite.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6efe51d3ce385b1fb54e7e45547ba601bc101507
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/starlite.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/statsig.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/statsig.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..be724edce38dc5dc0a4f8b7b91a14e8f30f18afa
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/statsig.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/stdlib.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/stdlib.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9a0bc0a00350e43823d10dda44e4b6681b540ac2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/stdlib.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/strawberry.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/strawberry.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3949e799654df8ab27204c45106ca0d90fd1c227
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/strawberry.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/sys_exit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/sys_exit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..550e5b75fa289afc08f8ca4d1990cf9008e84c74
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/sys_exit.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/threading.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/threading.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c4b72a02be763b37ad1b426ea3dace2bb9c2f5d6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/threading.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/tornado.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/tornado.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e9a5c9daf9a95905e9717fd698ce19bcdea1216a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/tornado.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/trytond.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/trytond.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..15ba2717d0603cf2555bc88f47508f70daa508ce
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/trytond.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/typer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/typer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6cb24fcd9bbc37332c3d155133fe84605b540a7e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/typer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/unleash.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/unleash.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eabd44731f21fb50ab14cba2a4a64ece49dce740
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/unleash.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/wsgi.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/wsgi.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..638a3853bfeb78d168499dd31ed1eaed64165d48
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/__pycache__/wsgi.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/_asgi_common.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/_asgi_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..c16bbbcfe8d75e26285813304a640bc8a786678d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/_asgi_common.py
@@ -0,0 +1,108 @@
+import urllib
+
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.integrations._wsgi_common import _filter_headers
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Dict
+    from typing import Optional
+    from typing import Union
+    from typing_extensions import Literal
+
+    from sentry_sdk.utils import AnnotatedValue
+
+
+def _get_headers(asgi_scope):
+    # type: (Any) -> Dict[str, str]
+    """
+    Extract headers from the ASGI scope, in the format that the Sentry protocol expects.
+    """
+    headers = {}  # type: Dict[str, str]
+    for raw_key, raw_value in asgi_scope["headers"]:
+        key = raw_key.decode("latin-1")
+        value = raw_value.decode("latin-1")
+        if key in headers:
+            headers[key] = headers[key] + ", " + value
+        else:
+            headers[key] = value
+
+    return headers
+
+
+def _get_url(asgi_scope, default_scheme, host):
+    # type: (Dict[str, Any], Literal["ws", "http"], Optional[Union[AnnotatedValue, str]]) -> str
+    """
+    Extract URL from the ASGI scope, without also including the querystring.
+    """
+    scheme = asgi_scope.get("scheme", default_scheme)
+
+    server = asgi_scope.get("server", None)
+    path = asgi_scope.get("root_path", "") + asgi_scope.get("path", "")
+
+    if host:
+        return "%s://%s%s" % (scheme, host, path)
+
+    if server is not None:
+        host, port = server
+        default_port = {"http": 80, "https": 443, "ws": 80, "wss": 443}.get(scheme)
+        if port != default_port:
+            return "%s://%s:%s%s" % (scheme, host, port, path)
+        return "%s://%s%s" % (scheme, host, path)
+    return path
+
+
+def _get_query(asgi_scope):
+    # type: (Any) -> Any
+    """
+    Extract querystring from the ASGI scope, in the format that the Sentry protocol expects.
+    """
+    qs = asgi_scope.get("query_string")
+    if not qs:
+        return None
+    return urllib.parse.unquote(qs.decode("latin-1"))
+
+
+def _get_ip(asgi_scope):
+    # type: (Any) -> str
+    """
+    Extract IP Address from the ASGI scope based on request headers with fallback to scope client.
+    """
+    headers = _get_headers(asgi_scope)
+    try:
+        return headers["x-forwarded-for"].split(",")[0].strip()
+    except (KeyError, IndexError):
+        pass
+
+    try:
+        return headers["x-real-ip"]
+    except KeyError:
+        pass
+
+    return asgi_scope.get("client")[0]
+
+
+def _get_request_data(asgi_scope):
+    # type: (Any) -> Dict[str, Any]
+    """
+    Returns data related to the HTTP request from the ASGI scope.
+    """
+    request_data = {}  # type: Dict[str, Any]
+    ty = asgi_scope["type"]
+    if ty in ("http", "websocket"):
+        request_data["method"] = asgi_scope.get("method")
+
+        request_data["headers"] = headers = _filter_headers(_get_headers(asgi_scope))
+        request_data["query_string"] = _get_query(asgi_scope)
+
+        request_data["url"] = _get_url(
+            asgi_scope, "http" if ty == "http" else "ws", headers.get("host")
+        )
+
+    client = asgi_scope.get("client")
+    if client and should_send_default_pii():
+        request_data["env"] = {"REMOTE_ADDR": _get_ip(asgi_scope)}
+
+    return request_data
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/_wsgi_common.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/_wsgi_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..48bc43288706404130a750c9f489d254022e3d8b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/_wsgi_common.py
@@ -0,0 +1,271 @@
+from contextlib import contextmanager
+import json
+from copy import deepcopy
+
+import sentry_sdk
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.utils import AnnotatedValue, logger
+
+try:
+    from django.http.request import RawPostDataException
+except ImportError:
+    RawPostDataException = None
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Dict
+    from typing import Iterator
+    from typing import Mapping
+    from typing import MutableMapping
+    from typing import Optional
+    from typing import Union
+    from sentry_sdk._types import Event, HttpStatusCodeRange
+
+
+SENSITIVE_ENV_KEYS = (
+    "REMOTE_ADDR",
+    "HTTP_X_FORWARDED_FOR",
+    "HTTP_SET_COOKIE",
+    "HTTP_COOKIE",
+    "HTTP_AUTHORIZATION",
+    "HTTP_X_API_KEY",
+    "HTTP_X_FORWARDED_FOR",
+    "HTTP_X_REAL_IP",
+)
+
+SENSITIVE_HEADERS = tuple(
+    x[len("HTTP_") :] for x in SENSITIVE_ENV_KEYS if x.startswith("HTTP_")
+)
+
+DEFAULT_HTTP_METHODS_TO_CAPTURE = (
+    "CONNECT",
+    "DELETE",
+    "GET",
+    # "HEAD",  # do not capture HEAD requests by default
+    # "OPTIONS",  # do not capture OPTIONS requests by default
+    "PATCH",
+    "POST",
+    "PUT",
+    "TRACE",
+)
+
+
+# This noop context manager can be replaced with "from contextlib import nullcontext" when we drop Python 3.6 support
+@contextmanager
+def nullcontext():
+    # type: () -> Iterator[None]
+    yield
+
+
+def request_body_within_bounds(client, content_length):
+    # type: (Optional[sentry_sdk.client.BaseClient], int) -> bool
+    if client is None:
+        return False
+
+    bodies = client.options["max_request_body_size"]
+    return not (
+        bodies == "never"
+        or (bodies == "small" and content_length > 10**3)
+        or (bodies == "medium" and content_length > 10**4)
+    )
+
+
+class RequestExtractor:
+    """
+    Base class for request extraction.
+    """
+
+    # It does not make sense to make this class an ABC because it is not used
+    # for typing, only so that child classes can inherit common methods from
+    # it. Only some child classes implement all methods that raise
+    # NotImplementedError in this class.
+
+    def __init__(self, request):
+        # type: (Any) -> None
+        self.request = request
+
+    def extract_into_event(self, event):
+        # type: (Event) -> None
+        client = sentry_sdk.get_client()
+        if not client.is_active():
+            return
+
+        data = None  # type: Optional[Union[AnnotatedValue, Dict[str, Any]]]
+
+        content_length = self.content_length()
+        request_info = event.get("request", {})
+
+        if should_send_default_pii():
+            request_info["cookies"] = dict(self.cookies())
+
+        if not request_body_within_bounds(client, content_length):
+            data = AnnotatedValue.removed_because_over_size_limit()
+        else:
+            # First read the raw body data
+            # It is important to read this first because if it is Django
+            # it will cache the body and then we can read the cached version
+            # again in parsed_body() (or json() or wherever).
+            raw_data = None
+            try:
+                raw_data = self.raw_data()
+            except (RawPostDataException, ValueError):
+                # If DjangoRestFramework is used it already read the body for us
+                # so reading it here will fail. We can ignore this.
+                pass
+
+            parsed_body = self.parsed_body()
+            if parsed_body is not None:
+                data = parsed_body
+            elif raw_data:
+                data = AnnotatedValue.removed_because_raw_data()
+            else:
+                data = None
+
+        if data is not None:
+            request_info["data"] = data
+
+        event["request"] = deepcopy(request_info)
+
+    def content_length(self):
+        # type: () -> int
+        try:
+            return int(self.env().get("CONTENT_LENGTH", 0))
+        except ValueError:
+            return 0
+
+    def cookies(self):
+        # type: () -> MutableMapping[str, Any]
+        raise NotImplementedError()
+
+    def raw_data(self):
+        # type: () -> Optional[Union[str, bytes]]
+        raise NotImplementedError()
+
+    def form(self):
+        # type: () -> Optional[Dict[str, Any]]
+        raise NotImplementedError()
+
+    def parsed_body(self):
+        # type: () -> Optional[Dict[str, Any]]
+        try:
+            form = self.form()
+        except Exception:
+            form = None
+        try:
+            files = self.files()
+        except Exception:
+            files = None
+
+        if form or files:
+            data = {}
+            if form:
+                data = dict(form.items())
+            if files:
+                for key in files.keys():
+                    data[key] = AnnotatedValue.removed_because_raw_data()
+
+            return data
+
+        return self.json()
+
+    def is_json(self):
+        # type: () -> bool
+        return _is_json_content_type(self.env().get("CONTENT_TYPE"))
+
+    def json(self):
+        # type: () -> Optional[Any]
+        try:
+            if not self.is_json():
+                return None
+
+            try:
+                raw_data = self.raw_data()
+            except (RawPostDataException, ValueError):
+                # The body might have already been read, in which case this will
+                # fail
+                raw_data = None
+
+            if raw_data is None:
+                return None
+
+            if isinstance(raw_data, str):
+                return json.loads(raw_data)
+            else:
+                return json.loads(raw_data.decode("utf-8"))
+        except ValueError:
+            pass
+
+        return None
+
+    def files(self):
+        # type: () -> Optional[Dict[str, Any]]
+        raise NotImplementedError()
+
+    def size_of_file(self, file):
+        # type: (Any) -> int
+        raise NotImplementedError()
+
+    def env(self):
+        # type: () -> Dict[str, Any]
+        raise NotImplementedError()
+
+
+def _is_json_content_type(ct):
+    # type: (Optional[str]) -> bool
+    mt = (ct or "").split(";", 1)[0]
+    return (
+        mt == "application/json"
+        or (mt.startswith("application/"))
+        and mt.endswith("+json")
+    )
+
+
+def _filter_headers(headers):
+    # type: (Mapping[str, str]) -> Mapping[str, Union[AnnotatedValue, str]]
+    if should_send_default_pii():
+        return headers
+
+    return {
+        k: (
+            v
+            if k.upper().replace("-", "_") not in SENSITIVE_HEADERS
+            else AnnotatedValue.removed_because_over_size_limit()
+        )
+        for k, v in headers.items()
+    }
+
+
+def _in_http_status_code_range(code, code_ranges):
+    # type: (object, list[HttpStatusCodeRange]) -> bool
+    for target in code_ranges:
+        if isinstance(target, int):
+            if code == target:
+                return True
+            continue
+
+        try:
+            if code in target:
+                return True
+        except TypeError:
+            logger.warning(
+                "failed_request_status_codes has to be a list of integers or containers"
+            )
+
+    return False
+
+
+class HttpCodeRangeContainer:
+    """
+    Wrapper to make it possible to use list[HttpStatusCodeRange] as a Container[int].
+    Used for backwards compatibility with the old `failed_request_status_codes` option.
+    """
+
+    def __init__(self, code_ranges):
+        # type: (list[HttpStatusCodeRange]) -> None
+        self._code_ranges = code_ranges
+
+    def __contains__(self, item):
+        # type: (object) -> bool
+        return _in_http_status_code_range(item, self._code_ranges)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/aiohttp.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/aiohttp.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad3202bf2c1a419c70de1849ecf71f19f860243f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/aiohttp.py
@@ -0,0 +1,357 @@
+import sys
+import weakref
+from functools import wraps
+
+import sentry_sdk
+from sentry_sdk.api import continue_trace
+from sentry_sdk.consts import OP, SPANSTATUS, SPANDATA
+from sentry_sdk.integrations import (
+    _DEFAULT_FAILED_REQUEST_STATUS_CODES,
+    _check_minimum_version,
+    Integration,
+    DidNotEnable,
+)
+from sentry_sdk.integrations.logging import ignore_logger
+from sentry_sdk.sessions import track_session
+from sentry_sdk.integrations._wsgi_common import (
+    _filter_headers,
+    request_body_within_bounds,
+)
+from sentry_sdk.tracing import (
+    BAGGAGE_HEADER_NAME,
+    SOURCE_FOR_STYLE,
+    TransactionSource,
+)
+from sentry_sdk.tracing_utils import should_propagate_trace
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    event_from_exception,
+    logger,
+    parse_url,
+    parse_version,
+    reraise,
+    transaction_from_function,
+    HAS_REAL_CONTEXTVARS,
+    CONTEXTVARS_ERROR_MESSAGE,
+    SENSITIVE_DATA_SUBSTITUTE,
+    AnnotatedValue,
+)
+
+try:
+    import asyncio
+
+    from aiohttp import __version__ as AIOHTTP_VERSION
+    from aiohttp import ClientSession, TraceConfig
+    from aiohttp.web import Application, HTTPException, UrlDispatcher
+except ImportError:
+    raise DidNotEnable("AIOHTTP not installed")
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from aiohttp.web_request import Request
+    from aiohttp.web_urldispatcher import UrlMappingMatchInfo
+    from aiohttp import TraceRequestStartParams, TraceRequestEndParams
+
+    from collections.abc import Set
+    from types import SimpleNamespace
+    from typing import Any
+    from typing import Optional
+    from typing import Tuple
+    from typing import Union
+
+    from sentry_sdk.utils import ExcInfo
+    from sentry_sdk._types import Event, EventProcessor
+
+
+TRANSACTION_STYLE_VALUES = ("handler_name", "method_and_path_pattern")
+
+
+class AioHttpIntegration(Integration):
+    identifier = "aiohttp"
+    origin = f"auto.http.{identifier}"
+
+    def __init__(
+        self,
+        transaction_style="handler_name",  # type: str
+        *,
+        failed_request_status_codes=_DEFAULT_FAILED_REQUEST_STATUS_CODES,  # type: Set[int]
+    ):
+        # type: (...) -> None
+        if transaction_style not in TRANSACTION_STYLE_VALUES:
+            raise ValueError(
+                "Invalid value for transaction_style: %s (must be in %s)"
+                % (transaction_style, TRANSACTION_STYLE_VALUES)
+            )
+        self.transaction_style = transaction_style
+        self._failed_request_status_codes = failed_request_status_codes
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+
+        version = parse_version(AIOHTTP_VERSION)
+        _check_minimum_version(AioHttpIntegration, version)
+
+        if not HAS_REAL_CONTEXTVARS:
+            # We better have contextvars or we're going to leak state between
+            # requests.
+            raise DidNotEnable(
+                "The aiohttp integration for Sentry requires Python 3.7+ "
+                " or aiocontextvars package." + CONTEXTVARS_ERROR_MESSAGE
+            )
+
+        ignore_logger("aiohttp.server")
+
+        old_handle = Application._handle
+
+        async def sentry_app_handle(self, request, *args, **kwargs):
+            # type: (Any, Request, *Any, **Any) -> Any
+            integration = sentry_sdk.get_client().get_integration(AioHttpIntegration)
+            if integration is None:
+                return await old_handle(self, request, *args, **kwargs)
+
+            weak_request = weakref.ref(request)
+
+            with sentry_sdk.isolation_scope() as scope:
+                with track_session(scope, session_mode="request"):
+                    # Scope data will not leak between requests because aiohttp
+                    # create a task to wrap each request.
+                    scope.generate_propagation_context()
+                    scope.clear_breadcrumbs()
+                    scope.add_event_processor(_make_request_processor(weak_request))
+
+                    headers = dict(request.headers)
+                    transaction = continue_trace(
+                        headers,
+                        op=OP.HTTP_SERVER,
+                        # If this transaction name makes it to the UI, AIOHTTP's
+                        # URL resolver did not find a route or died trying.
+                        name="generic AIOHTTP request",
+                        source=TransactionSource.ROUTE,
+                        origin=AioHttpIntegration.origin,
+                    )
+                    with sentry_sdk.start_transaction(
+                        transaction,
+                        custom_sampling_context={"aiohttp_request": request},
+                    ):
+                        try:
+                            response = await old_handle(self, request)
+                        except HTTPException as e:
+                            transaction.set_http_status(e.status_code)
+
+                            if (
+                                e.status_code
+                                in integration._failed_request_status_codes
+                            ):
+                                _capture_exception()
+
+                            raise
+                        except (asyncio.CancelledError, ConnectionResetError):
+                            transaction.set_status(SPANSTATUS.CANCELLED)
+                            raise
+                        except Exception:
+                            # This will probably map to a 500 but seems like we
+                            # have no way to tell. Do not set span status.
+                            reraise(*_capture_exception())
+
+                        try:
+                            # A valid response handler will return a valid response with a status. But, if the handler
+                            # returns an invalid response (e.g. None), the line below will raise an AttributeError.
+                            # Even though this is likely invalid, we need to handle this case to ensure we don't break
+                            # the application.
+                            response_status = response.status
+                        except AttributeError:
+                            pass
+                        else:
+                            transaction.set_http_status(response_status)
+
+                        return response
+
+        Application._handle = sentry_app_handle
+
+        old_urldispatcher_resolve = UrlDispatcher.resolve
+
+        @wraps(old_urldispatcher_resolve)
+        async def sentry_urldispatcher_resolve(self, request):
+            # type: (UrlDispatcher, Request) -> UrlMappingMatchInfo
+            rv = await old_urldispatcher_resolve(self, request)
+
+            integration = sentry_sdk.get_client().get_integration(AioHttpIntegration)
+            if integration is None:
+                return rv
+
+            name = None
+
+            try:
+                if integration.transaction_style == "handler_name":
+                    name = transaction_from_function(rv.handler)
+                elif integration.transaction_style == "method_and_path_pattern":
+                    route_info = rv.get_info()
+                    pattern = route_info.get("path") or route_info.get("formatter")
+                    name = "{} {}".format(request.method, pattern)
+            except Exception:
+                pass
+
+            if name is not None:
+                sentry_sdk.get_current_scope().set_transaction_name(
+                    name,
+                    source=SOURCE_FOR_STYLE[integration.transaction_style],
+                )
+
+            return rv
+
+        UrlDispatcher.resolve = sentry_urldispatcher_resolve
+
+        old_client_session_init = ClientSession.__init__
+
+        @ensure_integration_enabled(AioHttpIntegration, old_client_session_init)
+        def init(*args, **kwargs):
+            # type: (Any, Any) -> None
+            client_trace_configs = list(kwargs.get("trace_configs") or ())
+            trace_config = create_trace_config()
+            client_trace_configs.append(trace_config)
+
+            kwargs["trace_configs"] = client_trace_configs
+            return old_client_session_init(*args, **kwargs)
+
+        ClientSession.__init__ = init
+
+
+def create_trace_config():
+    # type: () -> TraceConfig
+
+    async def on_request_start(session, trace_config_ctx, params):
+        # type: (ClientSession, SimpleNamespace, TraceRequestStartParams) -> None
+        if sentry_sdk.get_client().get_integration(AioHttpIntegration) is None:
+            return
+
+        method = params.method.upper()
+
+        parsed_url = None
+        with capture_internal_exceptions():
+            parsed_url = parse_url(str(params.url), sanitize=False)
+
+        span = sentry_sdk.start_span(
+            op=OP.HTTP_CLIENT,
+            name="%s %s"
+            % (method, parsed_url.url if parsed_url else SENSITIVE_DATA_SUBSTITUTE),
+            origin=AioHttpIntegration.origin,
+        )
+        span.set_data(SPANDATA.HTTP_METHOD, method)
+        if parsed_url is not None:
+            span.set_data("url", parsed_url.url)
+            span.set_data(SPANDATA.HTTP_QUERY, parsed_url.query)
+            span.set_data(SPANDATA.HTTP_FRAGMENT, parsed_url.fragment)
+
+        client = sentry_sdk.get_client()
+
+        if should_propagate_trace(client, str(params.url)):
+            for (
+                key,
+                value,
+            ) in sentry_sdk.get_current_scope().iter_trace_propagation_headers(
+                span=span
+            ):
+                logger.debug(
+                    "[Tracing] Adding `{key}` header {value} to outgoing request to {url}.".format(
+                        key=key, value=value, url=params.url
+                    )
+                )
+                if key == BAGGAGE_HEADER_NAME and params.headers.get(
+                    BAGGAGE_HEADER_NAME
+                ):
+                    # do not overwrite any existing baggage, just append to it
+                    params.headers[key] += "," + value
+                else:
+                    params.headers[key] = value
+
+        trace_config_ctx.span = span
+
+    async def on_request_end(session, trace_config_ctx, params):
+        # type: (ClientSession, SimpleNamespace, TraceRequestEndParams) -> None
+        if trace_config_ctx.span is None:
+            return
+
+        span = trace_config_ctx.span
+        span.set_http_status(int(params.response.status))
+        span.set_data("reason", params.response.reason)
+        span.finish()
+
+    trace_config = TraceConfig()
+
+    trace_config.on_request_start.append(on_request_start)
+    trace_config.on_request_end.append(on_request_end)
+
+    return trace_config
+
+
+def _make_request_processor(weak_request):
+    # type: (weakref.ReferenceType[Request]) -> EventProcessor
+    def aiohttp_processor(
+        event,  # type: Event
+        hint,  # type: dict[str, Tuple[type, BaseException, Any]]
+    ):
+        # type: (...) -> Event
+        request = weak_request()
+        if request is None:
+            return event
+
+        with capture_internal_exceptions():
+            request_info = event.setdefault("request", {})
+
+            request_info["url"] = "%s://%s%s" % (
+                request.scheme,
+                request.host,
+                request.path,
+            )
+
+            request_info["query_string"] = request.query_string
+            request_info["method"] = request.method
+            request_info["env"] = {"REMOTE_ADDR": request.remote}
+            request_info["headers"] = _filter_headers(dict(request.headers))
+
+            # Just attach raw data here if it is within bounds, if available.
+            # Unfortunately there's no way to get structured data from aiohttp
+            # without awaiting on some coroutine.
+            request_info["data"] = get_aiohttp_request_data(request)
+
+        return event
+
+    return aiohttp_processor
+
+
+def _capture_exception():
+    # type: () -> ExcInfo
+    exc_info = sys.exc_info()
+    event, hint = event_from_exception(
+        exc_info,
+        client_options=sentry_sdk.get_client().options,
+        mechanism={"type": "aiohttp", "handled": False},
+    )
+    sentry_sdk.capture_event(event, hint=hint)
+    return exc_info
+
+
+BODY_NOT_READ_MESSAGE = "[Can't show request body due to implementation details.]"
+
+
+def get_aiohttp_request_data(request):
+    # type: (Request) -> Union[Optional[str], AnnotatedValue]
+    bytes_body = request._read_bytes
+
+    if bytes_body is not None:
+        # we have body to show
+        if not request_body_within_bounds(sentry_sdk.get_client(), len(bytes_body)):
+            return AnnotatedValue.removed_because_over_size_limit()
+
+        encoding = request.charset or "utf-8"
+        return bytes_body.decode(encoding, "replace")
+
+    if request.can_read_body:
+        # body exists but we can't show it
+        return BODY_NOT_READ_MESSAGE
+
+    # request has no body
+    return None
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/anthropic.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/anthropic.py
new file mode 100644
index 0000000000000000000000000000000000000000..05d45ef62f19774de6caf9f4e35cd04372b6b43c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/anthropic.py
@@ -0,0 +1,360 @@
+from functools import wraps
+import json
+from typing import TYPE_CHECKING
+
+import sentry_sdk
+from sentry_sdk.ai.monitoring import record_token_usage
+from sentry_sdk.ai.utils import set_data_normalized
+from sentry_sdk.consts import OP, SPANDATA
+from sentry_sdk.integrations import _check_minimum_version, DidNotEnable, Integration
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    event_from_exception,
+    package_version,
+    safe_serialize,
+)
+
+try:
+    try:
+        from anthropic import NOT_GIVEN
+    except ImportError:
+        NOT_GIVEN = None
+
+    from anthropic.resources import AsyncMessages, Messages
+
+    if TYPE_CHECKING:
+        from anthropic.types import MessageStreamEvent
+except ImportError:
+    raise DidNotEnable("Anthropic not installed")
+
+if TYPE_CHECKING:
+    from typing import Any, AsyncIterator, Iterator
+    from sentry_sdk.tracing import Span
+
+
+class AnthropicIntegration(Integration):
+    identifier = "anthropic"
+    origin = f"auto.ai.{identifier}"
+
+    def __init__(self, include_prompts=True):
+        # type: (AnthropicIntegration, bool) -> None
+        self.include_prompts = include_prompts
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        version = package_version("anthropic")
+        _check_minimum_version(AnthropicIntegration, version)
+
+        Messages.create = _wrap_message_create(Messages.create)
+        AsyncMessages.create = _wrap_message_create_async(AsyncMessages.create)
+
+
+def _capture_exception(exc):
+    # type: (Any) -> None
+    event, hint = event_from_exception(
+        exc,
+        client_options=sentry_sdk.get_client().options,
+        mechanism={"type": "anthropic", "handled": False},
+    )
+    sentry_sdk.capture_event(event, hint=hint)
+
+
+def _get_token_usage(result):
+    # type: (Messages) -> tuple[int, int]
+    """
+    Get token usage from the Anthropic response.
+    """
+    input_tokens = 0
+    output_tokens = 0
+    if hasattr(result, "usage"):
+        usage = result.usage
+        if hasattr(usage, "input_tokens") and isinstance(usage.input_tokens, int):
+            input_tokens = usage.input_tokens
+        if hasattr(usage, "output_tokens") and isinstance(usage.output_tokens, int):
+            output_tokens = usage.output_tokens
+
+    return input_tokens, output_tokens
+
+
+def _collect_ai_data(event, model, input_tokens, output_tokens, content_blocks):
+    # type: (MessageStreamEvent, str | None, int, int, list[str]) -> tuple[str | None, int, int, list[str]]
+    """
+    Collect model information, token usage, and collect content blocks from the AI streaming response.
+    """
+    with capture_internal_exceptions():
+        if hasattr(event, "type"):
+            if event.type == "message_start":
+                usage = event.message.usage
+                input_tokens += usage.input_tokens
+                output_tokens += usage.output_tokens
+                model = event.message.model or model
+            elif event.type == "content_block_start":
+                pass
+            elif event.type == "content_block_delta":
+                if hasattr(event.delta, "text"):
+                    content_blocks.append(event.delta.text)
+                elif hasattr(event.delta, "partial_json"):
+                    content_blocks.append(event.delta.partial_json)
+            elif event.type == "content_block_stop":
+                pass
+            elif event.type == "message_delta":
+                output_tokens += event.usage.output_tokens
+
+    return model, input_tokens, output_tokens, content_blocks
+
+
+def _set_input_data(span, kwargs, integration):
+    # type: (Span, dict[str, Any], AnthropicIntegration) -> None
+    """
+    Set input data for the span based on the provided keyword arguments for the anthropic message creation.
+    """
+    messages = kwargs.get("messages")
+    if (
+        messages is not None
+        and len(messages) > 0
+        and should_send_default_pii()
+        and integration.include_prompts
+    ):
+        set_data_normalized(
+            span, SPANDATA.GEN_AI_REQUEST_MESSAGES, safe_serialize(messages)
+        )
+
+    set_data_normalized(
+        span, SPANDATA.GEN_AI_RESPONSE_STREAMING, kwargs.get("stream", False)
+    )
+
+    kwargs_keys_to_attributes = {
+        "max_tokens": SPANDATA.GEN_AI_REQUEST_MAX_TOKENS,
+        "model": SPANDATA.GEN_AI_REQUEST_MODEL,
+        "temperature": SPANDATA.GEN_AI_REQUEST_TEMPERATURE,
+        "top_k": SPANDATA.GEN_AI_REQUEST_TOP_K,
+        "top_p": SPANDATA.GEN_AI_REQUEST_TOP_P,
+    }
+    for key, attribute in kwargs_keys_to_attributes.items():
+        value = kwargs.get(key)
+        if value is not NOT_GIVEN and value is not None:
+            set_data_normalized(span, attribute, value)
+
+    # Input attributes: Tools
+    tools = kwargs.get("tools")
+    if tools is not NOT_GIVEN and tools is not None and len(tools) > 0:
+        set_data_normalized(
+            span, SPANDATA.GEN_AI_REQUEST_AVAILABLE_TOOLS, safe_serialize(tools)
+        )
+
+
+def _set_output_data(
+    span,
+    integration,
+    model,
+    input_tokens,
+    output_tokens,
+    content_blocks,
+    finish_span=False,
+):
+    # type: (Span, AnthropicIntegration, str | None, int | None, int | None, list[Any], bool) -> None
+    """
+    Set output data for the span based on the AI response."""
+    span.set_data(SPANDATA.GEN_AI_RESPONSE_MODEL, model)
+    if should_send_default_pii() and integration.include_prompts:
+        set_data_normalized(
+            span,
+            SPANDATA.GEN_AI_RESPONSE_TEXT,
+            json.dumps(content_blocks),
+            unpack=False,
+        )
+
+    record_token_usage(
+        span,
+        input_tokens=input_tokens,
+        output_tokens=output_tokens,
+    )
+
+    # TODO: GEN_AI_RESPONSE_TOOL_CALLS ?
+
+    if finish_span:
+        span.__exit__(None, None, None)
+
+
+def _sentry_patched_create_common(f, *args, **kwargs):
+    # type: (Any, *Any, **Any) -> Any
+    integration = kwargs.pop("integration")
+    if integration is None:
+        return f(*args, **kwargs)
+
+    if "messages" not in kwargs:
+        return f(*args, **kwargs)
+
+    try:
+        iter(kwargs["messages"])
+    except TypeError:
+        return f(*args, **kwargs)
+
+    model = kwargs.get("model", "")
+
+    span = sentry_sdk.start_span(
+        op=OP.GEN_AI_CHAT,
+        name=f"chat {model}".strip(),
+        origin=AnthropicIntegration.origin,
+    )
+    span.__enter__()
+
+    _set_input_data(span, kwargs, integration)
+
+    result = yield f, args, kwargs
+
+    with capture_internal_exceptions():
+        if hasattr(result, "content"):
+            input_tokens, output_tokens = _get_token_usage(result)
+
+            content_blocks = []
+            for content_block in result.content:
+                if hasattr(content_block, "to_dict"):
+                    content_blocks.append(content_block.to_dict())
+                elif hasattr(content_block, "model_dump"):
+                    content_blocks.append(content_block.model_dump())
+                elif hasattr(content_block, "text"):
+                    content_blocks.append({"type": "text", "text": content_block.text})
+
+            _set_output_data(
+                span=span,
+                integration=integration,
+                model=getattr(result, "model", None),
+                input_tokens=input_tokens,
+                output_tokens=output_tokens,
+                content_blocks=content_blocks,
+                finish_span=True,
+            )
+
+        # Streaming response
+        elif hasattr(result, "_iterator"):
+            old_iterator = result._iterator
+
+            def new_iterator():
+                # type: () -> Iterator[MessageStreamEvent]
+                model = None
+                input_tokens = 0
+                output_tokens = 0
+                content_blocks = []  # type: list[str]
+
+                for event in old_iterator:
+                    model, input_tokens, output_tokens, content_blocks = (
+                        _collect_ai_data(
+                            event, model, input_tokens, output_tokens, content_blocks
+                        )
+                    )
+                    yield event
+
+                _set_output_data(
+                    span=span,
+                    integration=integration,
+                    model=model,
+                    input_tokens=input_tokens,
+                    output_tokens=output_tokens,
+                    content_blocks=[{"text": "".join(content_blocks), "type": "text"}],
+                    finish_span=True,
+                )
+
+            async def new_iterator_async():
+                # type: () -> AsyncIterator[MessageStreamEvent]
+                model = None
+                input_tokens = 0
+                output_tokens = 0
+                content_blocks = []  # type: list[str]
+
+                async for event in old_iterator:
+                    model, input_tokens, output_tokens, content_blocks = (
+                        _collect_ai_data(
+                            event, model, input_tokens, output_tokens, content_blocks
+                        )
+                    )
+                    yield event
+
+                _set_output_data(
+                    span=span,
+                    integration=integration,
+                    model=model,
+                    input_tokens=input_tokens,
+                    output_tokens=output_tokens,
+                    content_blocks=[{"text": "".join(content_blocks), "type": "text"}],
+                    finish_span=True,
+                )
+
+            if str(type(result._iterator)) == "":
+                result._iterator = new_iterator_async()
+            else:
+                result._iterator = new_iterator()
+
+        else:
+            span.set_data("unknown_response", True)
+            span.__exit__(None, None, None)
+
+    return result
+
+
+def _wrap_message_create(f):
+    # type: (Any) -> Any
+    def _execute_sync(f, *args, **kwargs):
+        # type: (Any, *Any, **Any) -> Any
+        gen = _sentry_patched_create_common(f, *args, **kwargs)
+
+        try:
+            f, args, kwargs = next(gen)
+        except StopIteration as e:
+            return e.value
+
+        try:
+            try:
+                result = f(*args, **kwargs)
+            except Exception as exc:
+                _capture_exception(exc)
+                raise exc from None
+
+            return gen.send(result)
+        except StopIteration as e:
+            return e.value
+
+    @wraps(f)
+    def _sentry_patched_create_sync(*args, **kwargs):
+        # type: (*Any, **Any) -> Any
+        integration = sentry_sdk.get_client().get_integration(AnthropicIntegration)
+        kwargs["integration"] = integration
+
+        return _execute_sync(f, *args, **kwargs)
+
+    return _sentry_patched_create_sync
+
+
+def _wrap_message_create_async(f):
+    # type: (Any) -> Any
+    async def _execute_async(f, *args, **kwargs):
+        # type: (Any, *Any, **Any) -> Any
+        gen = _sentry_patched_create_common(f, *args, **kwargs)
+
+        try:
+            f, args, kwargs = next(gen)
+        except StopIteration as e:
+            return await e.value
+
+        try:
+            try:
+                result = await f(*args, **kwargs)
+            except Exception as exc:
+                _capture_exception(exc)
+                raise exc from None
+
+            return gen.send(result)
+        except StopIteration as e:
+            return e.value
+
+    @wraps(f)
+    async def _sentry_patched_create_async(*args, **kwargs):
+        # type: (*Any, **Any) -> Any
+        integration = sentry_sdk.get_client().get_integration(AnthropicIntegration)
+        kwargs["integration"] = integration
+
+        return await _execute_async(f, *args, **kwargs)
+
+    return _sentry_patched_create_async
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/argv.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/argv.py
new file mode 100644
index 0000000000000000000000000000000000000000..315feefb4abbf00e62e2e77212f8f8f37c952792
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/argv.py
@@ -0,0 +1,31 @@
+import sys
+
+import sentry_sdk
+from sentry_sdk.integrations import Integration
+from sentry_sdk.scope import add_global_event_processor
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Optional
+
+    from sentry_sdk._types import Event, Hint
+
+
+class ArgvIntegration(Integration):
+    identifier = "argv"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        @add_global_event_processor
+        def processor(event, hint):
+            # type: (Event, Optional[Hint]) -> Optional[Event]
+            if sentry_sdk.get_client().get_integration(ArgvIntegration) is not None:
+                extra = event.setdefault("extra", {})
+                # If some event processor decided to set extra to e.g. an
+                # `int`, don't crash. Not here.
+                if isinstance(extra, dict):
+                    extra["sys.argv"] = sys.argv
+
+            return event
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/ariadne.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/ariadne.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a95bc014504744e3700786455839e595f9fd715
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/ariadne.py
@@ -0,0 +1,161 @@
+from importlib import import_module
+
+import sentry_sdk
+from sentry_sdk import get_client, capture_event
+from sentry_sdk.integrations import _check_minimum_version, DidNotEnable, Integration
+from sentry_sdk.integrations.logging import ignore_logger
+from sentry_sdk.integrations._wsgi_common import request_body_within_bounds
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    event_from_exception,
+    package_version,
+)
+
+try:
+    # importing like this is necessary due to name shadowing in ariadne
+    # (ariadne.graphql is also a function)
+    ariadne_graphql = import_module("ariadne.graphql")
+except ImportError:
+    raise DidNotEnable("ariadne is not installed")
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Dict, List, Optional
+    from ariadne.types import GraphQLError, GraphQLResult, GraphQLSchema, QueryParser  # type: ignore
+    from graphql.language.ast import DocumentNode
+    from sentry_sdk._types import Event, EventProcessor
+
+
+class AriadneIntegration(Integration):
+    identifier = "ariadne"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        version = package_version("ariadne")
+        _check_minimum_version(AriadneIntegration, version)
+
+        ignore_logger("ariadne")
+
+        _patch_graphql()
+
+
+def _patch_graphql():
+    # type: () -> None
+    old_parse_query = ariadne_graphql.parse_query
+    old_handle_errors = ariadne_graphql.handle_graphql_errors
+    old_handle_query_result = ariadne_graphql.handle_query_result
+
+    @ensure_integration_enabled(AriadneIntegration, old_parse_query)
+    def _sentry_patched_parse_query(context_value, query_parser, data):
+        # type: (Optional[Any], Optional[QueryParser], Any) -> DocumentNode
+        event_processor = _make_request_event_processor(data)
+        sentry_sdk.get_isolation_scope().add_event_processor(event_processor)
+
+        result = old_parse_query(context_value, query_parser, data)
+        return result
+
+    @ensure_integration_enabled(AriadneIntegration, old_handle_errors)
+    def _sentry_patched_handle_graphql_errors(errors, *args, **kwargs):
+        # type: (List[GraphQLError], Any, Any) -> GraphQLResult
+        result = old_handle_errors(errors, *args, **kwargs)
+
+        event_processor = _make_response_event_processor(result[1])
+        sentry_sdk.get_isolation_scope().add_event_processor(event_processor)
+
+        client = get_client()
+        if client.is_active():
+            with capture_internal_exceptions():
+                for error in errors:
+                    event, hint = event_from_exception(
+                        error,
+                        client_options=client.options,
+                        mechanism={
+                            "type": AriadneIntegration.identifier,
+                            "handled": False,
+                        },
+                    )
+                    capture_event(event, hint=hint)
+
+        return result
+
+    @ensure_integration_enabled(AriadneIntegration, old_handle_query_result)
+    def _sentry_patched_handle_query_result(result, *args, **kwargs):
+        # type: (Any, Any, Any) -> GraphQLResult
+        query_result = old_handle_query_result(result, *args, **kwargs)
+
+        event_processor = _make_response_event_processor(query_result[1])
+        sentry_sdk.get_isolation_scope().add_event_processor(event_processor)
+
+        client = get_client()
+        if client.is_active():
+            with capture_internal_exceptions():
+                for error in result.errors or []:
+                    event, hint = event_from_exception(
+                        error,
+                        client_options=client.options,
+                        mechanism={
+                            "type": AriadneIntegration.identifier,
+                            "handled": False,
+                        },
+                    )
+                    capture_event(event, hint=hint)
+
+        return query_result
+
+    ariadne_graphql.parse_query = _sentry_patched_parse_query  # type: ignore
+    ariadne_graphql.handle_graphql_errors = _sentry_patched_handle_graphql_errors  # type: ignore
+    ariadne_graphql.handle_query_result = _sentry_patched_handle_query_result  # type: ignore
+
+
+def _make_request_event_processor(data):
+    # type: (GraphQLSchema) -> EventProcessor
+    """Add request data and api_target to events."""
+
+    def inner(event, hint):
+        # type: (Event, dict[str, Any]) -> Event
+        if not isinstance(data, dict):
+            return event
+
+        with capture_internal_exceptions():
+            try:
+                content_length = int(
+                    (data.get("headers") or {}).get("Content-Length", 0)
+                )
+            except (TypeError, ValueError):
+                return event
+
+            if should_send_default_pii() and request_body_within_bounds(
+                get_client(), content_length
+            ):
+                request_info = event.setdefault("request", {})
+                request_info["api_target"] = "graphql"
+                request_info["data"] = data
+
+            elif event.get("request", {}).get("data"):
+                del event["request"]["data"]
+
+        return event
+
+    return inner
+
+
+def _make_response_event_processor(response):
+    # type: (Dict[str, Any]) -> EventProcessor
+    """Add response data to the event's response context."""
+
+    def inner(event, hint):
+        # type: (Event, dict[str, Any]) -> Event
+        with capture_internal_exceptions():
+            if should_send_default_pii() and response.get("errors"):
+                contexts = event.setdefault("contexts", {})
+                contexts["response"] = {
+                    "data": response,
+                }
+
+        return event
+
+    return inner
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/arq.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/arq.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0b3d3f03e01a45ce5ad6d46682779b32854f3d7
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/arq.py
@@ -0,0 +1,247 @@
+import sys
+
+import sentry_sdk
+from sentry_sdk.consts import OP, SPANSTATUS
+from sentry_sdk.integrations import _check_minimum_version, DidNotEnable, Integration
+from sentry_sdk.integrations.logging import ignore_logger
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.tracing import Transaction, TransactionSource
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    event_from_exception,
+    SENSITIVE_DATA_SUBSTITUTE,
+    parse_version,
+    reraise,
+)
+
+try:
+    import arq.worker
+    from arq.version import VERSION as ARQ_VERSION
+    from arq.connections import ArqRedis
+    from arq.worker import JobExecutionFailed, Retry, RetryJob, Worker
+except ImportError:
+    raise DidNotEnable("Arq is not installed")
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Dict, Optional, Union
+
+    from sentry_sdk._types import EventProcessor, Event, ExcInfo, Hint
+
+    from arq.cron import CronJob
+    from arq.jobs import Job
+    from arq.typing import WorkerCoroutine
+    from arq.worker import Function
+
+ARQ_CONTROL_FLOW_EXCEPTIONS = (JobExecutionFailed, Retry, RetryJob)
+
+
+class ArqIntegration(Integration):
+    identifier = "arq"
+    origin = f"auto.queue.{identifier}"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+
+        try:
+            if isinstance(ARQ_VERSION, str):
+                version = parse_version(ARQ_VERSION)
+            else:
+                version = ARQ_VERSION.version[:2]
+
+        except (TypeError, ValueError):
+            version = None
+
+        _check_minimum_version(ArqIntegration, version)
+
+        patch_enqueue_job()
+        patch_run_job()
+        patch_create_worker()
+
+        ignore_logger("arq.worker")
+
+
+def patch_enqueue_job():
+    # type: () -> None
+    old_enqueue_job = ArqRedis.enqueue_job
+    original_kwdefaults = old_enqueue_job.__kwdefaults__
+
+    async def _sentry_enqueue_job(self, function, *args, **kwargs):
+        # type: (ArqRedis, str, *Any, **Any) -> Optional[Job]
+        integration = sentry_sdk.get_client().get_integration(ArqIntegration)
+        if integration is None:
+            return await old_enqueue_job(self, function, *args, **kwargs)
+
+        with sentry_sdk.start_span(
+            op=OP.QUEUE_SUBMIT_ARQ, name=function, origin=ArqIntegration.origin
+        ):
+            return await old_enqueue_job(self, function, *args, **kwargs)
+
+    _sentry_enqueue_job.__kwdefaults__ = original_kwdefaults
+    ArqRedis.enqueue_job = _sentry_enqueue_job
+
+
+def patch_run_job():
+    # type: () -> None
+    old_run_job = Worker.run_job
+
+    async def _sentry_run_job(self, job_id, score):
+        # type: (Worker, str, int) -> None
+        integration = sentry_sdk.get_client().get_integration(ArqIntegration)
+        if integration is None:
+            return await old_run_job(self, job_id, score)
+
+        with sentry_sdk.isolation_scope() as scope:
+            scope._name = "arq"
+            scope.clear_breadcrumbs()
+
+            transaction = Transaction(
+                name="unknown arq task",
+                status="ok",
+                op=OP.QUEUE_TASK_ARQ,
+                source=TransactionSource.TASK,
+                origin=ArqIntegration.origin,
+            )
+
+            with sentry_sdk.start_transaction(transaction):
+                return await old_run_job(self, job_id, score)
+
+    Worker.run_job = _sentry_run_job
+
+
+def _capture_exception(exc_info):
+    # type: (ExcInfo) -> None
+    scope = sentry_sdk.get_current_scope()
+
+    if scope.transaction is not None:
+        if exc_info[0] in ARQ_CONTROL_FLOW_EXCEPTIONS:
+            scope.transaction.set_status(SPANSTATUS.ABORTED)
+            return
+
+        scope.transaction.set_status(SPANSTATUS.INTERNAL_ERROR)
+
+    event, hint = event_from_exception(
+        exc_info,
+        client_options=sentry_sdk.get_client().options,
+        mechanism={"type": ArqIntegration.identifier, "handled": False},
+    )
+    sentry_sdk.capture_event(event, hint=hint)
+
+
+def _make_event_processor(ctx, *args, **kwargs):
+    # type: (Dict[Any, Any], *Any, **Any) -> EventProcessor
+    def event_processor(event, hint):
+        # type: (Event, Hint) -> Optional[Event]
+
+        with capture_internal_exceptions():
+            scope = sentry_sdk.get_current_scope()
+            if scope.transaction is not None:
+                scope.transaction.name = ctx["job_name"]
+                event["transaction"] = ctx["job_name"]
+
+            tags = event.setdefault("tags", {})
+            tags["arq_task_id"] = ctx["job_id"]
+            tags["arq_task_retry"] = ctx["job_try"] > 1
+            extra = event.setdefault("extra", {})
+            extra["arq-job"] = {
+                "task": ctx["job_name"],
+                "args": (
+                    args if should_send_default_pii() else SENSITIVE_DATA_SUBSTITUTE
+                ),
+                "kwargs": (
+                    kwargs if should_send_default_pii() else SENSITIVE_DATA_SUBSTITUTE
+                ),
+                "retry": ctx["job_try"],
+            }
+
+        return event
+
+    return event_processor
+
+
+def _wrap_coroutine(name, coroutine):
+    # type: (str, WorkerCoroutine) -> WorkerCoroutine
+
+    async def _sentry_coroutine(ctx, *args, **kwargs):
+        # type: (Dict[Any, Any], *Any, **Any) -> Any
+        integration = sentry_sdk.get_client().get_integration(ArqIntegration)
+        if integration is None:
+            return await coroutine(ctx, *args, **kwargs)
+
+        sentry_sdk.get_isolation_scope().add_event_processor(
+            _make_event_processor({**ctx, "job_name": name}, *args, **kwargs)
+        )
+
+        try:
+            result = await coroutine(ctx, *args, **kwargs)
+        except Exception:
+            exc_info = sys.exc_info()
+            _capture_exception(exc_info)
+            reraise(*exc_info)
+
+        return result
+
+    return _sentry_coroutine
+
+
+def patch_create_worker():
+    # type: () -> None
+    old_create_worker = arq.worker.create_worker
+
+    @ensure_integration_enabled(ArqIntegration, old_create_worker)
+    def _sentry_create_worker(*args, **kwargs):
+        # type: (*Any, **Any) -> Worker
+        settings_cls = args[0]
+
+        if isinstance(settings_cls, dict):
+            if "functions" in settings_cls:
+                settings_cls["functions"] = [
+                    _get_arq_function(func)
+                    for func in settings_cls.get("functions", [])
+                ]
+            if "cron_jobs" in settings_cls:
+                settings_cls["cron_jobs"] = [
+                    _get_arq_cron_job(cron_job)
+                    for cron_job in settings_cls.get("cron_jobs", [])
+                ]
+
+        if hasattr(settings_cls, "functions"):
+            settings_cls.functions = [
+                _get_arq_function(func) for func in settings_cls.functions
+            ]
+        if hasattr(settings_cls, "cron_jobs"):
+            settings_cls.cron_jobs = [
+                _get_arq_cron_job(cron_job)
+                for cron_job in (settings_cls.cron_jobs or [])
+            ]
+
+        if "functions" in kwargs:
+            kwargs["functions"] = [
+                _get_arq_function(func) for func in kwargs.get("functions", [])
+            ]
+        if "cron_jobs" in kwargs:
+            kwargs["cron_jobs"] = [
+                _get_arq_cron_job(cron_job) for cron_job in kwargs.get("cron_jobs", [])
+            ]
+
+        return old_create_worker(*args, **kwargs)
+
+    arq.worker.create_worker = _sentry_create_worker
+
+
+def _get_arq_function(func):
+    # type: (Union[str, Function, WorkerCoroutine]) -> Function
+    arq_func = arq.worker.func(func)
+    arq_func.coroutine = _wrap_coroutine(arq_func.name, arq_func.coroutine)
+
+    return arq_func
+
+
+def _get_arq_cron_job(cron_job):
+    # type: (CronJob) -> CronJob
+    cron_job.coroutine = _wrap_coroutine(cron_job.name, cron_job.coroutine)
+
+    return cron_job
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/asgi.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/asgi.py
new file mode 100644
index 0000000000000000000000000000000000000000..dde8128a337f910dd2beb27bf438abec88d4287e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/asgi.py
@@ -0,0 +1,340 @@
+"""
+An ASGI middleware.
+
+Based on Tom Christie's `sentry-asgi `.
+"""
+
+import asyncio
+import inspect
+from copy import deepcopy
+from functools import partial
+
+import sentry_sdk
+from sentry_sdk.api import continue_trace
+from sentry_sdk.consts import OP
+from sentry_sdk.integrations._asgi_common import (
+    _get_headers,
+    _get_request_data,
+    _get_url,
+)
+from sentry_sdk.integrations._wsgi_common import (
+    DEFAULT_HTTP_METHODS_TO_CAPTURE,
+    nullcontext,
+)
+from sentry_sdk.sessions import track_session
+from sentry_sdk.tracing import (
+    SOURCE_FOR_STYLE,
+    TransactionSource,
+)
+from sentry_sdk.utils import (
+    ContextVar,
+    event_from_exception,
+    HAS_REAL_CONTEXTVARS,
+    CONTEXTVARS_ERROR_MESSAGE,
+    logger,
+    transaction_from_function,
+    _get_installed_modules,
+)
+from sentry_sdk.tracing import Transaction
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Dict
+    from typing import Optional
+    from typing import Tuple
+
+    from sentry_sdk._types import Event, Hint
+
+
+_asgi_middleware_applied = ContextVar("sentry_asgi_middleware_applied")
+
+_DEFAULT_TRANSACTION_NAME = "generic ASGI request"
+
+TRANSACTION_STYLE_VALUES = ("endpoint", "url")
+
+
+def _capture_exception(exc, mechanism_type="asgi"):
+    # type: (Any, str) -> None
+
+    event, hint = event_from_exception(
+        exc,
+        client_options=sentry_sdk.get_client().options,
+        mechanism={"type": mechanism_type, "handled": False},
+    )
+    sentry_sdk.capture_event(event, hint=hint)
+
+
+def _looks_like_asgi3(app):
+    # type: (Any) -> bool
+    """
+    Try to figure out if an application object supports ASGI3.
+
+    This is how uvicorn figures out the application version as well.
+    """
+    if inspect.isclass(app):
+        return hasattr(app, "__await__")
+    elif inspect.isfunction(app):
+        return asyncio.iscoroutinefunction(app)
+    else:
+        call = getattr(app, "__call__", None)  # noqa
+        return asyncio.iscoroutinefunction(call)
+
+
+class SentryAsgiMiddleware:
+    __slots__ = (
+        "app",
+        "__call__",
+        "transaction_style",
+        "mechanism_type",
+        "span_origin",
+        "http_methods_to_capture",
+    )
+
+    def __init__(
+        self,
+        app,  # type: Any
+        unsafe_context_data=False,  # type: bool
+        transaction_style="endpoint",  # type: str
+        mechanism_type="asgi",  # type: str
+        span_origin="manual",  # type: str
+        http_methods_to_capture=DEFAULT_HTTP_METHODS_TO_CAPTURE,  # type: Tuple[str, ...]
+        asgi_version=None,  # type: Optional[int]
+    ):
+        # type: (...) -> None
+        """
+        Instrument an ASGI application with Sentry. Provides HTTP/websocket
+        data to sent events and basic handling for exceptions bubbling up
+        through the middleware.
+
+        :param unsafe_context_data: Disable errors when a proper contextvars installation could not be found. We do not recommend changing this from the default.
+        """
+        if not unsafe_context_data and not HAS_REAL_CONTEXTVARS:
+            # We better have contextvars or we're going to leak state between
+            # requests.
+            raise RuntimeError(
+                "The ASGI middleware for Sentry requires Python 3.7+ "
+                "or the aiocontextvars package." + CONTEXTVARS_ERROR_MESSAGE
+            )
+        if transaction_style not in TRANSACTION_STYLE_VALUES:
+            raise ValueError(
+                "Invalid value for transaction_style: %s (must be in %s)"
+                % (transaction_style, TRANSACTION_STYLE_VALUES)
+            )
+
+        asgi_middleware_while_using_starlette_or_fastapi = (
+            mechanism_type == "asgi" and "starlette" in _get_installed_modules()
+        )
+        if asgi_middleware_while_using_starlette_or_fastapi:
+            logger.warning(
+                "The Sentry Python SDK can now automatically support ASGI frameworks like Starlette and FastAPI. "
+                "Please remove 'SentryAsgiMiddleware' from your project. "
+                "See https://docs.sentry.io/platforms/python/guides/asgi/ for more information."
+            )
+
+        self.transaction_style = transaction_style
+        self.mechanism_type = mechanism_type
+        self.span_origin = span_origin
+        self.app = app
+        self.http_methods_to_capture = http_methods_to_capture
+
+        if asgi_version is None:
+            if _looks_like_asgi3(app):
+                asgi_version = 3
+            else:
+                asgi_version = 2
+
+        if asgi_version == 3:
+            self.__call__ = self._run_asgi3
+        elif asgi_version == 2:
+            self.__call__ = self._run_asgi2  # type: ignore
+
+    def _capture_lifespan_exception(self, exc):
+        # type: (Exception) -> None
+        """Capture exceptions raise in application lifespan handlers.
+
+        The separate function is needed to support overriding in derived integrations that use different catching mechanisms.
+        """
+        return _capture_exception(exc=exc, mechanism_type=self.mechanism_type)
+
+    def _capture_request_exception(self, exc):
+        # type: (Exception) -> None
+        """Capture exceptions raised in incoming request handlers.
+
+        The separate function is needed to support overriding in derived integrations that use different catching mechanisms.
+        """
+        return _capture_exception(exc=exc, mechanism_type=self.mechanism_type)
+
+    def _run_asgi2(self, scope):
+        # type: (Any) -> Any
+        async def inner(receive, send):
+            # type: (Any, Any) -> Any
+            return await self._run_app(scope, receive, send, asgi_version=2)
+
+        return inner
+
+    async def _run_asgi3(self, scope, receive, send):
+        # type: (Any, Any, Any) -> Any
+        return await self._run_app(scope, receive, send, asgi_version=3)
+
+    async def _run_app(self, scope, receive, send, asgi_version):
+        # type: (Any, Any, Any, int) -> Any
+        is_recursive_asgi_middleware = _asgi_middleware_applied.get(False)
+        is_lifespan = scope["type"] == "lifespan"
+        if is_recursive_asgi_middleware or is_lifespan:
+            try:
+                if asgi_version == 2:
+                    return await self.app(scope)(receive, send)
+                else:
+                    return await self.app(scope, receive, send)
+
+            except Exception as exc:
+                self._capture_lifespan_exception(exc)
+                raise exc from None
+
+        _asgi_middleware_applied.set(True)
+        try:
+            with sentry_sdk.isolation_scope() as sentry_scope:
+                with track_session(sentry_scope, session_mode="request"):
+                    sentry_scope.clear_breadcrumbs()
+                    sentry_scope._name = "asgi"
+                    processor = partial(self.event_processor, asgi_scope=scope)
+                    sentry_scope.add_event_processor(processor)
+
+                    ty = scope["type"]
+                    (
+                        transaction_name,
+                        transaction_source,
+                    ) = self._get_transaction_name_and_source(
+                        self.transaction_style,
+                        scope,
+                    )
+
+                    method = scope.get("method", "").upper()
+                    transaction = None
+                    if ty in ("http", "websocket"):
+                        if ty == "websocket" or method in self.http_methods_to_capture:
+                            transaction = continue_trace(
+                                _get_headers(scope),
+                                op="{}.server".format(ty),
+                                name=transaction_name,
+                                source=transaction_source,
+                                origin=self.span_origin,
+                            )
+                    else:
+                        transaction = Transaction(
+                            op=OP.HTTP_SERVER,
+                            name=transaction_name,
+                            source=transaction_source,
+                            origin=self.span_origin,
+                        )
+
+                    if transaction:
+                        transaction.set_tag("asgi.type", ty)
+
+                    with (
+                        sentry_sdk.start_transaction(
+                            transaction,
+                            custom_sampling_context={"asgi_scope": scope},
+                        )
+                        if transaction is not None
+                        else nullcontext()
+                    ):
+                        try:
+
+                            async def _sentry_wrapped_send(event):
+                                # type: (Dict[str, Any]) -> Any
+                                if transaction is not None:
+                                    is_http_response = (
+                                        event.get("type") == "http.response.start"
+                                        and "status" in event
+                                    )
+                                    if is_http_response:
+                                        transaction.set_http_status(event["status"])
+
+                                return await send(event)
+
+                            if asgi_version == 2:
+                                return await self.app(scope)(
+                                    receive, _sentry_wrapped_send
+                                )
+                            else:
+                                return await self.app(
+                                    scope, receive, _sentry_wrapped_send
+                                )
+                        except Exception as exc:
+                            self._capture_request_exception(exc)
+                            raise exc from None
+        finally:
+            _asgi_middleware_applied.set(False)
+
+    def event_processor(self, event, hint, asgi_scope):
+        # type: (Event, Hint, Any) -> Optional[Event]
+        request_data = event.get("request", {})
+        request_data.update(_get_request_data(asgi_scope))
+        event["request"] = deepcopy(request_data)
+
+        # Only set transaction name if not already set by Starlette or FastAPI (or other frameworks)
+        transaction = event.get("transaction")
+        transaction_source = (event.get("transaction_info") or {}).get("source")
+        already_set = (
+            transaction is not None
+            and transaction != _DEFAULT_TRANSACTION_NAME
+            and transaction_source
+            in [
+                TransactionSource.COMPONENT,
+                TransactionSource.ROUTE,
+                TransactionSource.CUSTOM,
+            ]
+        )
+        if not already_set:
+            name, source = self._get_transaction_name_and_source(
+                self.transaction_style, asgi_scope
+            )
+            event["transaction"] = name
+            event["transaction_info"] = {"source": source}
+
+        return event
+
+    # Helper functions.
+    #
+    # Note: Those functions are not public API. If you want to mutate request
+    # data to your liking it's recommended to use the `before_send` callback
+    # for that.
+
+    def _get_transaction_name_and_source(self, transaction_style, asgi_scope):
+        # type: (SentryAsgiMiddleware, str, Any) -> Tuple[str, str]
+        name = None
+        source = SOURCE_FOR_STYLE[transaction_style]
+        ty = asgi_scope.get("type")
+
+        if transaction_style == "endpoint":
+            endpoint = asgi_scope.get("endpoint")
+            # Webframeworks like Starlette mutate the ASGI env once routing is
+            # done, which is sometime after the request has started. If we have
+            # an endpoint, overwrite our generic transaction name.
+            if endpoint:
+                name = transaction_from_function(endpoint) or ""
+            else:
+                name = _get_url(asgi_scope, "http" if ty == "http" else "ws", host=None)
+                source = TransactionSource.URL
+
+        elif transaction_style == "url":
+            # FastAPI includes the route object in the scope to let Sentry extract the
+            # path from it for the transaction name
+            route = asgi_scope.get("route")
+            if route:
+                path = getattr(route, "path", None)
+                if path is not None:
+                    name = path
+            else:
+                name = _get_url(asgi_scope, "http" if ty == "http" else "ws", host=None)
+                source = TransactionSource.URL
+
+        if name is None:
+            name = _DEFAULT_TRANSACTION_NAME
+            source = TransactionSource.ROUTE
+            return name, source
+
+        return name, source
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/asyncio.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/asyncio.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae580ca0385704c51f3ef7c5a27e4b6665a4cd78
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/asyncio.py
@@ -0,0 +1,127 @@
+import sys
+
+import sentry_sdk
+from sentry_sdk.consts import OP
+from sentry_sdk.integrations import Integration, DidNotEnable
+from sentry_sdk.utils import event_from_exception, logger, reraise
+
+try:
+    import asyncio
+    from asyncio.tasks import Task
+except ImportError:
+    raise DidNotEnable("asyncio not available")
+
+from typing import cast, TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from collections.abc import Coroutine
+
+    from sentry_sdk._types import ExcInfo
+
+
+def get_name(coro):
+    # type: (Any) -> str
+    return (
+        getattr(coro, "__qualname__", None)
+        or getattr(coro, "__name__", None)
+        or "coroutine without __name__"
+    )
+
+
+def patch_asyncio():
+    # type: () -> None
+    orig_task_factory = None
+    try:
+        loop = asyncio.get_running_loop()
+        orig_task_factory = loop.get_task_factory()
+
+        def _sentry_task_factory(loop, coro, **kwargs):
+            # type: (asyncio.AbstractEventLoop, Coroutine[Any, Any, Any], Any) -> asyncio.Future[Any]
+
+            async def _task_with_sentry_span_creation():
+                # type: () -> Any
+                result = None
+
+                with sentry_sdk.isolation_scope():
+                    with sentry_sdk.start_span(
+                        op=OP.FUNCTION,
+                        name=get_name(coro),
+                        origin=AsyncioIntegration.origin,
+                    ):
+                        try:
+                            result = await coro
+                        except Exception:
+                            reraise(*_capture_exception())
+
+                return result
+
+            task = None
+
+            # Trying to use user set task factory (if there is one)
+            if orig_task_factory:
+                task = orig_task_factory(
+                    loop, _task_with_sentry_span_creation(), **kwargs
+                )
+
+            if task is None:
+                # The default task factory in `asyncio` does not have its own function
+                # but is just a couple of lines in `asyncio.base_events.create_task()`
+                # Those lines are copied here.
+
+                # WARNING:
+                # If the default behavior of the task creation in asyncio changes,
+                # this will break!
+                task = Task(_task_with_sentry_span_creation(), loop=loop, **kwargs)
+                if task._source_traceback:  # type: ignore
+                    del task._source_traceback[-1]  # type: ignore
+
+            # Set the task name to include the original coroutine's name
+            try:
+                cast("asyncio.Task[Any]", task).set_name(
+                    f"{get_name(coro)} (Sentry-wrapped)"
+                )
+            except AttributeError:
+                # set_name might not be available in all Python versions
+                pass
+
+            return task
+
+        loop.set_task_factory(_sentry_task_factory)  # type: ignore
+
+    except RuntimeError:
+        # When there is no running loop, we have nothing to patch.
+        logger.warning(
+            "There is no running asyncio loop so there is nothing Sentry can patch. "
+            "Please make sure you call sentry_sdk.init() within a running "
+            "asyncio loop for the AsyncioIntegration to work. "
+            "See https://docs.sentry.io/platforms/python/integrations/asyncio/"
+        )
+
+
+def _capture_exception():
+    # type: () -> ExcInfo
+    exc_info = sys.exc_info()
+
+    client = sentry_sdk.get_client()
+
+    integration = client.get_integration(AsyncioIntegration)
+    if integration is not None:
+        event, hint = event_from_exception(
+            exc_info,
+            client_options=client.options,
+            mechanism={"type": "asyncio", "handled": False},
+        )
+        sentry_sdk.capture_event(event, hint=hint)
+
+    return exc_info
+
+
+class AsyncioIntegration(Integration):
+    identifier = "asyncio"
+    origin = f"auto.function.{identifier}"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        patch_asyncio()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/asyncpg.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/asyncpg.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6b53f4668b25c0931f969e60fb2dcd5c2db3dbe
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/asyncpg.py
@@ -0,0 +1,208 @@
+from __future__ import annotations
+import contextlib
+from typing import Any, TypeVar, Callable, Awaitable, Iterator
+
+import sentry_sdk
+from sentry_sdk.consts import OP, SPANDATA
+from sentry_sdk.integrations import _check_minimum_version, Integration, DidNotEnable
+from sentry_sdk.tracing import Span
+from sentry_sdk.tracing_utils import add_query_source, record_sql_queries
+from sentry_sdk.utils import (
+    ensure_integration_enabled,
+    parse_version,
+    capture_internal_exceptions,
+)
+
+try:
+    import asyncpg  # type: ignore[import-not-found]
+    from asyncpg.cursor import BaseCursor  # type: ignore
+
+except ImportError:
+    raise DidNotEnable("asyncpg not installed.")
+
+
+class AsyncPGIntegration(Integration):
+    identifier = "asyncpg"
+    origin = f"auto.db.{identifier}"
+    _record_params = False
+
+    def __init__(self, *, record_params: bool = False):
+        AsyncPGIntegration._record_params = record_params
+
+    @staticmethod
+    def setup_once() -> None:
+        # asyncpg.__version__ is a string containing the semantic version in the form of ".."
+        asyncpg_version = parse_version(asyncpg.__version__)
+        _check_minimum_version(AsyncPGIntegration, asyncpg_version)
+
+        asyncpg.Connection.execute = _wrap_execute(
+            asyncpg.Connection.execute,
+        )
+
+        asyncpg.Connection._execute = _wrap_connection_method(
+            asyncpg.Connection._execute
+        )
+        asyncpg.Connection._executemany = _wrap_connection_method(
+            asyncpg.Connection._executemany, executemany=True
+        )
+        asyncpg.Connection.cursor = _wrap_cursor_creation(asyncpg.Connection.cursor)
+        asyncpg.Connection.prepare = _wrap_connection_method(asyncpg.Connection.prepare)
+        asyncpg.connect_utils._connect_addr = _wrap_connect_addr(
+            asyncpg.connect_utils._connect_addr
+        )
+
+
+T = TypeVar("T")
+
+
+def _wrap_execute(f: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]:
+    async def _inner(*args: Any, **kwargs: Any) -> T:
+        if sentry_sdk.get_client().get_integration(AsyncPGIntegration) is None:
+            return await f(*args, **kwargs)
+
+        # Avoid recording calls to _execute twice.
+        # Calls to Connection.execute with args also call
+        # Connection._execute, which is recorded separately
+        # args[0] = the connection object, args[1] is the query
+        if len(args) > 2:
+            return await f(*args, **kwargs)
+
+        query = args[1]
+        with record_sql_queries(
+            cursor=None,
+            query=query,
+            params_list=None,
+            paramstyle=None,
+            executemany=False,
+            span_origin=AsyncPGIntegration.origin,
+        ) as span:
+            res = await f(*args, **kwargs)
+
+        with capture_internal_exceptions():
+            add_query_source(span)
+
+        return res
+
+    return _inner
+
+
+SubCursor = TypeVar("SubCursor", bound=BaseCursor)
+
+
+@contextlib.contextmanager
+def _record(
+    cursor: SubCursor | None,
+    query: str,
+    params_list: tuple[Any, ...] | None,
+    *,
+    executemany: bool = False,
+) -> Iterator[Span]:
+    integration = sentry_sdk.get_client().get_integration(AsyncPGIntegration)
+    if integration is not None and not integration._record_params:
+        params_list = None
+
+    param_style = "pyformat" if params_list else None
+
+    with record_sql_queries(
+        cursor=cursor,
+        query=query,
+        params_list=params_list,
+        paramstyle=param_style,
+        executemany=executemany,
+        record_cursor_repr=cursor is not None,
+        span_origin=AsyncPGIntegration.origin,
+    ) as span:
+        yield span
+
+
+def _wrap_connection_method(
+    f: Callable[..., Awaitable[T]], *, executemany: bool = False
+) -> Callable[..., Awaitable[T]]:
+    async def _inner(*args: Any, **kwargs: Any) -> T:
+        if sentry_sdk.get_client().get_integration(AsyncPGIntegration) is None:
+            return await f(*args, **kwargs)
+        query = args[1]
+        params_list = args[2] if len(args) > 2 else None
+        with _record(None, query, params_list, executemany=executemany) as span:
+            _set_db_data(span, args[0])
+            res = await f(*args, **kwargs)
+
+        return res
+
+    return _inner
+
+
+def _wrap_cursor_creation(f: Callable[..., T]) -> Callable[..., T]:
+    @ensure_integration_enabled(AsyncPGIntegration, f)
+    def _inner(*args: Any, **kwargs: Any) -> T:  # noqa: N807
+        query = args[1]
+        params_list = args[2] if len(args) > 2 else None
+
+        with _record(
+            None,
+            query,
+            params_list,
+            executemany=False,
+        ) as span:
+            _set_db_data(span, args[0])
+            res = f(*args, **kwargs)
+            span.set_data("db.cursor", res)
+
+        return res
+
+    return _inner
+
+
+def _wrap_connect_addr(f: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]:
+    async def _inner(*args: Any, **kwargs: Any) -> T:
+        if sentry_sdk.get_client().get_integration(AsyncPGIntegration) is None:
+            return await f(*args, **kwargs)
+
+        user = kwargs["params"].user
+        database = kwargs["params"].database
+
+        with sentry_sdk.start_span(
+            op=OP.DB,
+            name="connect",
+            origin=AsyncPGIntegration.origin,
+        ) as span:
+            span.set_data(SPANDATA.DB_SYSTEM, "postgresql")
+            addr = kwargs.get("addr")
+            if addr:
+                try:
+                    span.set_data(SPANDATA.SERVER_ADDRESS, addr[0])
+                    span.set_data(SPANDATA.SERVER_PORT, addr[1])
+                except IndexError:
+                    pass
+            span.set_data(SPANDATA.DB_NAME, database)
+            span.set_data(SPANDATA.DB_USER, user)
+
+            with capture_internal_exceptions():
+                sentry_sdk.add_breadcrumb(
+                    message="connect", category="query", data=span._data
+                )
+            res = await f(*args, **kwargs)
+
+        return res
+
+    return _inner
+
+
+def _set_db_data(span: Span, conn: Any) -> None:
+    span.set_data(SPANDATA.DB_SYSTEM, "postgresql")
+
+    addr = conn._addr
+    if addr:
+        try:
+            span.set_data(SPANDATA.SERVER_ADDRESS, addr[0])
+            span.set_data(SPANDATA.SERVER_PORT, addr[1])
+        except IndexError:
+            pass
+
+    database = conn._params.database
+    if database:
+        span.set_data(SPANDATA.DB_NAME, database)
+
+    user = conn._params.user
+    if user:
+        span.set_data(SPANDATA.DB_USER, user)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/atexit.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/atexit.py
new file mode 100644
index 0000000000000000000000000000000000000000..dfc6d08e1af25c4680a16e2e074c44eebf73fc53
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/atexit.py
@@ -0,0 +1,57 @@
+import os
+import sys
+import atexit
+
+import sentry_sdk
+from sentry_sdk.utils import logger
+from sentry_sdk.integrations import Integration
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Optional
+
+
+def default_callback(pending, timeout):
+    # type: (int, int) -> None
+    """This is the default shutdown callback that is set on the options.
+    It prints out a message to stderr that informs the user that some events
+    are still pending and the process is waiting for them to flush out.
+    """
+
+    def echo(msg):
+        # type: (str) -> None
+        sys.stderr.write(msg + "\n")
+
+    echo("Sentry is attempting to send %i pending events" % pending)
+    echo("Waiting up to %s seconds" % timeout)
+    echo("Press Ctrl-%s to quit" % (os.name == "nt" and "Break" or "C"))
+    sys.stderr.flush()
+
+
+class AtexitIntegration(Integration):
+    identifier = "atexit"
+
+    def __init__(self, callback=None):
+        # type: (Optional[Any]) -> None
+        if callback is None:
+            callback = default_callback
+        self.callback = callback
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        @atexit.register
+        def _shutdown():
+            # type: () -> None
+            client = sentry_sdk.get_client()
+            integration = client.get_integration(AtexitIntegration)
+
+            if integration is None:
+                return
+
+            logger.debug("atexit: got shutdown signal")
+            logger.debug("atexit: shutting down client")
+            sentry_sdk.get_isolation_scope().end_session()
+
+            client.close(callback=integration.callback)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/aws_lambda.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/aws_lambda.py
new file mode 100644
index 0000000000000000000000000000000000000000..4990fd6e6a4f8568412c5f6b94a6f420a98b70cb
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/aws_lambda.py
@@ -0,0 +1,499 @@
+import functools
+import json
+import re
+import sys
+from copy import deepcopy
+from datetime import datetime, timedelta, timezone
+from os import environ
+
+import sentry_sdk
+from sentry_sdk.api import continue_trace
+from sentry_sdk.consts import OP
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.tracing import TransactionSource
+from sentry_sdk.utils import (
+    AnnotatedValue,
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    event_from_exception,
+    logger,
+    TimeoutThread,
+    reraise,
+)
+from sentry_sdk.integrations import Integration
+from sentry_sdk.integrations._wsgi_common import _filter_headers
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import TypeVar
+    from typing import Callable
+    from typing import Optional
+
+    from sentry_sdk._types import EventProcessor, Event, Hint
+
+    F = TypeVar("F", bound=Callable[..., Any])
+
+# Constants
+TIMEOUT_WARNING_BUFFER = 1500  # Buffer time required to send timeout warning to Sentry
+MILLIS_TO_SECONDS = 1000.0
+
+
+def _wrap_init_error(init_error):
+    # type: (F) -> F
+    @ensure_integration_enabled(AwsLambdaIntegration, init_error)
+    def sentry_init_error(*args, **kwargs):
+        # type: (*Any, **Any) -> Any
+        client = sentry_sdk.get_client()
+
+        with capture_internal_exceptions():
+            sentry_sdk.get_isolation_scope().clear_breadcrumbs()
+
+            exc_info = sys.exc_info()
+            if exc_info and all(exc_info):
+                sentry_event, hint = event_from_exception(
+                    exc_info,
+                    client_options=client.options,
+                    mechanism={"type": "aws_lambda", "handled": False},
+                )
+                sentry_sdk.capture_event(sentry_event, hint=hint)
+
+            else:
+                # Fall back to AWS lambdas JSON representation of the error
+                error_info = args[1]
+                if isinstance(error_info, str):
+                    error_info = json.loads(error_info)
+                sentry_event = _event_from_error_json(error_info)
+                sentry_sdk.capture_event(sentry_event)
+
+        return init_error(*args, **kwargs)
+
+    return sentry_init_error  # type: ignore
+
+
+def _wrap_handler(handler):
+    # type: (F) -> F
+    @functools.wraps(handler)
+    def sentry_handler(aws_event, aws_context, *args, **kwargs):
+        # type: (Any, Any, *Any, **Any) -> Any
+
+        # Per https://docs.aws.amazon.com/lambda/latest/dg/python-handler.html,
+        # `event` here is *likely* a dictionary, but also might be a number of
+        # other types (str, int, float, None).
+        #
+        # In some cases, it is a list (if the user is batch-invoking their
+        # function, for example), in which case we'll use the first entry as a
+        # representative from which to try pulling request data. (Presumably it
+        # will be the same for all events in the list, since they're all hitting
+        # the lambda in the same request.)
+
+        client = sentry_sdk.get_client()
+        integration = client.get_integration(AwsLambdaIntegration)
+
+        if integration is None:
+            return handler(aws_event, aws_context, *args, **kwargs)
+
+        if isinstance(aws_event, list) and len(aws_event) >= 1:
+            request_data = aws_event[0]
+            batch_size = len(aws_event)
+        else:
+            request_data = aws_event
+            batch_size = 1
+
+        if not isinstance(request_data, dict):
+            # If we're not dealing with a dictionary, we won't be able to get
+            # headers, path, http method, etc in any case, so it's fine that
+            # this is empty
+            request_data = {}
+
+        configured_time = aws_context.get_remaining_time_in_millis()
+
+        with sentry_sdk.isolation_scope() as scope:
+            timeout_thread = None
+            with capture_internal_exceptions():
+                scope.clear_breadcrumbs()
+                scope.add_event_processor(
+                    _make_request_event_processor(
+                        request_data, aws_context, configured_time
+                    )
+                )
+                scope.set_tag(
+                    "aws_region", aws_context.invoked_function_arn.split(":")[3]
+                )
+                if batch_size > 1:
+                    scope.set_tag("batch_request", True)
+                    scope.set_tag("batch_size", batch_size)
+
+                # Starting the Timeout thread only if the configured time is greater than Timeout warning
+                # buffer and timeout_warning parameter is set True.
+                if (
+                    integration.timeout_warning
+                    and configured_time > TIMEOUT_WARNING_BUFFER
+                ):
+                    waiting_time = (
+                        configured_time - TIMEOUT_WARNING_BUFFER
+                    ) / MILLIS_TO_SECONDS
+
+                    timeout_thread = TimeoutThread(
+                        waiting_time,
+                        configured_time / MILLIS_TO_SECONDS,
+                    )
+
+                    # Starting the thread to raise timeout warning exception
+                    timeout_thread.start()
+
+            headers = request_data.get("headers", {})
+            # Some AWS Services (ie. EventBridge) set headers as a list
+            # or None, so we must ensure it is a dict
+            if not isinstance(headers, dict):
+                headers = {}
+
+            transaction = continue_trace(
+                headers,
+                op=OP.FUNCTION_AWS,
+                name=aws_context.function_name,
+                source=TransactionSource.COMPONENT,
+                origin=AwsLambdaIntegration.origin,
+            )
+            with sentry_sdk.start_transaction(
+                transaction,
+                custom_sampling_context={
+                    "aws_event": aws_event,
+                    "aws_context": aws_context,
+                },
+            ):
+                try:
+                    return handler(aws_event, aws_context, *args, **kwargs)
+                except Exception:
+                    exc_info = sys.exc_info()
+                    sentry_event, hint = event_from_exception(
+                        exc_info,
+                        client_options=client.options,
+                        mechanism={"type": "aws_lambda", "handled": False},
+                    )
+                    sentry_sdk.capture_event(sentry_event, hint=hint)
+                    reraise(*exc_info)
+                finally:
+                    if timeout_thread:
+                        timeout_thread.stop()
+
+    return sentry_handler  # type: ignore
+
+
+def _drain_queue():
+    # type: () -> None
+    with capture_internal_exceptions():
+        client = sentry_sdk.get_client()
+        integration = client.get_integration(AwsLambdaIntegration)
+        if integration is not None:
+            # Flush out the event queue before AWS kills the
+            # process.
+            client.flush()
+
+
+class AwsLambdaIntegration(Integration):
+    identifier = "aws_lambda"
+    origin = f"auto.function.{identifier}"
+
+    def __init__(self, timeout_warning=False):
+        # type: (bool) -> None
+        self.timeout_warning = timeout_warning
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+
+        lambda_bootstrap = get_lambda_bootstrap()
+        if not lambda_bootstrap:
+            logger.warning(
+                "Not running in AWS Lambda environment, "
+                "AwsLambdaIntegration disabled (could not find bootstrap module)"
+            )
+            return
+
+        if not hasattr(lambda_bootstrap, "handle_event_request"):
+            logger.warning(
+                "Not running in AWS Lambda environment, "
+                "AwsLambdaIntegration disabled (could not find handle_event_request)"
+            )
+            return
+
+        pre_37 = hasattr(lambda_bootstrap, "handle_http_request")  # Python 3.6
+
+        if pre_37:
+            old_handle_event_request = lambda_bootstrap.handle_event_request
+
+            def sentry_handle_event_request(request_handler, *args, **kwargs):
+                # type: (Any, *Any, **Any) -> Any
+                request_handler = _wrap_handler(request_handler)
+                return old_handle_event_request(request_handler, *args, **kwargs)
+
+            lambda_bootstrap.handle_event_request = sentry_handle_event_request
+
+            old_handle_http_request = lambda_bootstrap.handle_http_request
+
+            def sentry_handle_http_request(request_handler, *args, **kwargs):
+                # type: (Any, *Any, **Any) -> Any
+                request_handler = _wrap_handler(request_handler)
+                return old_handle_http_request(request_handler, *args, **kwargs)
+
+            lambda_bootstrap.handle_http_request = sentry_handle_http_request
+
+            # Patch to_json to drain the queue. This should work even when the
+            # SDK is initialized inside of the handler
+
+            old_to_json = lambda_bootstrap.to_json
+
+            def sentry_to_json(*args, **kwargs):
+                # type: (*Any, **Any) -> Any
+                _drain_queue()
+                return old_to_json(*args, **kwargs)
+
+            lambda_bootstrap.to_json = sentry_to_json
+        else:
+            lambda_bootstrap.LambdaRuntimeClient.post_init_error = _wrap_init_error(
+                lambda_bootstrap.LambdaRuntimeClient.post_init_error
+            )
+
+            old_handle_event_request = lambda_bootstrap.handle_event_request
+
+            def sentry_handle_event_request(  # type: ignore
+                lambda_runtime_client, request_handler, *args, **kwargs
+            ):
+                request_handler = _wrap_handler(request_handler)
+                return old_handle_event_request(
+                    lambda_runtime_client, request_handler, *args, **kwargs
+                )
+
+            lambda_bootstrap.handle_event_request = sentry_handle_event_request
+
+            # Patch the runtime client to drain the queue. This should work
+            # even when the SDK is initialized inside of the handler
+
+            def _wrap_post_function(f):
+                # type: (F) -> F
+                def inner(*args, **kwargs):
+                    # type: (*Any, **Any) -> Any
+                    _drain_queue()
+                    return f(*args, **kwargs)
+
+                return inner  # type: ignore
+
+            lambda_bootstrap.LambdaRuntimeClient.post_invocation_result = (
+                _wrap_post_function(
+                    lambda_bootstrap.LambdaRuntimeClient.post_invocation_result
+                )
+            )
+            lambda_bootstrap.LambdaRuntimeClient.post_invocation_error = (
+                _wrap_post_function(
+                    lambda_bootstrap.LambdaRuntimeClient.post_invocation_error
+                )
+            )
+
+
+def get_lambda_bootstrap():
+    # type: () -> Optional[Any]
+
+    # Python 3.7: If the bootstrap module is *already imported*, it is the
+    # one we actually want to use (no idea what's in __main__)
+    #
+    # Python 3.8: bootstrap is also importable, but will be the same file
+    # as __main__ imported under a different name:
+    #
+    #     sys.modules['__main__'].__file__ == sys.modules['bootstrap'].__file__
+    #     sys.modules['__main__'] is not sys.modules['bootstrap']
+    #
+    # Python 3.9: bootstrap is in __main__.awslambdaricmain
+    #
+    # On container builds using the `aws-lambda-python-runtime-interface-client`
+    # (awslamdaric) module, bootstrap is located in sys.modules['__main__'].bootstrap
+    #
+    # Such a setup would then make all monkeypatches useless.
+    if "bootstrap" in sys.modules:
+        return sys.modules["bootstrap"]
+    elif "__main__" in sys.modules:
+        module = sys.modules["__main__"]
+        # python3.9 runtime
+        if hasattr(module, "awslambdaricmain") and hasattr(
+            module.awslambdaricmain, "bootstrap"
+        ):
+            return module.awslambdaricmain.bootstrap
+        elif hasattr(module, "bootstrap"):
+            # awslambdaric python module in container builds
+            return module.bootstrap
+
+        # python3.8 runtime
+        return module
+    else:
+        return None
+
+
+def _make_request_event_processor(aws_event, aws_context, configured_timeout):
+    # type: (Any, Any, Any) -> EventProcessor
+    start_time = datetime.now(timezone.utc)
+
+    def event_processor(sentry_event, hint, start_time=start_time):
+        # type: (Event, Hint, datetime) -> Optional[Event]
+        remaining_time_in_milis = aws_context.get_remaining_time_in_millis()
+        exec_duration = configured_timeout - remaining_time_in_milis
+
+        extra = sentry_event.setdefault("extra", {})
+        extra["lambda"] = {
+            "function_name": aws_context.function_name,
+            "function_version": aws_context.function_version,
+            "invoked_function_arn": aws_context.invoked_function_arn,
+            "aws_request_id": aws_context.aws_request_id,
+            "execution_duration_in_millis": exec_duration,
+            "remaining_time_in_millis": remaining_time_in_milis,
+        }
+
+        extra["cloudwatch logs"] = {
+            "url": _get_cloudwatch_logs_url(aws_context, start_time),
+            "log_group": aws_context.log_group_name,
+            "log_stream": aws_context.log_stream_name,
+        }
+
+        request = sentry_event.get("request", {})
+
+        if "httpMethod" in aws_event:
+            request["method"] = aws_event["httpMethod"]
+
+        request["url"] = _get_url(aws_event, aws_context)
+
+        if "queryStringParameters" in aws_event:
+            request["query_string"] = aws_event["queryStringParameters"]
+
+        if "headers" in aws_event:
+            request["headers"] = _filter_headers(aws_event["headers"])
+
+        if should_send_default_pii():
+            user_info = sentry_event.setdefault("user", {})
+
+            identity = aws_event.get("identity")
+            if identity is None:
+                identity = {}
+
+            id = identity.get("userArn")
+            if id is not None:
+                user_info.setdefault("id", id)
+
+            ip = identity.get("sourceIp")
+            if ip is not None:
+                user_info.setdefault("ip_address", ip)
+
+            if "body" in aws_event:
+                request["data"] = aws_event.get("body", "")
+        else:
+            if aws_event.get("body", None):
+                # Unfortunately couldn't find a way to get structured body from AWS
+                # event. Meaning every body is unstructured to us.
+                request["data"] = AnnotatedValue.removed_because_raw_data()
+
+        sentry_event["request"] = deepcopy(request)
+
+        return sentry_event
+
+    return event_processor
+
+
+def _get_url(aws_event, aws_context):
+    # type: (Any, Any) -> str
+    path = aws_event.get("path", None)
+
+    headers = aws_event.get("headers")
+    if headers is None:
+        headers = {}
+
+    host = headers.get("Host", None)
+    proto = headers.get("X-Forwarded-Proto", None)
+    if proto and host and path:
+        return "{}://{}{}".format(proto, host, path)
+    return "awslambda:///{}".format(aws_context.function_name)
+
+
+def _get_cloudwatch_logs_url(aws_context, start_time):
+    # type: (Any, datetime) -> str
+    """
+    Generates a CloudWatchLogs console URL based on the context object
+
+    Arguments:
+        aws_context {Any} -- context from lambda handler
+
+    Returns:
+        str -- AWS Console URL to logs.
+    """
+    formatstring = "%Y-%m-%dT%H:%M:%SZ"
+    region = environ.get("AWS_REGION", "")
+
+    url = (
+        "https://console.{domain}/cloudwatch/home?region={region}"
+        "#logEventViewer:group={log_group};stream={log_stream}"
+        ";start={start_time};end={end_time}"
+    ).format(
+        domain="amazonaws.cn" if region.startswith("cn-") else "aws.amazon.com",
+        region=region,
+        log_group=aws_context.log_group_name,
+        log_stream=aws_context.log_stream_name,
+        start_time=(start_time - timedelta(seconds=1)).strftime(formatstring),
+        end_time=(datetime.now(timezone.utc) + timedelta(seconds=2)).strftime(
+            formatstring
+        ),
+    )
+
+    return url
+
+
+def _parse_formatted_traceback(formatted_tb):
+    # type: (list[str]) -> list[dict[str, Any]]
+    frames = []
+    for frame in formatted_tb:
+        match = re.match(r'File "(.+)", line (\d+), in (.+)', frame.strip())
+        if match:
+            file_name, line_number, func_name = match.groups()
+            line_number = int(line_number)
+            frames.append(
+                {
+                    "filename": file_name,
+                    "function": func_name,
+                    "lineno": line_number,
+                    "vars": None,
+                    "pre_context": None,
+                    "context_line": None,
+                    "post_context": None,
+                }
+            )
+    return frames
+
+
+def _event_from_error_json(error_json):
+    # type: (dict[str, Any]) -> Event
+    """
+    Converts the error JSON from AWS Lambda into a Sentry error event.
+    This is not a full fletched event, but better than nothing.
+
+    This is an example of where AWS creates the error JSON:
+    https://github.com/aws/aws-lambda-python-runtime-interface-client/blob/2.2.1/awslambdaric/bootstrap.py#L479
+    """
+    event = {
+        "level": "error",
+        "exception": {
+            "values": [
+                {
+                    "type": error_json.get("errorType"),
+                    "value": error_json.get("errorMessage"),
+                    "stacktrace": {
+                        "frames": _parse_formatted_traceback(
+                            error_json.get("stackTrace", [])
+                        ),
+                    },
+                    "mechanism": {
+                        "type": "aws_lambda",
+                        "handled": False,
+                    },
+                }
+            ],
+        },
+    }  # type: Event
+
+    return event
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/beam.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/beam.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2e4553f5a28e7546afd10215f0bb2f263ef8271
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/beam.py
@@ -0,0 +1,176 @@
+import sys
+import types
+from functools import wraps
+
+import sentry_sdk
+from sentry_sdk.integrations import Integration
+from sentry_sdk.integrations.logging import ignore_logger
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    event_from_exception,
+    reraise,
+)
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Iterator
+    from typing import TypeVar
+    from typing import Callable
+
+    from sentry_sdk._types import ExcInfo
+
+    T = TypeVar("T")
+    F = TypeVar("F", bound=Callable[..., Any])
+
+
+WRAPPED_FUNC = "_wrapped_{}_"
+INSPECT_FUNC = "_inspect_{}"  # Required format per apache_beam/transforms/core.py
+USED_FUNC = "_sentry_used_"
+
+
+class BeamIntegration(Integration):
+    identifier = "beam"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        from apache_beam.transforms.core import DoFn, ParDo  # type: ignore
+
+        ignore_logger("root")
+        ignore_logger("bundle_processor.create")
+
+        function_patches = ["process", "start_bundle", "finish_bundle", "setup"]
+        for func_name in function_patches:
+            setattr(
+                DoFn,
+                INSPECT_FUNC.format(func_name),
+                _wrap_inspect_call(DoFn, func_name),
+            )
+
+        old_init = ParDo.__init__
+
+        def sentry_init_pardo(self, fn, *args, **kwargs):
+            # type: (ParDo, Any, *Any, **Any) -> Any
+            # Do not monkey patch init twice
+            if not getattr(self, "_sentry_is_patched", False):
+                for func_name in function_patches:
+                    if not hasattr(fn, func_name):
+                        continue
+                    wrapped_func = WRAPPED_FUNC.format(func_name)
+
+                    # Check to see if inspect is set and process is not
+                    # to avoid monkey patching process twice.
+                    # Check to see if function is part of object for
+                    # backwards compatibility.
+                    process_func = getattr(fn, func_name)
+                    inspect_func = getattr(fn, INSPECT_FUNC.format(func_name))
+                    if not getattr(inspect_func, USED_FUNC, False) and not getattr(
+                        process_func, USED_FUNC, False
+                    ):
+                        setattr(fn, wrapped_func, process_func)
+                        setattr(fn, func_name, _wrap_task_call(process_func))
+
+                self._sentry_is_patched = True
+            old_init(self, fn, *args, **kwargs)
+
+        ParDo.__init__ = sentry_init_pardo
+
+
+def _wrap_inspect_call(cls, func_name):
+    # type: (Any, Any) -> Any
+
+    if not hasattr(cls, func_name):
+        return None
+
+    def _inspect(self):
+        # type: (Any) -> Any
+        """
+        Inspect function overrides the way Beam gets argspec.
+        """
+        wrapped_func = WRAPPED_FUNC.format(func_name)
+        if hasattr(self, wrapped_func):
+            process_func = getattr(self, wrapped_func)
+        else:
+            process_func = getattr(self, func_name)
+            setattr(self, func_name, _wrap_task_call(process_func))
+            setattr(self, wrapped_func, process_func)
+
+        # getfullargspec is deprecated in more recent beam versions and get_function_args_defaults
+        # (which uses Signatures internally) should be used instead.
+        try:
+            from apache_beam.transforms.core import get_function_args_defaults
+
+            return get_function_args_defaults(process_func)
+        except ImportError:
+            from apache_beam.typehints.decorators import getfullargspec  # type: ignore
+
+            return getfullargspec(process_func)
+
+    setattr(_inspect, USED_FUNC, True)
+    return _inspect
+
+
+def _wrap_task_call(func):
+    # type: (F) -> F
+    """
+    Wrap task call with a try catch to get exceptions.
+    """
+
+    @wraps(func)
+    def _inner(*args, **kwargs):
+        # type: (*Any, **Any) -> Any
+        try:
+            gen = func(*args, **kwargs)
+        except Exception:
+            raise_exception()
+
+        if not isinstance(gen, types.GeneratorType):
+            return gen
+        return _wrap_generator_call(gen)
+
+    setattr(_inner, USED_FUNC, True)
+    return _inner  # type: ignore
+
+
+@ensure_integration_enabled(BeamIntegration)
+def _capture_exception(exc_info):
+    # type: (ExcInfo) -> None
+    """
+    Send Beam exception to Sentry.
+    """
+    client = sentry_sdk.get_client()
+
+    event, hint = event_from_exception(
+        exc_info,
+        client_options=client.options,
+        mechanism={"type": "beam", "handled": False},
+    )
+    sentry_sdk.capture_event(event, hint=hint)
+
+
+def raise_exception():
+    # type: () -> None
+    """
+    Raise an exception.
+    """
+    exc_info = sys.exc_info()
+    with capture_internal_exceptions():
+        _capture_exception(exc_info)
+    reraise(*exc_info)
+
+
+def _wrap_generator_call(gen):
+    # type: (Iterator[T]) -> Iterator[T]
+    """
+    Wrap the generator to handle any failures.
+    """
+    while True:
+        try:
+            yield next(gen)
+        except StopIteration:
+            break
+        except Exception:
+            raise_exception()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/boto3.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/boto3.py
new file mode 100644
index 0000000000000000000000000000000000000000..0207341f1bb8bd126beae3a2fb65639e87d90e9c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/boto3.py
@@ -0,0 +1,137 @@
+from functools import partial
+
+import sentry_sdk
+from sentry_sdk.consts import OP, SPANDATA
+from sentry_sdk.integrations import _check_minimum_version, Integration, DidNotEnable
+from sentry_sdk.tracing import Span
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    parse_url,
+    parse_version,
+)
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Dict
+    from typing import Optional
+    from typing import Type
+
+try:
+    from botocore import __version__ as BOTOCORE_VERSION  # type: ignore
+    from botocore.client import BaseClient  # type: ignore
+    from botocore.response import StreamingBody  # type: ignore
+    from botocore.awsrequest import AWSRequest  # type: ignore
+except ImportError:
+    raise DidNotEnable("botocore is not installed")
+
+
+class Boto3Integration(Integration):
+    identifier = "boto3"
+    origin = f"auto.http.{identifier}"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        version = parse_version(BOTOCORE_VERSION)
+        _check_minimum_version(Boto3Integration, version, "botocore")
+
+        orig_init = BaseClient.__init__
+
+        def sentry_patched_init(self, *args, **kwargs):
+            # type: (Type[BaseClient], *Any, **Any) -> None
+            orig_init(self, *args, **kwargs)
+            meta = self.meta
+            service_id = meta.service_model.service_id.hyphenize()
+            meta.events.register(
+                "request-created",
+                partial(_sentry_request_created, service_id=service_id),
+            )
+            meta.events.register("after-call", _sentry_after_call)
+            meta.events.register("after-call-error", _sentry_after_call_error)
+
+        BaseClient.__init__ = sentry_patched_init
+
+
+@ensure_integration_enabled(Boto3Integration)
+def _sentry_request_created(service_id, request, operation_name, **kwargs):
+    # type: (str, AWSRequest, str, **Any) -> None
+    description = "aws.%s.%s" % (service_id, operation_name)
+    span = sentry_sdk.start_span(
+        op=OP.HTTP_CLIENT,
+        name=description,
+        origin=Boto3Integration.origin,
+    )
+
+    with capture_internal_exceptions():
+        parsed_url = parse_url(request.url, sanitize=False)
+        span.set_data("aws.request.url", parsed_url.url)
+        span.set_data(SPANDATA.HTTP_QUERY, parsed_url.query)
+        span.set_data(SPANDATA.HTTP_FRAGMENT, parsed_url.fragment)
+
+    span.set_tag("aws.service_id", service_id)
+    span.set_tag("aws.operation_name", operation_name)
+    span.set_data(SPANDATA.HTTP_METHOD, request.method)
+
+    # We do it in order for subsequent http calls/retries be
+    # attached to this span.
+    span.__enter__()
+
+    # request.context is an open-ended data-structure
+    # where we can add anything useful in request life cycle.
+    request.context["_sentrysdk_span"] = span
+
+
+def _sentry_after_call(context, parsed, **kwargs):
+    # type: (Dict[str, Any], Dict[str, Any], **Any) -> None
+    span = context.pop("_sentrysdk_span", None)  # type: Optional[Span]
+
+    # Span could be absent if the integration is disabled.
+    if span is None:
+        return
+    span.__exit__(None, None, None)
+
+    body = parsed.get("Body")
+    if not isinstance(body, StreamingBody):
+        return
+
+    streaming_span = span.start_child(
+        op=OP.HTTP_CLIENT_STREAM,
+        name=span.description,
+        origin=Boto3Integration.origin,
+    )
+
+    orig_read = body.read
+    orig_close = body.close
+
+    def sentry_streaming_body_read(*args, **kwargs):
+        # type: (*Any, **Any) -> bytes
+        try:
+            ret = orig_read(*args, **kwargs)
+            if not ret:
+                streaming_span.finish()
+            return ret
+        except Exception:
+            streaming_span.finish()
+            raise
+
+    body.read = sentry_streaming_body_read
+
+    def sentry_streaming_body_close(*args, **kwargs):
+        # type: (*Any, **Any) -> None
+        streaming_span.finish()
+        orig_close(*args, **kwargs)
+
+    body.close = sentry_streaming_body_close
+
+
+def _sentry_after_call_error(context, exception, **kwargs):
+    # type: (Dict[str, Any], Type[BaseException], **Any) -> None
+    span = context.pop("_sentrysdk_span", None)  # type: Optional[Span]
+
+    # Span could be absent if the integration is disabled.
+    if span is None:
+        return
+    span.__exit__(type(exception), exception, None)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/bottle.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/bottle.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a9fc41208b8cd6cbf82663ed19cceb6a23fed6c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/bottle.py
@@ -0,0 +1,221 @@
+import functools
+
+import sentry_sdk
+from sentry_sdk.tracing import SOURCE_FOR_STYLE
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    event_from_exception,
+    parse_version,
+    transaction_from_function,
+)
+from sentry_sdk.integrations import (
+    Integration,
+    DidNotEnable,
+    _DEFAULT_FAILED_REQUEST_STATUS_CODES,
+    _check_minimum_version,
+)
+from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware
+from sentry_sdk.integrations._wsgi_common import RequestExtractor
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from collections.abc import Set
+
+    from sentry_sdk.integrations.wsgi import _ScopedResponse
+    from typing import Any
+    from typing import Dict
+    from typing import Callable
+    from typing import Optional
+    from bottle import FileUpload, FormsDict, LocalRequest  # type: ignore
+
+    from sentry_sdk._types import EventProcessor, Event
+
+try:
+    from bottle import (
+        Bottle,
+        HTTPResponse,
+        Route,
+        request as bottle_request,
+        __version__ as BOTTLE_VERSION,
+    )
+except ImportError:
+    raise DidNotEnable("Bottle not installed")
+
+
+TRANSACTION_STYLE_VALUES = ("endpoint", "url")
+
+
+class BottleIntegration(Integration):
+    identifier = "bottle"
+    origin = f"auto.http.{identifier}"
+
+    transaction_style = ""
+
+    def __init__(
+        self,
+        transaction_style="endpoint",  # type: str
+        *,
+        failed_request_status_codes=_DEFAULT_FAILED_REQUEST_STATUS_CODES,  # type: Set[int]
+    ):
+        # type: (...) -> None
+
+        if transaction_style not in TRANSACTION_STYLE_VALUES:
+            raise ValueError(
+                "Invalid value for transaction_style: %s (must be in %s)"
+                % (transaction_style, TRANSACTION_STYLE_VALUES)
+            )
+        self.transaction_style = transaction_style
+        self.failed_request_status_codes = failed_request_status_codes
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        version = parse_version(BOTTLE_VERSION)
+        _check_minimum_version(BottleIntegration, version)
+
+        old_app = Bottle.__call__
+
+        @ensure_integration_enabled(BottleIntegration, old_app)
+        def sentry_patched_wsgi_app(self, environ, start_response):
+            # type: (Any, Dict[str, str], Callable[..., Any]) -> _ScopedResponse
+            middleware = SentryWsgiMiddleware(
+                lambda *a, **kw: old_app(self, *a, **kw),
+                span_origin=BottleIntegration.origin,
+            )
+
+            return middleware(environ, start_response)
+
+        Bottle.__call__ = sentry_patched_wsgi_app
+
+        old_handle = Bottle._handle
+
+        @functools.wraps(old_handle)
+        def _patched_handle(self, environ):
+            # type: (Bottle, Dict[str, Any]) -> Any
+            integration = sentry_sdk.get_client().get_integration(BottleIntegration)
+            if integration is None:
+                return old_handle(self, environ)
+
+            scope = sentry_sdk.get_isolation_scope()
+            scope._name = "bottle"
+            scope.add_event_processor(
+                _make_request_event_processor(self, bottle_request, integration)
+            )
+            res = old_handle(self, environ)
+
+            return res
+
+        Bottle._handle = _patched_handle
+
+        old_make_callback = Route._make_callback
+
+        @functools.wraps(old_make_callback)
+        def patched_make_callback(self, *args, **kwargs):
+            # type: (Route, *object, **object) -> Any
+            prepared_callback = old_make_callback(self, *args, **kwargs)
+
+            integration = sentry_sdk.get_client().get_integration(BottleIntegration)
+            if integration is None:
+                return prepared_callback
+
+            def wrapped_callback(*args, **kwargs):
+                # type: (*object, **object) -> Any
+                try:
+                    res = prepared_callback(*args, **kwargs)
+                except Exception as exception:
+                    _capture_exception(exception, handled=False)
+                    raise exception
+
+                if (
+                    isinstance(res, HTTPResponse)
+                    and res.status_code in integration.failed_request_status_codes
+                ):
+                    _capture_exception(res, handled=True)
+
+                return res
+
+            return wrapped_callback
+
+        Route._make_callback = patched_make_callback
+
+
+class BottleRequestExtractor(RequestExtractor):
+    def env(self):
+        # type: () -> Dict[str, str]
+        return self.request.environ
+
+    def cookies(self):
+        # type: () -> Dict[str, str]
+        return self.request.cookies
+
+    def raw_data(self):
+        # type: () -> bytes
+        return self.request.body.read()
+
+    def form(self):
+        # type: () -> FormsDict
+        if self.is_json():
+            return None
+        return self.request.forms.decode()
+
+    def files(self):
+        # type: () -> Optional[Dict[str, str]]
+        if self.is_json():
+            return None
+
+        return self.request.files
+
+    def size_of_file(self, file):
+        # type: (FileUpload) -> int
+        return file.content_length
+
+
+def _set_transaction_name_and_source(event, transaction_style, request):
+    # type: (Event, str, Any) -> None
+    name = ""
+
+    if transaction_style == "url":
+        try:
+            name = request.route.rule or ""
+        except RuntimeError:
+            pass
+
+    elif transaction_style == "endpoint":
+        try:
+            name = (
+                request.route.name
+                or transaction_from_function(request.route.callback)
+                or ""
+            )
+        except RuntimeError:
+            pass
+
+    event["transaction"] = name
+    event["transaction_info"] = {"source": SOURCE_FOR_STYLE[transaction_style]}
+
+
+def _make_request_event_processor(app, request, integration):
+    # type: (Bottle, LocalRequest, BottleIntegration) -> EventProcessor
+
+    def event_processor(event, hint):
+        # type: (Event, dict[str, Any]) -> Event
+        _set_transaction_name_and_source(event, integration.transaction_style, request)
+
+        with capture_internal_exceptions():
+            BottleRequestExtractor(request).extract_into_event(event)
+
+        return event
+
+    return event_processor
+
+
+def _capture_exception(exception, handled):
+    # type: (BaseException, bool) -> None
+    event, hint = event_from_exception(
+        exception,
+        client_options=sentry_sdk.get_client().options,
+        mechanism={"type": "bottle", "handled": handled},
+    )
+    sentry_sdk.capture_event(event, hint=hint)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/celery/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/celery/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5601fc0f95b5b0acf7df53780b016b89dd230d2
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/celery/__init__.py
@@ -0,0 +1,529 @@
+import sys
+from collections.abc import Mapping
+from functools import wraps
+
+import sentry_sdk
+from sentry_sdk import isolation_scope
+from sentry_sdk.api import continue_trace
+from sentry_sdk.consts import OP, SPANSTATUS, SPANDATA
+from sentry_sdk.integrations import _check_minimum_version, Integration, DidNotEnable
+from sentry_sdk.integrations.celery.beat import (
+    _patch_beat_apply_entry,
+    _patch_redbeat_apply_async,
+    _setup_celery_beat_signals,
+)
+from sentry_sdk.integrations.celery.utils import _now_seconds_since_epoch
+from sentry_sdk.integrations.logging import ignore_logger
+from sentry_sdk.tracing import BAGGAGE_HEADER_NAME, TransactionSource
+from sentry_sdk.tracing_utils import Baggage
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    event_from_exception,
+    reraise,
+)
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Callable
+    from typing import List
+    from typing import Optional
+    from typing import TypeVar
+    from typing import Union
+
+    from sentry_sdk._types import EventProcessor, Event, Hint, ExcInfo
+    from sentry_sdk.tracing import Span
+
+    F = TypeVar("F", bound=Callable[..., Any])
+
+
+try:
+    from celery import VERSION as CELERY_VERSION  # type: ignore
+    from celery.app.task import Task  # type: ignore
+    from celery.app.trace import task_has_custom
+    from celery.exceptions import (  # type: ignore
+        Ignore,
+        Reject,
+        Retry,
+        SoftTimeLimitExceeded,
+    )
+    from kombu import Producer  # type: ignore
+except ImportError:
+    raise DidNotEnable("Celery not installed")
+
+
+CELERY_CONTROL_FLOW_EXCEPTIONS = (Retry, Ignore, Reject)
+
+
+class CeleryIntegration(Integration):
+    identifier = "celery"
+    origin = f"auto.queue.{identifier}"
+
+    def __init__(
+        self,
+        propagate_traces=True,
+        monitor_beat_tasks=False,
+        exclude_beat_tasks=None,
+    ):
+        # type: (bool, bool, Optional[List[str]]) -> None
+        self.propagate_traces = propagate_traces
+        self.monitor_beat_tasks = monitor_beat_tasks
+        self.exclude_beat_tasks = exclude_beat_tasks
+
+        _patch_beat_apply_entry()
+        _patch_redbeat_apply_async()
+        _setup_celery_beat_signals(monitor_beat_tasks)
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        _check_minimum_version(CeleryIntegration, CELERY_VERSION)
+
+        _patch_build_tracer()
+        _patch_task_apply_async()
+        _patch_celery_send_task()
+        _patch_worker_exit()
+        _patch_producer_publish()
+
+        # This logger logs every status of every task that ran on the worker.
+        # Meaning that every task's breadcrumbs are full of stuff like "Task
+        #  raised unexpected ".
+        ignore_logger("celery.worker.job")
+        ignore_logger("celery.app.trace")
+
+        # This is stdout/err redirected to a logger, can't deal with this
+        # (need event_level=logging.WARN to reproduce)
+        ignore_logger("celery.redirected")
+
+
+def _set_status(status):
+    # type: (str) -> None
+    with capture_internal_exceptions():
+        scope = sentry_sdk.get_current_scope()
+        if scope.span is not None:
+            scope.span.set_status(status)
+
+
+def _capture_exception(task, exc_info):
+    # type: (Any, ExcInfo) -> None
+    client = sentry_sdk.get_client()
+    if client.get_integration(CeleryIntegration) is None:
+        return
+
+    if isinstance(exc_info[1], CELERY_CONTROL_FLOW_EXCEPTIONS):
+        # ??? Doesn't map to anything
+        _set_status("aborted")
+        return
+
+    _set_status("internal_error")
+
+    if hasattr(task, "throws") and isinstance(exc_info[1], task.throws):
+        return
+
+    event, hint = event_from_exception(
+        exc_info,
+        client_options=client.options,
+        mechanism={"type": "celery", "handled": False},
+    )
+
+    sentry_sdk.capture_event(event, hint=hint)
+
+
+def _make_event_processor(task, uuid, args, kwargs, request=None):
+    # type: (Any, Any, Any, Any, Optional[Any]) -> EventProcessor
+    def event_processor(event, hint):
+        # type: (Event, Hint) -> Optional[Event]
+
+        with capture_internal_exceptions():
+            tags = event.setdefault("tags", {})
+            tags["celery_task_id"] = uuid
+            extra = event.setdefault("extra", {})
+            extra["celery-job"] = {
+                "task_name": task.name,
+                "args": args,
+                "kwargs": kwargs,
+            }
+
+        if "exc_info" in hint:
+            with capture_internal_exceptions():
+                if issubclass(hint["exc_info"][0], SoftTimeLimitExceeded):
+                    event["fingerprint"] = [
+                        "celery",
+                        "SoftTimeLimitExceeded",
+                        getattr(task, "name", task),
+                    ]
+
+        return event
+
+    return event_processor
+
+
+def _update_celery_task_headers(original_headers, span, monitor_beat_tasks):
+    # type: (dict[str, Any], Optional[Span], bool) -> dict[str, Any]
+    """
+    Updates the headers of the Celery task with the tracing information
+    and eventually Sentry Crons monitoring information for beat tasks.
+    """
+    updated_headers = original_headers.copy()
+    with capture_internal_exceptions():
+        # if span is None (when the task was started by Celery Beat)
+        # this will return the trace headers from the scope.
+        headers = dict(
+            sentry_sdk.get_isolation_scope().iter_trace_propagation_headers(span=span)
+        )
+
+        if monitor_beat_tasks:
+            headers.update(
+                {
+                    "sentry-monitor-start-timestamp-s": "%.9f"
+                    % _now_seconds_since_epoch(),
+                }
+            )
+
+        # Add the time the task was enqueued to the headers
+        # This is used in the consumer to calculate the latency
+        updated_headers.update(
+            {"sentry-task-enqueued-time": _now_seconds_since_epoch()}
+        )
+
+        if headers:
+            existing_baggage = updated_headers.get(BAGGAGE_HEADER_NAME)
+            sentry_baggage = headers.get(BAGGAGE_HEADER_NAME)
+
+            combined_baggage = sentry_baggage or existing_baggage
+            if sentry_baggage and existing_baggage:
+                # Merge incoming and sentry baggage, where the sentry trace information
+                # in the incoming baggage takes precedence and the third-party items
+                # are concatenated.
+                incoming = Baggage.from_incoming_header(existing_baggage)
+                combined = Baggage.from_incoming_header(sentry_baggage)
+                combined.sentry_items.update(incoming.sentry_items)
+                combined.third_party_items = ",".join(
+                    [
+                        x
+                        for x in [
+                            combined.third_party_items,
+                            incoming.third_party_items,
+                        ]
+                        if x is not None and x != ""
+                    ]
+                )
+                combined_baggage = combined.serialize(include_third_party=True)
+
+            updated_headers.update(headers)
+            if combined_baggage:
+                updated_headers[BAGGAGE_HEADER_NAME] = combined_baggage
+
+            # https://github.com/celery/celery/issues/4875
+            #
+            # Need to setdefault the inner headers too since other
+            # tracing tools (dd-trace-py) also employ this exact
+            # workaround and we don't want to break them.
+            updated_headers.setdefault("headers", {}).update(headers)
+            if combined_baggage:
+                updated_headers["headers"][BAGGAGE_HEADER_NAME] = combined_baggage
+
+            # Add the Sentry options potentially added in `sentry_apply_entry`
+            # to the headers (done when auto-instrumenting Celery Beat tasks)
+            for key, value in updated_headers.items():
+                if key.startswith("sentry-"):
+                    updated_headers["headers"][key] = value
+
+    return updated_headers
+
+
+class NoOpMgr:
+    def __enter__(self):
+        # type: () -> None
+        return None
+
+    def __exit__(self, exc_type, exc_value, traceback):
+        # type: (Any, Any, Any) -> None
+        return None
+
+
+def _wrap_task_run(f):
+    # type: (F) -> F
+    @wraps(f)
+    def apply_async(*args, **kwargs):
+        # type: (*Any, **Any) -> Any
+        # Note: kwargs can contain headers=None, so no setdefault!
+        # Unsure which backend though.
+        integration = sentry_sdk.get_client().get_integration(CeleryIntegration)
+        if integration is None:
+            return f(*args, **kwargs)
+
+        kwarg_headers = kwargs.get("headers") or {}
+        propagate_traces = kwarg_headers.pop(
+            "sentry-propagate-traces", integration.propagate_traces
+        )
+
+        if not propagate_traces:
+            return f(*args, **kwargs)
+
+        if isinstance(args[0], Task):
+            task_name = args[0].name  # type: str
+        elif len(args) > 1 and isinstance(args[1], str):
+            task_name = args[1]
+        else:
+            task_name = ""
+
+        task_started_from_beat = sentry_sdk.get_isolation_scope()._name == "celery-beat"
+
+        span_mgr = (
+            sentry_sdk.start_span(
+                op=OP.QUEUE_SUBMIT_CELERY,
+                name=task_name,
+                origin=CeleryIntegration.origin,
+            )
+            if not task_started_from_beat
+            else NoOpMgr()
+        )  # type: Union[Span, NoOpMgr]
+
+        with span_mgr as span:
+            kwargs["headers"] = _update_celery_task_headers(
+                kwarg_headers, span, integration.monitor_beat_tasks
+            )
+            return f(*args, **kwargs)
+
+    return apply_async  # type: ignore
+
+
+def _wrap_tracer(task, f):
+    # type: (Any, F) -> F
+
+    # Need to wrap tracer for pushing the scope before prerun is sent, and
+    # popping it after postrun is sent.
+    #
+    # This is the reason we don't use signals for hooking in the first place.
+    # Also because in Celery 3, signal dispatch returns early if one handler
+    # crashes.
+    @wraps(f)
+    @ensure_integration_enabled(CeleryIntegration, f)
+    def _inner(*args, **kwargs):
+        # type: (*Any, **Any) -> Any
+        with isolation_scope() as scope:
+            scope._name = "celery"
+            scope.clear_breadcrumbs()
+            scope.add_event_processor(_make_event_processor(task, *args, **kwargs))
+
+            transaction = None
+
+            # Celery task objects are not a thing to be trusted. Even
+            # something such as attribute access can fail.
+            with capture_internal_exceptions():
+                headers = args[3].get("headers") or {}
+                transaction = continue_trace(
+                    headers,
+                    op=OP.QUEUE_TASK_CELERY,
+                    name="unknown celery task",
+                    source=TransactionSource.TASK,
+                    origin=CeleryIntegration.origin,
+                )
+                transaction.name = task.name
+                transaction.set_status(SPANSTATUS.OK)
+
+            if transaction is None:
+                return f(*args, **kwargs)
+
+            with sentry_sdk.start_transaction(
+                transaction,
+                custom_sampling_context={
+                    "celery_job": {
+                        "task": task.name,
+                        # for some reason, args[1] is a list if non-empty but a
+                        # tuple if empty
+                        "args": list(args[1]),
+                        "kwargs": args[2],
+                    }
+                },
+            ):
+                return f(*args, **kwargs)
+
+    return _inner  # type: ignore
+
+
+def _set_messaging_destination_name(task, span):
+    # type: (Any, Span) -> None
+    """Set "messaging.destination.name" tag for span"""
+    with capture_internal_exceptions():
+        delivery_info = task.request.delivery_info
+        if delivery_info:
+            routing_key = delivery_info.get("routing_key")
+            if delivery_info.get("exchange") == "" and routing_key is not None:
+                # Empty exchange indicates the default exchange, meaning the tasks
+                # are sent to the queue with the same name as the routing key.
+                span.set_data(SPANDATA.MESSAGING_DESTINATION_NAME, routing_key)
+
+
+def _wrap_task_call(task, f):
+    # type: (Any, F) -> F
+
+    # Need to wrap task call because the exception is caught before we get to
+    # see it. Also celery's reported stacktrace is untrustworthy.
+
+    # functools.wraps is important here because celery-once looks at this
+    # method's name. @ensure_integration_enabled internally calls functools.wraps,
+    # but if we ever remove the @ensure_integration_enabled decorator, we need
+    # to add @functools.wraps(f) here.
+    # https://github.com/getsentry/sentry-python/issues/421
+    @ensure_integration_enabled(CeleryIntegration, f)
+    def _inner(*args, **kwargs):
+        # type: (*Any, **Any) -> Any
+        try:
+            with sentry_sdk.start_span(
+                op=OP.QUEUE_PROCESS,
+                name=task.name,
+                origin=CeleryIntegration.origin,
+            ) as span:
+                _set_messaging_destination_name(task, span)
+
+                latency = None
+                with capture_internal_exceptions():
+                    if (
+                        task.request.headers is not None
+                        and "sentry-task-enqueued-time" in task.request.headers
+                    ):
+                        latency = _now_seconds_since_epoch() - task.request.headers.pop(
+                            "sentry-task-enqueued-time"
+                        )
+
+                if latency is not None:
+                    latency *= 1000  # milliseconds
+                    span.set_data(SPANDATA.MESSAGING_MESSAGE_RECEIVE_LATENCY, latency)
+
+                with capture_internal_exceptions():
+                    span.set_data(SPANDATA.MESSAGING_MESSAGE_ID, task.request.id)
+
+                with capture_internal_exceptions():
+                    span.set_data(
+                        SPANDATA.MESSAGING_MESSAGE_RETRY_COUNT, task.request.retries
+                    )
+
+                with capture_internal_exceptions():
+                    span.set_data(
+                        SPANDATA.MESSAGING_SYSTEM,
+                        task.app.connection().transport.driver_type,
+                    )
+
+                return f(*args, **kwargs)
+        except Exception:
+            exc_info = sys.exc_info()
+            with capture_internal_exceptions():
+                _capture_exception(task, exc_info)
+            reraise(*exc_info)
+
+    return _inner  # type: ignore
+
+
+def _patch_build_tracer():
+    # type: () -> None
+    import celery.app.trace as trace  # type: ignore
+
+    original_build_tracer = trace.build_tracer
+
+    def sentry_build_tracer(name, task, *args, **kwargs):
+        # type: (Any, Any, *Any, **Any) -> Any
+        if not getattr(task, "_sentry_is_patched", False):
+            # determine whether Celery will use __call__ or run and patch
+            # accordingly
+            if task_has_custom(task, "__call__"):
+                type(task).__call__ = _wrap_task_call(task, type(task).__call__)
+            else:
+                task.run = _wrap_task_call(task, task.run)
+
+            # `build_tracer` is apparently called for every task
+            # invocation. Can't wrap every celery task for every invocation
+            # or we will get infinitely nested wrapper functions.
+            task._sentry_is_patched = True
+
+        return _wrap_tracer(task, original_build_tracer(name, task, *args, **kwargs))
+
+    trace.build_tracer = sentry_build_tracer
+
+
+def _patch_task_apply_async():
+    # type: () -> None
+    Task.apply_async = _wrap_task_run(Task.apply_async)
+
+
+def _patch_celery_send_task():
+    # type: () -> None
+    from celery import Celery
+
+    Celery.send_task = _wrap_task_run(Celery.send_task)
+
+
+def _patch_worker_exit():
+    # type: () -> None
+
+    # Need to flush queue before worker shutdown because a crashing worker will
+    # call os._exit
+    from billiard.pool import Worker  # type: ignore
+
+    original_workloop = Worker.workloop
+
+    def sentry_workloop(*args, **kwargs):
+        # type: (*Any, **Any) -> Any
+        try:
+            return original_workloop(*args, **kwargs)
+        finally:
+            with capture_internal_exceptions():
+                if (
+                    sentry_sdk.get_client().get_integration(CeleryIntegration)
+                    is not None
+                ):
+                    sentry_sdk.flush()
+
+    Worker.workloop = sentry_workloop
+
+
+def _patch_producer_publish():
+    # type: () -> None
+    original_publish = Producer.publish
+
+    @ensure_integration_enabled(CeleryIntegration, original_publish)
+    def sentry_publish(self, *args, **kwargs):
+        # type: (Producer, *Any, **Any) -> Any
+        kwargs_headers = kwargs.get("headers", {})
+        if not isinstance(kwargs_headers, Mapping):
+            # Ensure kwargs_headers is a Mapping, so we can safely call get().
+            # We don't expect this to happen, but it's better to be safe. Even
+            # if it does happen, only our instrumentation breaks. This line
+            # does not overwrite kwargs["headers"], so the original publish
+            # method will still work.
+            kwargs_headers = {}
+
+        task_name = kwargs_headers.get("task")
+        task_id = kwargs_headers.get("id")
+        retries = kwargs_headers.get("retries")
+
+        routing_key = kwargs.get("routing_key")
+        exchange = kwargs.get("exchange")
+
+        with sentry_sdk.start_span(
+            op=OP.QUEUE_PUBLISH,
+            name=task_name,
+            origin=CeleryIntegration.origin,
+        ) as span:
+            if task_id is not None:
+                span.set_data(SPANDATA.MESSAGING_MESSAGE_ID, task_id)
+
+            if exchange == "" and routing_key is not None:
+                # Empty exchange indicates the default exchange, meaning messages are
+                # routed to the queue with the same name as the routing key.
+                span.set_data(SPANDATA.MESSAGING_DESTINATION_NAME, routing_key)
+
+            if retries is not None:
+                span.set_data(SPANDATA.MESSAGING_MESSAGE_RETRY_COUNT, retries)
+
+            with capture_internal_exceptions():
+                span.set_data(
+                    SPANDATA.MESSAGING_SYSTEM, self.connection.transport.driver_type
+                )
+
+            return original_publish(self, *args, **kwargs)
+
+    Producer.publish = sentry_publish
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/celery/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/celery/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..53b04429775973a503b3009193a617e5e3307d35
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/celery/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/celery/__pycache__/beat.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/celery/__pycache__/beat.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1fe929192f4f9fef21e65d27c7cb289d226307dd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/celery/__pycache__/beat.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/celery/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/celery/__pycache__/utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c99f0ff5ec55dfffaa74ee259296ca947bee5850
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/celery/__pycache__/utils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/celery/beat.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/celery/beat.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b7e45e6f0419e3f4618c96291f666e992a3113d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/celery/beat.py
@@ -0,0 +1,293 @@
+import sentry_sdk
+from sentry_sdk.crons import capture_checkin, MonitorStatus
+from sentry_sdk.integrations import DidNotEnable
+from sentry_sdk.integrations.celery.utils import (
+    _get_humanized_interval,
+    _now_seconds_since_epoch,
+)
+from sentry_sdk.utils import (
+    logger,
+    match_regex_list,
+)
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from collections.abc import Callable
+    from typing import Any, Optional, TypeVar, Union
+    from sentry_sdk._types import (
+        MonitorConfig,
+        MonitorConfigScheduleType,
+        MonitorConfigScheduleUnit,
+    )
+
+    F = TypeVar("F", bound=Callable[..., Any])
+
+
+try:
+    from celery import Task, Celery  # type: ignore
+    from celery.beat import Scheduler  # type: ignore
+    from celery.schedules import crontab, schedule  # type: ignore
+    from celery.signals import (  # type: ignore
+        task_failure,
+        task_success,
+        task_retry,
+    )
+except ImportError:
+    raise DidNotEnable("Celery not installed")
+
+try:
+    from redbeat.schedulers import RedBeatScheduler  # type: ignore
+except ImportError:
+    RedBeatScheduler = None
+
+
+def _get_headers(task):
+    # type: (Task) -> dict[str, Any]
+    headers = task.request.get("headers") or {}
+
+    # flatten nested headers
+    if "headers" in headers:
+        headers.update(headers["headers"])
+        del headers["headers"]
+
+    headers.update(task.request.get("properties") or {})
+
+    return headers
+
+
+def _get_monitor_config(celery_schedule, app, monitor_name):
+    # type: (Any, Celery, str) -> MonitorConfig
+    monitor_config = {}  # type: MonitorConfig
+    schedule_type = None  # type: Optional[MonitorConfigScheduleType]
+    schedule_value = None  # type: Optional[Union[str, int]]
+    schedule_unit = None  # type: Optional[MonitorConfigScheduleUnit]
+
+    if isinstance(celery_schedule, crontab):
+        schedule_type = "crontab"
+        schedule_value = (
+            "{0._orig_minute} "
+            "{0._orig_hour} "
+            "{0._orig_day_of_month} "
+            "{0._orig_month_of_year} "
+            "{0._orig_day_of_week}".format(celery_schedule)
+        )
+    elif isinstance(celery_schedule, schedule):
+        schedule_type = "interval"
+        (schedule_value, schedule_unit) = _get_humanized_interval(
+            celery_schedule.seconds
+        )
+
+        if schedule_unit == "second":
+            logger.warning(
+                "Intervals shorter than one minute are not supported by Sentry Crons. Monitor '%s' has an interval of %s seconds. Use the `exclude_beat_tasks` option in the celery integration to exclude it.",
+                monitor_name,
+                schedule_value,
+            )
+            return {}
+
+    else:
+        logger.warning(
+            "Celery schedule type '%s' not supported by Sentry Crons.",
+            type(celery_schedule),
+        )
+        return {}
+
+    monitor_config["schedule"] = {}
+    monitor_config["schedule"]["type"] = schedule_type
+    monitor_config["schedule"]["value"] = schedule_value
+
+    if schedule_unit is not None:
+        monitor_config["schedule"]["unit"] = schedule_unit
+
+    monitor_config["timezone"] = (
+        (
+            hasattr(celery_schedule, "tz")
+            and celery_schedule.tz is not None
+            and str(celery_schedule.tz)
+        )
+        or app.timezone
+        or "UTC"
+    )
+
+    return monitor_config
+
+
+def _apply_crons_data_to_schedule_entry(scheduler, schedule_entry, integration):
+    # type: (Any, Any, sentry_sdk.integrations.celery.CeleryIntegration) -> None
+    """
+    Add Sentry Crons information to the schedule_entry headers.
+    """
+    if not integration.monitor_beat_tasks:
+        return
+
+    monitor_name = schedule_entry.name
+
+    task_should_be_excluded = match_regex_list(
+        monitor_name, integration.exclude_beat_tasks
+    )
+    if task_should_be_excluded:
+        return
+
+    celery_schedule = schedule_entry.schedule
+    app = scheduler.app
+
+    monitor_config = _get_monitor_config(celery_schedule, app, monitor_name)
+
+    is_supported_schedule = bool(monitor_config)
+    if not is_supported_schedule:
+        return
+
+    headers = schedule_entry.options.pop("headers", {})
+    headers.update(
+        {
+            "sentry-monitor-slug": monitor_name,
+            "sentry-monitor-config": monitor_config,
+        }
+    )
+
+    check_in_id = capture_checkin(
+        monitor_slug=monitor_name,
+        monitor_config=monitor_config,
+        status=MonitorStatus.IN_PROGRESS,
+    )
+    headers.update({"sentry-monitor-check-in-id": check_in_id})
+
+    # Set the Sentry configuration in the options of the ScheduleEntry.
+    # Those will be picked up in `apply_async` and added to the headers.
+    schedule_entry.options["headers"] = headers
+
+
+def _wrap_beat_scheduler(original_function):
+    # type: (Callable[..., Any]) -> Callable[..., Any]
+    """
+    Makes sure that:
+    - a new Sentry trace is started for each task started by Celery Beat and
+      it is propagated to the task.
+    - the Sentry Crons information is set in the Celery Beat task's
+      headers so that is is monitored with Sentry Crons.
+
+    After the patched function is called,
+    Celery Beat will call apply_async to put the task in the queue.
+    """
+    # Patch only once
+    # Can't use __name__ here, because some of our tests mock original_apply_entry
+    already_patched = "sentry_patched_scheduler" in str(original_function)
+    if already_patched:
+        return original_function
+
+    from sentry_sdk.integrations.celery import CeleryIntegration
+
+    def sentry_patched_scheduler(*args, **kwargs):
+        # type: (*Any, **Any) -> None
+        integration = sentry_sdk.get_client().get_integration(CeleryIntegration)
+        if integration is None:
+            return original_function(*args, **kwargs)
+
+        # Tasks started by Celery Beat start a new Trace
+        scope = sentry_sdk.get_isolation_scope()
+        scope.set_new_propagation_context()
+        scope._name = "celery-beat"
+
+        scheduler, schedule_entry = args
+        _apply_crons_data_to_schedule_entry(scheduler, schedule_entry, integration)
+
+        return original_function(*args, **kwargs)
+
+    return sentry_patched_scheduler
+
+
+def _patch_beat_apply_entry():
+    # type: () -> None
+    Scheduler.apply_entry = _wrap_beat_scheduler(Scheduler.apply_entry)
+
+
+def _patch_redbeat_apply_async():
+    # type: () -> None
+    if RedBeatScheduler is None:
+        return
+
+    RedBeatScheduler.apply_async = _wrap_beat_scheduler(RedBeatScheduler.apply_async)
+
+
+def _setup_celery_beat_signals(monitor_beat_tasks):
+    # type: (bool) -> None
+    if monitor_beat_tasks:
+        task_success.connect(crons_task_success)
+        task_failure.connect(crons_task_failure)
+        task_retry.connect(crons_task_retry)
+
+
+def crons_task_success(sender, **kwargs):
+    # type: (Task, dict[Any, Any]) -> None
+    logger.debug("celery_task_success %s", sender)
+    headers = _get_headers(sender)
+
+    if "sentry-monitor-slug" not in headers:
+        return
+
+    monitor_config = headers.get("sentry-monitor-config", {})
+
+    start_timestamp_s = headers.get("sentry-monitor-start-timestamp-s")
+
+    capture_checkin(
+        monitor_slug=headers["sentry-monitor-slug"],
+        monitor_config=monitor_config,
+        check_in_id=headers["sentry-monitor-check-in-id"],
+        duration=(
+            _now_seconds_since_epoch() - float(start_timestamp_s)
+            if start_timestamp_s
+            else None
+        ),
+        status=MonitorStatus.OK,
+    )
+
+
+def crons_task_failure(sender, **kwargs):
+    # type: (Task, dict[Any, Any]) -> None
+    logger.debug("celery_task_failure %s", sender)
+    headers = _get_headers(sender)
+
+    if "sentry-monitor-slug" not in headers:
+        return
+
+    monitor_config = headers.get("sentry-monitor-config", {})
+
+    start_timestamp_s = headers.get("sentry-monitor-start-timestamp-s")
+
+    capture_checkin(
+        monitor_slug=headers["sentry-monitor-slug"],
+        monitor_config=monitor_config,
+        check_in_id=headers["sentry-monitor-check-in-id"],
+        duration=(
+            _now_seconds_since_epoch() - float(start_timestamp_s)
+            if start_timestamp_s
+            else None
+        ),
+        status=MonitorStatus.ERROR,
+    )
+
+
+def crons_task_retry(sender, **kwargs):
+    # type: (Task, dict[Any, Any]) -> None
+    logger.debug("celery_task_retry %s", sender)
+    headers = _get_headers(sender)
+
+    if "sentry-monitor-slug" not in headers:
+        return
+
+    monitor_config = headers.get("sentry-monitor-config", {})
+
+    start_timestamp_s = headers.get("sentry-monitor-start-timestamp-s")
+
+    capture_checkin(
+        monitor_slug=headers["sentry-monitor-slug"],
+        monitor_config=monitor_config,
+        check_in_id=headers["sentry-monitor-check-in-id"],
+        duration=(
+            _now_seconds_since_epoch() - float(start_timestamp_s)
+            if start_timestamp_s
+            else None
+        ),
+        status=MonitorStatus.ERROR,
+    )
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/celery/utils.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/celery/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1961b15bc8fe3433f59494d9cccbe8cfe21bc12
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/celery/utils.py
@@ -0,0 +1,43 @@
+import time
+from typing import TYPE_CHECKING, cast
+
+if TYPE_CHECKING:
+    from typing import Any, Tuple
+    from sentry_sdk._types import MonitorConfigScheduleUnit
+
+
+def _now_seconds_since_epoch():
+    # type: () -> float
+    # We cannot use `time.perf_counter()` when dealing with the duration
+    # of a Celery task, because the start of a Celery task and
+    # the end are recorded in different processes.
+    # Start happens in the Celery Beat process,
+    # the end in a Celery Worker process.
+    return time.time()
+
+
+def _get_humanized_interval(seconds):
+    # type: (float) -> Tuple[int, MonitorConfigScheduleUnit]
+    TIME_UNITS = (  # noqa: N806
+        ("day", 60 * 60 * 24.0),
+        ("hour", 60 * 60.0),
+        ("minute", 60.0),
+    )
+
+    seconds = float(seconds)
+    for unit, divider in TIME_UNITS:
+        if seconds >= divider:
+            interval = int(seconds / divider)
+            return (interval, cast("MonitorConfigScheduleUnit", unit))
+
+    return (int(seconds), "second")
+
+
+class NoOpMgr:
+    def __enter__(self):
+        # type: () -> None
+        return None
+
+    def __exit__(self, exc_type, exc_value, traceback):
+        # type: (Any, Any, Any) -> None
+        return None
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/chalice.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/chalice.py
new file mode 100644
index 0000000000000000000000000000000000000000..947e41ebf7cdee54ab6cd1e3b2dc5055ad3f168b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/chalice.py
@@ -0,0 +1,134 @@
+import sys
+from functools import wraps
+
+import sentry_sdk
+from sentry_sdk.integrations import Integration, DidNotEnable
+from sentry_sdk.integrations.aws_lambda import _make_request_event_processor
+from sentry_sdk.tracing import TransactionSource
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    event_from_exception,
+    parse_version,
+    reraise,
+)
+
+try:
+    import chalice  # type: ignore
+    from chalice import __version__ as CHALICE_VERSION
+    from chalice import Chalice, ChaliceViewError
+    from chalice.app import EventSourceHandler as ChaliceEventSourceHandler  # type: ignore
+except ImportError:
+    raise DidNotEnable("Chalice is not installed")
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Dict
+    from typing import TypeVar
+    from typing import Callable
+
+    F = TypeVar("F", bound=Callable[..., Any])
+
+
+class EventSourceHandler(ChaliceEventSourceHandler):  # type: ignore
+    def __call__(self, event, context):
+        # type: (Any, Any) -> Any
+        client = sentry_sdk.get_client()
+
+        with sentry_sdk.isolation_scope() as scope:
+            with capture_internal_exceptions():
+                configured_time = context.get_remaining_time_in_millis()
+                scope.add_event_processor(
+                    _make_request_event_processor(event, context, configured_time)
+                )
+            try:
+                return ChaliceEventSourceHandler.__call__(self, event, context)
+            except Exception:
+                exc_info = sys.exc_info()
+                event, hint = event_from_exception(
+                    exc_info,
+                    client_options=client.options,
+                    mechanism={"type": "chalice", "handled": False},
+                )
+                sentry_sdk.capture_event(event, hint=hint)
+                client.flush()
+                reraise(*exc_info)
+
+
+def _get_view_function_response(app, view_function, function_args):
+    # type: (Any, F, Any) -> F
+    @wraps(view_function)
+    def wrapped_view_function(**function_args):
+        # type: (**Any) -> Any
+        client = sentry_sdk.get_client()
+        with sentry_sdk.isolation_scope() as scope:
+            with capture_internal_exceptions():
+                configured_time = app.lambda_context.get_remaining_time_in_millis()
+                scope.set_transaction_name(
+                    app.lambda_context.function_name,
+                    source=TransactionSource.COMPONENT,
+                )
+
+                scope.add_event_processor(
+                    _make_request_event_processor(
+                        app.current_request.to_dict(),
+                        app.lambda_context,
+                        configured_time,
+                    )
+                )
+            try:
+                return view_function(**function_args)
+            except Exception as exc:
+                if isinstance(exc, ChaliceViewError):
+                    raise
+                exc_info = sys.exc_info()
+                event, hint = event_from_exception(
+                    exc_info,
+                    client_options=client.options,
+                    mechanism={"type": "chalice", "handled": False},
+                )
+                sentry_sdk.capture_event(event, hint=hint)
+                client.flush()
+                raise
+
+    return wrapped_view_function  # type: ignore
+
+
+class ChaliceIntegration(Integration):
+    identifier = "chalice"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+
+        version = parse_version(CHALICE_VERSION)
+
+        if version is None:
+            raise DidNotEnable("Unparsable Chalice version: {}".format(CHALICE_VERSION))
+
+        if version < (1, 20):
+            old_get_view_function_response = Chalice._get_view_function_response
+        else:
+            from chalice.app import RestAPIEventHandler
+
+            old_get_view_function_response = (
+                RestAPIEventHandler._get_view_function_response
+            )
+
+        def sentry_event_response(app, view_function, function_args):
+            # type: (Any, F, Dict[str, Any]) -> Any
+            wrapped_view_function = _get_view_function_response(
+                app, view_function, function_args
+            )
+
+            return old_get_view_function_response(
+                app, wrapped_view_function, function_args
+            )
+
+        if version < (1, 20):
+            Chalice._get_view_function_response = sentry_event_response
+        else:
+            RestAPIEventHandler._get_view_function_response = sentry_event_response
+        # for everything else (like events)
+        chalice.app.EventSourceHandler = EventSourceHandler
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/clickhouse_driver.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/clickhouse_driver.py
new file mode 100644
index 0000000000000000000000000000000000000000..bbaaaeec8e16e855cbcb8134d647862adac114fc
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/clickhouse_driver.py
@@ -0,0 +1,177 @@
+import sentry_sdk
+from sentry_sdk.consts import OP, SPANDATA
+from sentry_sdk.integrations import _check_minimum_version, Integration, DidNotEnable
+from sentry_sdk.tracing import Span
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.utils import capture_internal_exceptions, ensure_integration_enabled
+
+from typing import TYPE_CHECKING, TypeVar
+
+# Hack to get new Python features working in older versions
+# without introducing a hard dependency on `typing_extensions`
+# from: https://stackoverflow.com/a/71944042/300572
+if TYPE_CHECKING:
+    from collections.abc import Iterator
+    from typing import Any, ParamSpec, Callable
+else:
+    # Fake ParamSpec
+    class ParamSpec:
+        def __init__(self, _):
+            self.args = None
+            self.kwargs = None
+
+    # Callable[anything] will return None
+    class _Callable:
+        def __getitem__(self, _):
+            return None
+
+    # Make instances
+    Callable = _Callable()
+
+
+try:
+    import clickhouse_driver  # type: ignore[import-not-found]
+
+except ImportError:
+    raise DidNotEnable("clickhouse-driver not installed.")
+
+
+class ClickhouseDriverIntegration(Integration):
+    identifier = "clickhouse_driver"
+    origin = f"auto.db.{identifier}"
+
+    @staticmethod
+    def setup_once() -> None:
+        _check_minimum_version(ClickhouseDriverIntegration, clickhouse_driver.VERSION)
+
+        # Every query is done using the Connection's `send_query` function
+        clickhouse_driver.connection.Connection.send_query = _wrap_start(
+            clickhouse_driver.connection.Connection.send_query
+        )
+
+        # If the query contains parameters then the send_data function is used to send those parameters to clickhouse
+        _wrap_send_data()
+
+        # Every query ends either with the Client's `receive_end_of_query` (no result expected)
+        # or its `receive_result` (result expected)
+        clickhouse_driver.client.Client.receive_end_of_query = _wrap_end(
+            clickhouse_driver.client.Client.receive_end_of_query
+        )
+        if hasattr(clickhouse_driver.client.Client, "receive_end_of_insert_query"):
+            # In 0.2.7, insert queries are handled separately via `receive_end_of_insert_query`
+            clickhouse_driver.client.Client.receive_end_of_insert_query = _wrap_end(
+                clickhouse_driver.client.Client.receive_end_of_insert_query
+            )
+        clickhouse_driver.client.Client.receive_result = _wrap_end(
+            clickhouse_driver.client.Client.receive_result
+        )
+
+
+P = ParamSpec("P")
+T = TypeVar("T")
+
+
+def _wrap_start(f: Callable[P, T]) -> Callable[P, T]:
+    @ensure_integration_enabled(ClickhouseDriverIntegration, f)
+    def _inner(*args: P.args, **kwargs: P.kwargs) -> T:
+        connection = args[0]
+        query = args[1]
+        query_id = args[2] if len(args) > 2 else kwargs.get("query_id")
+        params = args[3] if len(args) > 3 else kwargs.get("params")
+
+        span = sentry_sdk.start_span(
+            op=OP.DB,
+            name=query,
+            origin=ClickhouseDriverIntegration.origin,
+        )
+
+        connection._sentry_span = span  # type: ignore[attr-defined]
+
+        _set_db_data(span, connection)
+
+        span.set_data("query", query)
+
+        if query_id:
+            span.set_data("db.query_id", query_id)
+
+        if params and should_send_default_pii():
+            span.set_data("db.params", params)
+
+        # run the original code
+        ret = f(*args, **kwargs)
+
+        return ret
+
+    return _inner
+
+
+def _wrap_end(f: Callable[P, T]) -> Callable[P, T]:
+    def _inner_end(*args: P.args, **kwargs: P.kwargs) -> T:
+        res = f(*args, **kwargs)
+        instance = args[0]
+        span = getattr(instance.connection, "_sentry_span", None)  # type: ignore[attr-defined]
+
+        if span is not None:
+            if res is not None and should_send_default_pii():
+                span.set_data("db.result", res)
+
+            with capture_internal_exceptions():
+                span.scope.add_breadcrumb(
+                    message=span._data.pop("query"), category="query", data=span._data
+                )
+
+            span.finish()
+
+        return res
+
+    return _inner_end
+
+
+def _wrap_send_data() -> None:
+    original_send_data = clickhouse_driver.client.Client.send_data
+
+    def _inner_send_data(  # type: ignore[no-untyped-def] # clickhouse-driver does not type send_data
+        self, sample_block, data, types_check=False, columnar=False, *args, **kwargs
+    ):
+        span = getattr(self.connection, "_sentry_span", None)
+
+        if span is not None:
+            _set_db_data(span, self.connection)
+
+            if should_send_default_pii():
+                db_params = span._data.get("db.params", [])
+
+                if isinstance(data, (list, tuple)):
+                    db_params.extend(data)
+
+                else:  # data is a generic iterator
+                    orig_data = data
+
+                    # Wrap the generator to add items to db.params as they are yielded.
+                    # This allows us to send the params to Sentry without needing to allocate
+                    # memory for the entire generator at once.
+                    def wrapped_generator() -> "Iterator[Any]":
+                        for item in orig_data:
+                            db_params.append(item)
+                            yield item
+
+                    # Replace the original iterator with the wrapped one.
+                    data = wrapped_generator()
+
+                span.set_data("db.params", db_params)
+
+        return original_send_data(
+            self, sample_block, data, types_check, columnar, *args, **kwargs
+        )
+
+    clickhouse_driver.client.Client.send_data = _inner_send_data
+
+
+def _set_db_data(
+    span: Span, connection: clickhouse_driver.connection.Connection
+) -> None:
+    span.set_data(SPANDATA.DB_SYSTEM, "clickhouse")
+    span.set_data(SPANDATA.SERVER_ADDRESS, connection.host)
+    span.set_data(SPANDATA.SERVER_PORT, connection.port)
+    span.set_data(SPANDATA.DB_NAME, connection.database)
+    span.set_data(SPANDATA.DB_USER, connection.user)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/cloud_resource_context.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/cloud_resource_context.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca5ae47e6be7277f0db1e8a9322fbc7b04b2717d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/cloud_resource_context.py
@@ -0,0 +1,280 @@
+import json
+import urllib3
+
+from sentry_sdk.integrations import Integration
+from sentry_sdk.api import set_context
+from sentry_sdk.utils import logger
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Dict
+
+
+CONTEXT_TYPE = "cloud_resource"
+
+HTTP_TIMEOUT = 2.0
+
+AWS_METADATA_HOST = "169.254.169.254"
+AWS_TOKEN_URL = "http://{}/latest/api/token".format(AWS_METADATA_HOST)
+AWS_METADATA_URL = "http://{}/latest/dynamic/instance-identity/document".format(
+    AWS_METADATA_HOST
+)
+
+GCP_METADATA_HOST = "metadata.google.internal"
+GCP_METADATA_URL = "http://{}/computeMetadata/v1/?recursive=true".format(
+    GCP_METADATA_HOST
+)
+
+
+class CLOUD_PROVIDER:  # noqa: N801
+    """
+    Name of the cloud provider.
+    see https://opentelemetry.io/docs/reference/specification/resource/semantic_conventions/cloud/
+    """
+
+    ALIBABA = "alibaba_cloud"
+    AWS = "aws"
+    AZURE = "azure"
+    GCP = "gcp"
+    IBM = "ibm_cloud"
+    TENCENT = "tencent_cloud"
+
+
+class CLOUD_PLATFORM:  # noqa: N801
+    """
+    The cloud platform.
+    see https://opentelemetry.io/docs/reference/specification/resource/semantic_conventions/cloud/
+    """
+
+    AWS_EC2 = "aws_ec2"
+    GCP_COMPUTE_ENGINE = "gcp_compute_engine"
+
+
+class CloudResourceContextIntegration(Integration):
+    """
+    Adds cloud resource context to the Senty scope
+    """
+
+    identifier = "cloudresourcecontext"
+
+    cloud_provider = ""
+
+    aws_token = ""
+    http = urllib3.PoolManager(timeout=HTTP_TIMEOUT)
+
+    gcp_metadata = None
+
+    def __init__(self, cloud_provider=""):
+        # type: (str) -> None
+        CloudResourceContextIntegration.cloud_provider = cloud_provider
+
+    @classmethod
+    def _is_aws(cls):
+        # type: () -> bool
+        try:
+            r = cls.http.request(
+                "PUT",
+                AWS_TOKEN_URL,
+                headers={"X-aws-ec2-metadata-token-ttl-seconds": "60"},
+            )
+
+            if r.status != 200:
+                return False
+
+            cls.aws_token = r.data.decode()
+            return True
+
+        except urllib3.exceptions.TimeoutError:
+            logger.debug(
+                "AWS metadata service timed out after %s seconds", HTTP_TIMEOUT
+            )
+            return False
+        except Exception as e:
+            logger.debug("Error checking AWS metadata service: %s", str(e))
+            return False
+
+    @classmethod
+    def _get_aws_context(cls):
+        # type: () -> Dict[str, str]
+        ctx = {
+            "cloud.provider": CLOUD_PROVIDER.AWS,
+            "cloud.platform": CLOUD_PLATFORM.AWS_EC2,
+        }
+
+        try:
+            r = cls.http.request(
+                "GET",
+                AWS_METADATA_URL,
+                headers={"X-aws-ec2-metadata-token": cls.aws_token},
+            )
+
+            if r.status != 200:
+                return ctx
+
+            data = json.loads(r.data.decode("utf-8"))
+
+            try:
+                ctx["cloud.account.id"] = data["accountId"]
+            except Exception:
+                pass
+
+            try:
+                ctx["cloud.availability_zone"] = data["availabilityZone"]
+            except Exception:
+                pass
+
+            try:
+                ctx["cloud.region"] = data["region"]
+            except Exception:
+                pass
+
+            try:
+                ctx["host.id"] = data["instanceId"]
+            except Exception:
+                pass
+
+            try:
+                ctx["host.type"] = data["instanceType"]
+            except Exception:
+                pass
+
+        except urllib3.exceptions.TimeoutError:
+            logger.debug(
+                "AWS metadata service timed out after %s seconds", HTTP_TIMEOUT
+            )
+        except Exception as e:
+            logger.debug("Error fetching AWS metadata: %s", str(e))
+
+        return ctx
+
+    @classmethod
+    def _is_gcp(cls):
+        # type: () -> bool
+        try:
+            r = cls.http.request(
+                "GET",
+                GCP_METADATA_URL,
+                headers={"Metadata-Flavor": "Google"},
+            )
+
+            if r.status != 200:
+                return False
+
+            cls.gcp_metadata = json.loads(r.data.decode("utf-8"))
+            return True
+
+        except urllib3.exceptions.TimeoutError:
+            logger.debug(
+                "GCP metadata service timed out after %s seconds", HTTP_TIMEOUT
+            )
+            return False
+        except Exception as e:
+            logger.debug("Error checking GCP metadata service: %s", str(e))
+            return False
+
+    @classmethod
+    def _get_gcp_context(cls):
+        # type: () -> Dict[str, str]
+        ctx = {
+            "cloud.provider": CLOUD_PROVIDER.GCP,
+            "cloud.platform": CLOUD_PLATFORM.GCP_COMPUTE_ENGINE,
+        }
+
+        try:
+            if cls.gcp_metadata is None:
+                r = cls.http.request(
+                    "GET",
+                    GCP_METADATA_URL,
+                    headers={"Metadata-Flavor": "Google"},
+                )
+
+                if r.status != 200:
+                    return ctx
+
+                cls.gcp_metadata = json.loads(r.data.decode("utf-8"))
+
+            try:
+                ctx["cloud.account.id"] = cls.gcp_metadata["project"]["projectId"]
+            except Exception:
+                pass
+
+            try:
+                ctx["cloud.availability_zone"] = cls.gcp_metadata["instance"][
+                    "zone"
+                ].split("/")[-1]
+            except Exception:
+                pass
+
+            try:
+                # only populated in google cloud run
+                ctx["cloud.region"] = cls.gcp_metadata["instance"]["region"].split("/")[
+                    -1
+                ]
+            except Exception:
+                pass
+
+            try:
+                ctx["host.id"] = cls.gcp_metadata["instance"]["id"]
+            except Exception:
+                pass
+
+        except urllib3.exceptions.TimeoutError:
+            logger.debug(
+                "GCP metadata service timed out after %s seconds", HTTP_TIMEOUT
+            )
+        except Exception as e:
+            logger.debug("Error fetching GCP metadata: %s", str(e))
+
+        return ctx
+
+    @classmethod
+    def _get_cloud_provider(cls):
+        # type: () -> str
+        if cls._is_aws():
+            return CLOUD_PROVIDER.AWS
+
+        if cls._is_gcp():
+            return CLOUD_PROVIDER.GCP
+
+        return ""
+
+    @classmethod
+    def _get_cloud_resource_context(cls):
+        # type: () -> Dict[str, str]
+        cloud_provider = (
+            cls.cloud_provider
+            if cls.cloud_provider != ""
+            else CloudResourceContextIntegration._get_cloud_provider()
+        )
+        if cloud_provider in context_getters.keys():
+            return context_getters[cloud_provider]()
+
+        return {}
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        cloud_provider = CloudResourceContextIntegration.cloud_provider
+        unsupported_cloud_provider = (
+            cloud_provider != "" and cloud_provider not in context_getters.keys()
+        )
+
+        if unsupported_cloud_provider:
+            logger.warning(
+                "Invalid value for cloud_provider: %s (must be in %s). Falling back to autodetection...",
+                CloudResourceContextIntegration.cloud_provider,
+                list(context_getters.keys()),
+            )
+
+        context = CloudResourceContextIntegration._get_cloud_resource_context()
+        if context != {}:
+            set_context(CONTEXT_TYPE, context)
+
+
+# Map with the currently supported cloud providers
+# mapping to functions extracting the context
+context_getters = {
+    CLOUD_PROVIDER.AWS: CloudResourceContextIntegration._get_aws_context,
+    CLOUD_PROVIDER.GCP: CloudResourceContextIntegration._get_gcp_context,
+}
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/cohere.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/cohere.py
new file mode 100644
index 0000000000000000000000000000000000000000..57ffdb908ae97a62d2ec7e70a88b8d9754f421f7
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/cohere.py
@@ -0,0 +1,270 @@
+from functools import wraps
+
+from sentry_sdk import consts
+from sentry_sdk.ai.monitoring import record_token_usage
+from sentry_sdk.consts import SPANDATA
+from sentry_sdk.ai.utils import set_data_normalized
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Callable, Iterator
+    from sentry_sdk.tracing import Span
+
+import sentry_sdk
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.integrations import DidNotEnable, Integration
+from sentry_sdk.utils import capture_internal_exceptions, event_from_exception
+
+try:
+    from cohere.client import Client
+    from cohere.base_client import BaseCohere
+    from cohere import (
+        ChatStreamEndEvent,
+        NonStreamedChatResponse,
+    )
+
+    if TYPE_CHECKING:
+        from cohere import StreamedChatResponse
+except ImportError:
+    raise DidNotEnable("Cohere not installed")
+
+try:
+    # cohere 5.9.3+
+    from cohere import StreamEndStreamedChatResponse
+except ImportError:
+    from cohere import StreamedChatResponse_StreamEnd as StreamEndStreamedChatResponse
+
+
+COLLECTED_CHAT_PARAMS = {
+    "model": SPANDATA.AI_MODEL_ID,
+    "k": SPANDATA.AI_TOP_K,
+    "p": SPANDATA.AI_TOP_P,
+    "seed": SPANDATA.AI_SEED,
+    "frequency_penalty": SPANDATA.AI_FREQUENCY_PENALTY,
+    "presence_penalty": SPANDATA.AI_PRESENCE_PENALTY,
+    "raw_prompting": SPANDATA.AI_RAW_PROMPTING,
+}
+
+COLLECTED_PII_CHAT_PARAMS = {
+    "tools": SPANDATA.AI_TOOLS,
+    "preamble": SPANDATA.AI_PREAMBLE,
+}
+
+COLLECTED_CHAT_RESP_ATTRS = {
+    "generation_id": SPANDATA.AI_GENERATION_ID,
+    "is_search_required": SPANDATA.AI_SEARCH_REQUIRED,
+    "finish_reason": SPANDATA.AI_FINISH_REASON,
+}
+
+COLLECTED_PII_CHAT_RESP_ATTRS = {
+    "citations": SPANDATA.AI_CITATIONS,
+    "documents": SPANDATA.AI_DOCUMENTS,
+    "search_queries": SPANDATA.AI_SEARCH_QUERIES,
+    "search_results": SPANDATA.AI_SEARCH_RESULTS,
+    "tool_calls": SPANDATA.AI_TOOL_CALLS,
+}
+
+
+class CohereIntegration(Integration):
+    identifier = "cohere"
+    origin = f"auto.ai.{identifier}"
+
+    def __init__(self, include_prompts=True):
+        # type: (CohereIntegration, bool) -> None
+        self.include_prompts = include_prompts
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        BaseCohere.chat = _wrap_chat(BaseCohere.chat, streaming=False)
+        Client.embed = _wrap_embed(Client.embed)
+        BaseCohere.chat_stream = _wrap_chat(BaseCohere.chat_stream, streaming=True)
+
+
+def _capture_exception(exc):
+    # type: (Any) -> None
+    event, hint = event_from_exception(
+        exc,
+        client_options=sentry_sdk.get_client().options,
+        mechanism={"type": "cohere", "handled": False},
+    )
+    sentry_sdk.capture_event(event, hint=hint)
+
+
+def _wrap_chat(f, streaming):
+    # type: (Callable[..., Any], bool) -> Callable[..., Any]
+
+    def collect_chat_response_fields(span, res, include_pii):
+        # type: (Span, NonStreamedChatResponse, bool) -> None
+        if include_pii:
+            if hasattr(res, "text"):
+                set_data_normalized(
+                    span,
+                    SPANDATA.AI_RESPONSES,
+                    [res.text],
+                )
+            for pii_attr in COLLECTED_PII_CHAT_RESP_ATTRS:
+                if hasattr(res, pii_attr):
+                    set_data_normalized(span, "ai." + pii_attr, getattr(res, pii_attr))
+
+        for attr in COLLECTED_CHAT_RESP_ATTRS:
+            if hasattr(res, attr):
+                set_data_normalized(span, "ai." + attr, getattr(res, attr))
+
+        if hasattr(res, "meta"):
+            if hasattr(res.meta, "billed_units"):
+                record_token_usage(
+                    span,
+                    input_tokens=res.meta.billed_units.input_tokens,
+                    output_tokens=res.meta.billed_units.output_tokens,
+                )
+            elif hasattr(res.meta, "tokens"):
+                record_token_usage(
+                    span,
+                    input_tokens=res.meta.tokens.input_tokens,
+                    output_tokens=res.meta.tokens.output_tokens,
+                )
+
+            if hasattr(res.meta, "warnings"):
+                set_data_normalized(span, SPANDATA.AI_WARNINGS, res.meta.warnings)
+
+    @wraps(f)
+    def new_chat(*args, **kwargs):
+        # type: (*Any, **Any) -> Any
+        integration = sentry_sdk.get_client().get_integration(CohereIntegration)
+
+        if (
+            integration is None
+            or "message" not in kwargs
+            or not isinstance(kwargs.get("message"), str)
+        ):
+            return f(*args, **kwargs)
+
+        message = kwargs.get("message")
+
+        span = sentry_sdk.start_span(
+            op=consts.OP.COHERE_CHAT_COMPLETIONS_CREATE,
+            name="cohere.client.Chat",
+            origin=CohereIntegration.origin,
+        )
+        span.__enter__()
+        try:
+            res = f(*args, **kwargs)
+        except Exception as e:
+            _capture_exception(e)
+            span.__exit__(None, None, None)
+            raise e from None
+
+        with capture_internal_exceptions():
+            if should_send_default_pii() and integration.include_prompts:
+                set_data_normalized(
+                    span,
+                    SPANDATA.AI_INPUT_MESSAGES,
+                    list(
+                        map(
+                            lambda x: {
+                                "role": getattr(x, "role", "").lower(),
+                                "content": getattr(x, "message", ""),
+                            },
+                            kwargs.get("chat_history", []),
+                        )
+                    )
+                    + [{"role": "user", "content": message}],
+                )
+                for k, v in COLLECTED_PII_CHAT_PARAMS.items():
+                    if k in kwargs:
+                        set_data_normalized(span, v, kwargs[k])
+
+            for k, v in COLLECTED_CHAT_PARAMS.items():
+                if k in kwargs:
+                    set_data_normalized(span, v, kwargs[k])
+            set_data_normalized(span, SPANDATA.AI_STREAMING, False)
+
+            if streaming:
+                old_iterator = res
+
+                def new_iterator():
+                    # type: () -> Iterator[StreamedChatResponse]
+
+                    with capture_internal_exceptions():
+                        for x in old_iterator:
+                            if isinstance(x, ChatStreamEndEvent) or isinstance(
+                                x, StreamEndStreamedChatResponse
+                            ):
+                                collect_chat_response_fields(
+                                    span,
+                                    x.response,
+                                    include_pii=should_send_default_pii()
+                                    and integration.include_prompts,
+                                )
+                            yield x
+
+                    span.__exit__(None, None, None)
+
+                return new_iterator()
+            elif isinstance(res, NonStreamedChatResponse):
+                collect_chat_response_fields(
+                    span,
+                    res,
+                    include_pii=should_send_default_pii()
+                    and integration.include_prompts,
+                )
+                span.__exit__(None, None, None)
+            else:
+                set_data_normalized(span, "unknown_response", True)
+                span.__exit__(None, None, None)
+            return res
+
+    return new_chat
+
+
+def _wrap_embed(f):
+    # type: (Callable[..., Any]) -> Callable[..., Any]
+
+    @wraps(f)
+    def new_embed(*args, **kwargs):
+        # type: (*Any, **Any) -> Any
+        integration = sentry_sdk.get_client().get_integration(CohereIntegration)
+        if integration is None:
+            return f(*args, **kwargs)
+
+        with sentry_sdk.start_span(
+            op=consts.OP.COHERE_EMBEDDINGS_CREATE,
+            name="Cohere Embedding Creation",
+            origin=CohereIntegration.origin,
+        ) as span:
+            if "texts" in kwargs and (
+                should_send_default_pii() and integration.include_prompts
+            ):
+                if isinstance(kwargs["texts"], str):
+                    set_data_normalized(span, SPANDATA.AI_TEXTS, [kwargs["texts"]])
+                elif (
+                    isinstance(kwargs["texts"], list)
+                    and len(kwargs["texts"]) > 0
+                    and isinstance(kwargs["texts"][0], str)
+                ):
+                    set_data_normalized(
+                        span, SPANDATA.AI_INPUT_MESSAGES, kwargs["texts"]
+                    )
+
+            if "model" in kwargs:
+                set_data_normalized(span, SPANDATA.AI_MODEL_ID, kwargs["model"])
+            try:
+                res = f(*args, **kwargs)
+            except Exception as e:
+                _capture_exception(e)
+                raise e from None
+            if (
+                hasattr(res, "meta")
+                and hasattr(res.meta, "billed_units")
+                and hasattr(res.meta.billed_units, "input_tokens")
+            ):
+                record_token_usage(
+                    span,
+                    input_tokens=res.meta.billed_units.input_tokens,
+                    total_tokens=res.meta.billed_units.input_tokens,
+                )
+            return res
+
+    return new_embed
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/dedupe.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/dedupe.py
new file mode 100644
index 0000000000000000000000000000000000000000..a115e35292e3c40b57fc7e0b6ceec08536ee7028
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/dedupe.py
@@ -0,0 +1,51 @@
+import sentry_sdk
+from sentry_sdk.utils import ContextVar
+from sentry_sdk.integrations import Integration
+from sentry_sdk.scope import add_global_event_processor
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Optional
+
+    from sentry_sdk._types import Event, Hint
+
+
+class DedupeIntegration(Integration):
+    identifier = "dedupe"
+
+    def __init__(self):
+        # type: () -> None
+        self._last_seen = ContextVar("last-seen")
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        @add_global_event_processor
+        def processor(event, hint):
+            # type: (Event, Optional[Hint]) -> Optional[Event]
+            if hint is None:
+                return event
+
+            integration = sentry_sdk.get_client().get_integration(DedupeIntegration)
+            if integration is None:
+                return event
+
+            exc_info = hint.get("exc_info", None)
+            if exc_info is None:
+                return event
+
+            exc = exc_info[1]
+            if integration._last_seen.get(None) is exc:
+                return None
+            integration._last_seen.set(exc)
+            return event
+
+    @staticmethod
+    def reset_last_seen():
+        # type: () -> None
+        integration = sentry_sdk.get_client().get_integration(DedupeIntegration)
+        if integration is None:
+            return
+
+        integration._last_seen.set(None)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2041598fa08e4be678123575fa41e18436c023ea
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__init__.py
@@ -0,0 +1,758 @@
+import inspect
+import sys
+import threading
+import weakref
+from importlib import import_module
+
+import sentry_sdk
+from sentry_sdk.consts import OP, SPANDATA
+from sentry_sdk.scope import add_global_event_processor, should_send_default_pii
+from sentry_sdk.serializer import add_global_repr_processor, add_repr_sequence_type
+from sentry_sdk.tracing import SOURCE_FOR_STYLE, TransactionSource
+from sentry_sdk.tracing_utils import add_query_source, record_sql_queries
+from sentry_sdk.utils import (
+    AnnotatedValue,
+    HAS_REAL_CONTEXTVARS,
+    CONTEXTVARS_ERROR_MESSAGE,
+    SENSITIVE_DATA_SUBSTITUTE,
+    logger,
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    event_from_exception,
+    transaction_from_function,
+    walk_exception_chain,
+)
+from sentry_sdk.integrations import _check_minimum_version, Integration, DidNotEnable
+from sentry_sdk.integrations.logging import ignore_logger
+from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware
+from sentry_sdk.integrations._wsgi_common import (
+    DEFAULT_HTTP_METHODS_TO_CAPTURE,
+    RequestExtractor,
+)
+
+try:
+    from django import VERSION as DJANGO_VERSION
+    from django.conf import settings as django_settings
+    from django.core import signals
+    from django.conf import settings
+
+    try:
+        from django.urls import resolve
+    except ImportError:
+        from django.core.urlresolvers import resolve
+
+    try:
+        from django.urls import Resolver404
+    except ImportError:
+        from django.core.urlresolvers import Resolver404
+
+    # Only available in Django 3.0+
+    try:
+        from django.core.handlers.asgi import ASGIRequest
+    except Exception:
+        ASGIRequest = None
+
+except ImportError:
+    raise DidNotEnable("Django not installed")
+
+from sentry_sdk.integrations.django.transactions import LEGACY_RESOLVER
+from sentry_sdk.integrations.django.templates import (
+    get_template_frame_from_exception,
+    patch_templates,
+)
+from sentry_sdk.integrations.django.middleware import patch_django_middlewares
+from sentry_sdk.integrations.django.signals_handlers import patch_signals
+from sentry_sdk.integrations.django.views import patch_views
+
+if DJANGO_VERSION[:2] > (1, 8):
+    from sentry_sdk.integrations.django.caching import patch_caching
+else:
+    patch_caching = None  # type: ignore
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Callable
+    from typing import Dict
+    from typing import Optional
+    from typing import Union
+    from typing import List
+
+    from django.core.handlers.wsgi import WSGIRequest
+    from django.http.response import HttpResponse
+    from django.http.request import QueryDict
+    from django.utils.datastructures import MultiValueDict
+
+    from sentry_sdk.tracing import Span
+    from sentry_sdk.integrations.wsgi import _ScopedResponse
+    from sentry_sdk._types import Event, Hint, EventProcessor, NotImplementedType
+
+
+if DJANGO_VERSION < (1, 10):
+
+    def is_authenticated(request_user):
+        # type: (Any) -> bool
+        return request_user.is_authenticated()
+
+else:
+
+    def is_authenticated(request_user):
+        # type: (Any) -> bool
+        return request_user.is_authenticated
+
+
+TRANSACTION_STYLE_VALUES = ("function_name", "url")
+
+
+class DjangoIntegration(Integration):
+    """
+    Auto instrument a Django application.
+
+    :param transaction_style: How to derive transaction names. Either `"function_name"` or `"url"`. Defaults to `"url"`.
+    :param middleware_spans: Whether to create spans for middleware. Defaults to `True`.
+    :param signals_spans: Whether to create spans for signals. Defaults to `True`.
+    :param signals_denylist: A list of signals to ignore when creating spans.
+    :param cache_spans: Whether to create spans for cache operations. Defaults to `False`.
+    """
+
+    identifier = "django"
+    origin = f"auto.http.{identifier}"
+    origin_db = f"auto.db.{identifier}"
+
+    transaction_style = ""
+    middleware_spans = None
+    signals_spans = None
+    cache_spans = None
+    signals_denylist = []  # type: list[signals.Signal]
+
+    def __init__(
+        self,
+        transaction_style="url",  # type: str
+        middleware_spans=True,  # type: bool
+        signals_spans=True,  # type: bool
+        cache_spans=False,  # type: bool
+        signals_denylist=None,  # type: Optional[list[signals.Signal]]
+        http_methods_to_capture=DEFAULT_HTTP_METHODS_TO_CAPTURE,  # type: tuple[str, ...]
+    ):
+        # type: (...) -> None
+        if transaction_style not in TRANSACTION_STYLE_VALUES:
+            raise ValueError(
+                "Invalid value for transaction_style: %s (must be in %s)"
+                % (transaction_style, TRANSACTION_STYLE_VALUES)
+            )
+        self.transaction_style = transaction_style
+        self.middleware_spans = middleware_spans
+
+        self.signals_spans = signals_spans
+        self.signals_denylist = signals_denylist or []
+
+        self.cache_spans = cache_spans
+
+        self.http_methods_to_capture = tuple(map(str.upper, http_methods_to_capture))
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        _check_minimum_version(DjangoIntegration, DJANGO_VERSION)
+
+        install_sql_hook()
+        # Patch in our custom middleware.
+
+        # logs an error for every 500
+        ignore_logger("django.server")
+        ignore_logger("django.request")
+
+        from django.core.handlers.wsgi import WSGIHandler
+
+        old_app = WSGIHandler.__call__
+
+        @ensure_integration_enabled(DjangoIntegration, old_app)
+        def sentry_patched_wsgi_handler(self, environ, start_response):
+            # type: (Any, Dict[str, str], Callable[..., Any]) -> _ScopedResponse
+            bound_old_app = old_app.__get__(self, WSGIHandler)
+
+            from django.conf import settings
+
+            use_x_forwarded_for = settings.USE_X_FORWARDED_HOST
+
+            integration = sentry_sdk.get_client().get_integration(DjangoIntegration)
+
+            middleware = SentryWsgiMiddleware(
+                bound_old_app,
+                use_x_forwarded_for,
+                span_origin=DjangoIntegration.origin,
+                http_methods_to_capture=(
+                    integration.http_methods_to_capture
+                    if integration
+                    else DEFAULT_HTTP_METHODS_TO_CAPTURE
+                ),
+            )
+            return middleware(environ, start_response)
+
+        WSGIHandler.__call__ = sentry_patched_wsgi_handler
+
+        _patch_get_response()
+
+        _patch_django_asgi_handler()
+
+        signals.got_request_exception.connect(_got_request_exception)
+
+        @add_global_event_processor
+        def process_django_templates(event, hint):
+            # type: (Event, Optional[Hint]) -> Optional[Event]
+            if hint is None:
+                return event
+
+            exc_info = hint.get("exc_info", None)
+
+            if exc_info is None:
+                return event
+
+            exception = event.get("exception", None)
+
+            if exception is None:
+                return event
+
+            values = exception.get("values", None)
+
+            if values is None:
+                return event
+
+            for exception, (_, exc_value, _) in zip(
+                reversed(values), walk_exception_chain(exc_info)
+            ):
+                frame = get_template_frame_from_exception(exc_value)
+                if frame is not None:
+                    frames = exception.get("stacktrace", {}).get("frames", [])
+
+                    for i in reversed(range(len(frames))):
+                        f = frames[i]
+                        if (
+                            f.get("function") in ("Parser.parse", "parse", "render")
+                            and f.get("module") == "django.template.base"
+                        ):
+                            i += 1
+                            break
+                    else:
+                        i = len(frames)
+
+                    frames.insert(i, frame)
+
+            return event
+
+        @add_global_repr_processor
+        def _django_queryset_repr(value, hint):
+            # type: (Any, Dict[str, Any]) -> Union[NotImplementedType, str]
+            try:
+                # Django 1.6 can fail to import `QuerySet` when Django settings
+                # have not yet been initialized.
+                #
+                # If we fail to import, return `NotImplemented`. It's at least
+                # unlikely that we have a query set in `value` when importing
+                # `QuerySet` fails.
+                from django.db.models.query import QuerySet
+            except Exception:
+                return NotImplemented
+
+            if not isinstance(value, QuerySet) or value._result_cache:
+                return NotImplemented
+
+            return "<%s from %s at 0x%x>" % (
+                value.__class__.__name__,
+                value.__module__,
+                id(value),
+            )
+
+        _patch_channels()
+        patch_django_middlewares()
+        patch_views()
+        patch_templates()
+        patch_signals()
+        add_template_context_repr_sequence()
+
+        if patch_caching is not None:
+            patch_caching()
+
+
+_DRF_PATCHED = False
+_DRF_PATCH_LOCK = threading.Lock()
+
+
+def _patch_drf():
+    # type: () -> None
+    """
+    Patch Django Rest Framework for more/better request data. DRF's request
+    type is a wrapper around Django's request type. The attribute we're
+    interested in is `request.data`, which is a cached property containing a
+    parsed request body. Reading a request body from that property is more
+    reliable than reading from any of Django's own properties, as those don't
+    hold payloads in memory and therefore can only be accessed once.
+
+    We patch the Django request object to include a weak backreference to the
+    DRF request object, such that we can later use either in
+    `DjangoRequestExtractor`.
+
+    This function is not called directly on SDK setup, because importing almost
+    any part of Django Rest Framework will try to access Django settings (where
+    `sentry_sdk.init()` might be called from in the first place). Instead we
+    run this function on every request and do the patching on the first
+    request.
+    """
+
+    global _DRF_PATCHED
+
+    if _DRF_PATCHED:
+        # Double-checked locking
+        return
+
+    with _DRF_PATCH_LOCK:
+        if _DRF_PATCHED:
+            return
+
+        # We set this regardless of whether the code below succeeds or fails.
+        # There is no point in trying to patch again on the next request.
+        _DRF_PATCHED = True
+
+        with capture_internal_exceptions():
+            try:
+                from rest_framework.views import APIView  # type: ignore
+            except ImportError:
+                pass
+            else:
+                old_drf_initial = APIView.initial
+
+                def sentry_patched_drf_initial(self, request, *args, **kwargs):
+                    # type: (APIView, Any, *Any, **Any) -> Any
+                    with capture_internal_exceptions():
+                        request._request._sentry_drf_request_backref = weakref.ref(
+                            request
+                        )
+                        pass
+                    return old_drf_initial(self, request, *args, **kwargs)
+
+                APIView.initial = sentry_patched_drf_initial
+
+
+def _patch_channels():
+    # type: () -> None
+    try:
+        from channels.http import AsgiHandler  # type: ignore
+    except ImportError:
+        return
+
+    if not HAS_REAL_CONTEXTVARS:
+        # We better have contextvars or we're going to leak state between
+        # requests.
+        #
+        # We cannot hard-raise here because channels may not be used at all in
+        # the current process. That is the case when running traditional WSGI
+        # workers in gunicorn+gevent and the websocket stuff in a separate
+        # process.
+        logger.warning(
+            "We detected that you are using Django channels 2.0."
+            + CONTEXTVARS_ERROR_MESSAGE
+        )
+
+    from sentry_sdk.integrations.django.asgi import patch_channels_asgi_handler_impl
+
+    patch_channels_asgi_handler_impl(AsgiHandler)
+
+
+def _patch_django_asgi_handler():
+    # type: () -> None
+    try:
+        from django.core.handlers.asgi import ASGIHandler
+    except ImportError:
+        return
+
+    if not HAS_REAL_CONTEXTVARS:
+        # We better have contextvars or we're going to leak state between
+        # requests.
+        #
+        # We cannot hard-raise here because Django's ASGI stuff may not be used
+        # at all.
+        logger.warning(
+            "We detected that you are using Django 3." + CONTEXTVARS_ERROR_MESSAGE
+        )
+
+    from sentry_sdk.integrations.django.asgi import patch_django_asgi_handler_impl
+
+    patch_django_asgi_handler_impl(ASGIHandler)
+
+
+def _set_transaction_name_and_source(scope, transaction_style, request):
+    # type: (sentry_sdk.Scope, str, WSGIRequest) -> None
+    try:
+        transaction_name = None
+        if transaction_style == "function_name":
+            fn = resolve(request.path).func
+            transaction_name = transaction_from_function(getattr(fn, "view_class", fn))
+
+        elif transaction_style == "url":
+            if hasattr(request, "urlconf"):
+                transaction_name = LEGACY_RESOLVER.resolve(
+                    request.path_info, urlconf=request.urlconf
+                )
+            else:
+                transaction_name = LEGACY_RESOLVER.resolve(request.path_info)
+
+        if transaction_name is None:
+            transaction_name = request.path_info
+            source = TransactionSource.URL
+        else:
+            source = SOURCE_FOR_STYLE[transaction_style]
+
+        scope.set_transaction_name(
+            transaction_name,
+            source=source,
+        )
+    except Resolver404:
+        urlconf = import_module(settings.ROOT_URLCONF)
+        # This exception only gets thrown when transaction_style is `function_name`
+        # So we don't check here what style is configured
+        if hasattr(urlconf, "handler404"):
+            handler = urlconf.handler404
+            if isinstance(handler, str):
+                scope.transaction = handler
+            else:
+                scope.transaction = transaction_from_function(
+                    getattr(handler, "view_class", handler)
+                )
+    except Exception:
+        pass
+
+
+def _before_get_response(request):
+    # type: (WSGIRequest) -> None
+    integration = sentry_sdk.get_client().get_integration(DjangoIntegration)
+    if integration is None:
+        return
+
+    _patch_drf()
+
+    scope = sentry_sdk.get_current_scope()
+    # Rely on WSGI middleware to start a trace
+    _set_transaction_name_and_source(scope, integration.transaction_style, request)
+
+    scope.add_event_processor(
+        _make_wsgi_request_event_processor(weakref.ref(request), integration)
+    )
+
+
+def _attempt_resolve_again(request, scope, transaction_style):
+    # type: (WSGIRequest, sentry_sdk.Scope, str) -> None
+    """
+    Some django middlewares overwrite request.urlconf
+    so we need to respect that contract,
+    so we try to resolve the url again.
+    """
+    if not hasattr(request, "urlconf"):
+        return
+
+    _set_transaction_name_and_source(scope, transaction_style, request)
+
+
+def _after_get_response(request):
+    # type: (WSGIRequest) -> None
+    integration = sentry_sdk.get_client().get_integration(DjangoIntegration)
+    if integration is None or integration.transaction_style != "url":
+        return
+
+    scope = sentry_sdk.get_current_scope()
+    _attempt_resolve_again(request, scope, integration.transaction_style)
+
+
+def _patch_get_response():
+    # type: () -> None
+    """
+    patch get_response, because at that point we have the Django request object
+    """
+    from django.core.handlers.base import BaseHandler
+
+    old_get_response = BaseHandler.get_response
+
+    def sentry_patched_get_response(self, request):
+        # type: (Any, WSGIRequest) -> Union[HttpResponse, BaseException]
+        _before_get_response(request)
+        rv = old_get_response(self, request)
+        _after_get_response(request)
+        return rv
+
+    BaseHandler.get_response = sentry_patched_get_response
+
+    if hasattr(BaseHandler, "get_response_async"):
+        from sentry_sdk.integrations.django.asgi import patch_get_response_async
+
+        patch_get_response_async(BaseHandler, _before_get_response)
+
+
+def _make_wsgi_request_event_processor(weak_request, integration):
+    # type: (Callable[[], WSGIRequest], DjangoIntegration) -> EventProcessor
+    def wsgi_request_event_processor(event, hint):
+        # type: (Event, dict[str, Any]) -> Event
+        # if the request is gone we are fine not logging the data from
+        # it.  This might happen if the processor is pushed away to
+        # another thread.
+        request = weak_request()
+        if request is None:
+            return event
+
+        django_3 = ASGIRequest is not None
+        if django_3 and type(request) == ASGIRequest:
+            # We have a `asgi_request_event_processor` for this.
+            return event
+
+        with capture_internal_exceptions():
+            DjangoRequestExtractor(request).extract_into_event(event)
+
+        if should_send_default_pii():
+            with capture_internal_exceptions():
+                _set_user_info(request, event)
+
+        return event
+
+    return wsgi_request_event_processor
+
+
+def _got_request_exception(request=None, **kwargs):
+    # type: (WSGIRequest, **Any) -> None
+    client = sentry_sdk.get_client()
+    integration = client.get_integration(DjangoIntegration)
+    if integration is None:
+        return
+
+    if request is not None and integration.transaction_style == "url":
+        scope = sentry_sdk.get_current_scope()
+        _attempt_resolve_again(request, scope, integration.transaction_style)
+
+    event, hint = event_from_exception(
+        sys.exc_info(),
+        client_options=client.options,
+        mechanism={"type": "django", "handled": False},
+    )
+    sentry_sdk.capture_event(event, hint=hint)
+
+
+class DjangoRequestExtractor(RequestExtractor):
+    def __init__(self, request):
+        # type: (Union[WSGIRequest, ASGIRequest]) -> None
+        try:
+            drf_request = request._sentry_drf_request_backref()
+            if drf_request is not None:
+                request = drf_request
+        except AttributeError:
+            pass
+        self.request = request
+
+    def env(self):
+        # type: () -> Dict[str, str]
+        return self.request.META
+
+    def cookies(self):
+        # type: () -> Dict[str, Union[str, AnnotatedValue]]
+        privacy_cookies = [
+            django_settings.CSRF_COOKIE_NAME,
+            django_settings.SESSION_COOKIE_NAME,
+        ]
+
+        clean_cookies = {}  # type: Dict[str, Union[str, AnnotatedValue]]
+        for key, val in self.request.COOKIES.items():
+            if key in privacy_cookies:
+                clean_cookies[key] = SENSITIVE_DATA_SUBSTITUTE
+            else:
+                clean_cookies[key] = val
+
+        return clean_cookies
+
+    def raw_data(self):
+        # type: () -> bytes
+        return self.request.body
+
+    def form(self):
+        # type: () -> QueryDict
+        return self.request.POST
+
+    def files(self):
+        # type: () -> MultiValueDict
+        return self.request.FILES
+
+    def size_of_file(self, file):
+        # type: (Any) -> int
+        return file.size
+
+    def parsed_body(self):
+        # type: () -> Optional[Dict[str, Any]]
+        try:
+            return self.request.data
+        except Exception:
+            return RequestExtractor.parsed_body(self)
+
+
+def _set_user_info(request, event):
+    # type: (WSGIRequest, Event) -> None
+    user_info = event.setdefault("user", {})
+
+    user = getattr(request, "user", None)
+
+    if user is None or not is_authenticated(user):
+        return
+
+    try:
+        user_info.setdefault("id", str(user.pk))
+    except Exception:
+        pass
+
+    try:
+        user_info.setdefault("email", user.email)
+    except Exception:
+        pass
+
+    try:
+        user_info.setdefault("username", user.get_username())
+    except Exception:
+        pass
+
+
+def install_sql_hook():
+    # type: () -> None
+    """If installed this causes Django's queries to be captured."""
+    try:
+        from django.db.backends.utils import CursorWrapper
+    except ImportError:
+        from django.db.backends.util import CursorWrapper
+
+    try:
+        # django 1.6 and 1.7 compatability
+        from django.db.backends import BaseDatabaseWrapper
+    except ImportError:
+        # django 1.8 or later
+        from django.db.backends.base.base import BaseDatabaseWrapper
+
+    try:
+        real_execute = CursorWrapper.execute
+        real_executemany = CursorWrapper.executemany
+        real_connect = BaseDatabaseWrapper.connect
+    except AttributeError:
+        # This won't work on Django versions < 1.6
+        return
+
+    @ensure_integration_enabled(DjangoIntegration, real_execute)
+    def execute(self, sql, params=None):
+        # type: (CursorWrapper, Any, Optional[Any]) -> Any
+        with record_sql_queries(
+            cursor=self.cursor,
+            query=sql,
+            params_list=params,
+            paramstyle="format",
+            executemany=False,
+            span_origin=DjangoIntegration.origin_db,
+        ) as span:
+            _set_db_data(span, self)
+            result = real_execute(self, sql, params)
+
+        with capture_internal_exceptions():
+            add_query_source(span)
+
+        return result
+
+    @ensure_integration_enabled(DjangoIntegration, real_executemany)
+    def executemany(self, sql, param_list):
+        # type: (CursorWrapper, Any, List[Any]) -> Any
+        with record_sql_queries(
+            cursor=self.cursor,
+            query=sql,
+            params_list=param_list,
+            paramstyle="format",
+            executemany=True,
+            span_origin=DjangoIntegration.origin_db,
+        ) as span:
+            _set_db_data(span, self)
+
+            result = real_executemany(self, sql, param_list)
+
+        with capture_internal_exceptions():
+            add_query_source(span)
+
+        return result
+
+    @ensure_integration_enabled(DjangoIntegration, real_connect)
+    def connect(self):
+        # type: (BaseDatabaseWrapper) -> None
+        with capture_internal_exceptions():
+            sentry_sdk.add_breadcrumb(message="connect", category="query")
+
+        with sentry_sdk.start_span(
+            op=OP.DB,
+            name="connect",
+            origin=DjangoIntegration.origin_db,
+        ) as span:
+            _set_db_data(span, self)
+            return real_connect(self)
+
+    CursorWrapper.execute = execute
+    CursorWrapper.executemany = executemany
+    BaseDatabaseWrapper.connect = connect
+    ignore_logger("django.db.backends")
+
+
+def _set_db_data(span, cursor_or_db):
+    # type: (Span, Any) -> None
+    db = cursor_or_db.db if hasattr(cursor_or_db, "db") else cursor_or_db
+    vendor = db.vendor
+    span.set_data(SPANDATA.DB_SYSTEM, vendor)
+
+    # Some custom backends override `__getattr__`, making it look like `cursor_or_db`
+    # actually has a `connection` and the `connection` has a `get_dsn_parameters`
+    # attribute, only to throw an error once you actually want to call it.
+    # Hence the `inspect` check whether `get_dsn_parameters` is an actual callable
+    # function.
+    is_psycopg2 = (
+        hasattr(cursor_or_db, "connection")
+        and hasattr(cursor_or_db.connection, "get_dsn_parameters")
+        and inspect.isroutine(cursor_or_db.connection.get_dsn_parameters)
+    )
+    if is_psycopg2:
+        connection_params = cursor_or_db.connection.get_dsn_parameters()
+    else:
+        try:
+            # psycopg3, only extract needed params as get_parameters
+            # can be slow because of the additional logic to filter out default
+            # values
+            connection_params = {
+                "dbname": cursor_or_db.connection.info.dbname,
+                "port": cursor_or_db.connection.info.port,
+            }
+            # PGhost returns host or base dir of UNIX socket as an absolute path
+            # starting with /, use it only when it contains host
+            pg_host = cursor_or_db.connection.info.host
+            if pg_host and not pg_host.startswith("/"):
+                connection_params["host"] = pg_host
+        except Exception:
+            connection_params = db.get_connection_params()
+
+    db_name = connection_params.get("dbname") or connection_params.get("database")
+    if db_name is not None:
+        span.set_data(SPANDATA.DB_NAME, db_name)
+
+    server_address = connection_params.get("host")
+    if server_address is not None:
+        span.set_data(SPANDATA.SERVER_ADDRESS, server_address)
+
+    server_port = connection_params.get("port")
+    if server_port is not None:
+        span.set_data(SPANDATA.SERVER_PORT, str(server_port))
+
+    server_socket_address = connection_params.get("unix_socket")
+    if server_socket_address is not None:
+        span.set_data(SPANDATA.SERVER_SOCKET_ADDRESS, server_socket_address)
+
+
+def add_template_context_repr_sequence():
+    # type: () -> None
+    try:
+        from django.template.context import BaseContext
+
+        add_repr_sequence_type(BaseContext)
+    except Exception:
+        pass
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d35fb2afafcf56ffca091fb168e91e573c95cbc5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/asgi.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/asgi.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f65e1f23c5870e73ff5174cef3a5b051c9ee8f82
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/asgi.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/caching.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/caching.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8471d2a713a6b80703451ea7ad9b0f7e11b9959d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/caching.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/middleware.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/middleware.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..99066b403e13801553c2427b0079133d427bc6d5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/middleware.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/signals_handlers.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/signals_handlers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d86f868b33c053e0180f61ad099fb5493e72403b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/signals_handlers.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/templates.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/templates.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0a842412ddc460665768ebe0ce07ef11958652c1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/templates.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/transactions.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/transactions.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..acc3c701d8cfa64d6c94a0661ed37c7bd5ebd131
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/transactions.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/views.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/views.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ddc607f041902d83c7ec3aa765c2e30954b0f34f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__pycache__/views.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/asgi.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/asgi.py
new file mode 100644
index 0000000000000000000000000000000000000000..773c538045169436f5518593090c41c2d6eb1b4c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/asgi.py
@@ -0,0 +1,245 @@
+"""
+Instrumentation for Django 3.0
+
+Since this file contains `async def` it is conditionally imported in
+`sentry_sdk.integrations.django` (depending on the existence of
+`django.core.handlers.asgi`.
+"""
+
+import asyncio
+import functools
+import inspect
+
+from django.core.handlers.wsgi import WSGIRequest
+
+import sentry_sdk
+from sentry_sdk.consts import OP
+
+from sentry_sdk.integrations.asgi import SentryAsgiMiddleware
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+)
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Callable, Union, TypeVar
+
+    from django.core.handlers.asgi import ASGIRequest
+    from django.http.response import HttpResponse
+
+    from sentry_sdk._types import Event, EventProcessor
+
+    _F = TypeVar("_F", bound=Callable[..., Any])
+
+
+# Python 3.12 deprecates asyncio.iscoroutinefunction() as an alias for
+# inspect.iscoroutinefunction(), whilst also removing the _is_coroutine marker.
+# The latter is replaced with the inspect.markcoroutinefunction decorator.
+# Until 3.12 is the minimum supported Python version, provide a shim.
+# This was copied from https://github.com/django/asgiref/blob/main/asgiref/sync.py
+if hasattr(inspect, "markcoroutinefunction"):
+    iscoroutinefunction = inspect.iscoroutinefunction
+    markcoroutinefunction = inspect.markcoroutinefunction
+else:
+    iscoroutinefunction = asyncio.iscoroutinefunction  # type: ignore[assignment]
+
+    def markcoroutinefunction(func: "_F") -> "_F":
+        func._is_coroutine = asyncio.coroutines._is_coroutine  # type: ignore
+        return func
+
+
+def _make_asgi_request_event_processor(request):
+    # type: (ASGIRequest) -> EventProcessor
+    def asgi_request_event_processor(event, hint):
+        # type: (Event, dict[str, Any]) -> Event
+        # if the request is gone we are fine not logging the data from
+        # it.  This might happen if the processor is pushed away to
+        # another thread.
+        from sentry_sdk.integrations.django import (
+            DjangoRequestExtractor,
+            _set_user_info,
+        )
+
+        if request is None:
+            return event
+
+        if type(request) == WSGIRequest:
+            return event
+
+        with capture_internal_exceptions():
+            DjangoRequestExtractor(request).extract_into_event(event)
+
+        if should_send_default_pii():
+            with capture_internal_exceptions():
+                _set_user_info(request, event)
+
+        return event
+
+    return asgi_request_event_processor
+
+
+def patch_django_asgi_handler_impl(cls):
+    # type: (Any) -> None
+
+    from sentry_sdk.integrations.django import DjangoIntegration
+
+    old_app = cls.__call__
+
+    async def sentry_patched_asgi_handler(self, scope, receive, send):
+        # type: (Any, Any, Any, Any) -> Any
+        integration = sentry_sdk.get_client().get_integration(DjangoIntegration)
+        if integration is None:
+            return await old_app(self, scope, receive, send)
+
+        middleware = SentryAsgiMiddleware(
+            old_app.__get__(self, cls),
+            unsafe_context_data=True,
+            span_origin=DjangoIntegration.origin,
+            http_methods_to_capture=integration.http_methods_to_capture,
+        )._run_asgi3
+
+        return await middleware(scope, receive, send)
+
+    cls.__call__ = sentry_patched_asgi_handler
+
+    modern_django_asgi_support = hasattr(cls, "create_request")
+    if modern_django_asgi_support:
+        old_create_request = cls.create_request
+
+        @ensure_integration_enabled(DjangoIntegration, old_create_request)
+        def sentry_patched_create_request(self, *args, **kwargs):
+            # type: (Any, *Any, **Any) -> Any
+            request, error_response = old_create_request(self, *args, **kwargs)
+            scope = sentry_sdk.get_isolation_scope()
+            scope.add_event_processor(_make_asgi_request_event_processor(request))
+
+            return request, error_response
+
+        cls.create_request = sentry_patched_create_request
+
+
+def patch_get_response_async(cls, _before_get_response):
+    # type: (Any, Any) -> None
+    old_get_response_async = cls.get_response_async
+
+    async def sentry_patched_get_response_async(self, request):
+        # type: (Any, Any) -> Union[HttpResponse, BaseException]
+        _before_get_response(request)
+        return await old_get_response_async(self, request)
+
+    cls.get_response_async = sentry_patched_get_response_async
+
+
+def patch_channels_asgi_handler_impl(cls):
+    # type: (Any) -> None
+    import channels  # type: ignore
+
+    from sentry_sdk.integrations.django import DjangoIntegration
+
+    if channels.__version__ < "3.0.0":
+        old_app = cls.__call__
+
+        async def sentry_patched_asgi_handler(self, receive, send):
+            # type: (Any, Any, Any) -> Any
+            integration = sentry_sdk.get_client().get_integration(DjangoIntegration)
+            if integration is None:
+                return await old_app(self, receive, send)
+
+            middleware = SentryAsgiMiddleware(
+                lambda _scope: old_app.__get__(self, cls),
+                unsafe_context_data=True,
+                span_origin=DjangoIntegration.origin,
+                http_methods_to_capture=integration.http_methods_to_capture,
+            )
+
+            return await middleware(self.scope)(receive, send)  # type: ignore
+
+        cls.__call__ = sentry_patched_asgi_handler
+
+    else:
+        # The ASGI handler in Channels >= 3 has the same signature as
+        # the Django handler.
+        patch_django_asgi_handler_impl(cls)
+
+
+def wrap_async_view(callback):
+    # type: (Any) -> Any
+    from sentry_sdk.integrations.django import DjangoIntegration
+
+    @functools.wraps(callback)
+    async def sentry_wrapped_callback(request, *args, **kwargs):
+        # type: (Any, *Any, **Any) -> Any
+        current_scope = sentry_sdk.get_current_scope()
+        if current_scope.transaction is not None:
+            current_scope.transaction.update_active_thread()
+
+        sentry_scope = sentry_sdk.get_isolation_scope()
+        if sentry_scope.profile is not None:
+            sentry_scope.profile.update_active_thread_id()
+
+        with sentry_sdk.start_span(
+            op=OP.VIEW_RENDER,
+            name=request.resolver_match.view_name,
+            origin=DjangoIntegration.origin,
+        ):
+            return await callback(request, *args, **kwargs)
+
+    return sentry_wrapped_callback
+
+
+def _asgi_middleware_mixin_factory(_check_middleware_span):
+    # type: (Callable[..., Any]) -> Any
+    """
+    Mixin class factory that generates a middleware mixin for handling requests
+    in async mode.
+    """
+
+    class SentryASGIMixin:
+        if TYPE_CHECKING:
+            _inner = None
+
+        def __init__(self, get_response):
+            # type: (Callable[..., Any]) -> None
+            self.get_response = get_response
+            self._acall_method = None
+            self._async_check()
+
+        def _async_check(self):
+            # type: () -> None
+            """
+            If get_response is a coroutine function, turns us into async mode so
+            a thread is not consumed during a whole request.
+            Taken from django.utils.deprecation::MiddlewareMixin._async_check
+            """
+            if iscoroutinefunction(self.get_response):
+                markcoroutinefunction(self)
+
+        def async_route_check(self):
+            # type: () -> bool
+            """
+            Function that checks if we are in async mode,
+            and if we are forwards the handling of requests to __acall__
+            """
+            return iscoroutinefunction(self.get_response)
+
+        async def __acall__(self, *args, **kwargs):
+            # type: (*Any, **Any) -> Any
+            f = self._acall_method
+            if f is None:
+                if hasattr(self._inner, "__acall__"):
+                    self._acall_method = f = self._inner.__acall__  # type: ignore
+                else:
+                    self._acall_method = f = self._inner
+
+            middleware_span = _check_middleware_span(old_method=f)
+
+            if middleware_span is None:
+                return await f(*args, **kwargs)  # type: ignore
+
+            with middleware_span:
+                return await f(*args, **kwargs)  # type: ignore
+
+    return SentryASGIMixin
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/caching.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/caching.py
new file mode 100644
index 0000000000000000000000000000000000000000..7985611761155bf57313eba4784466f7a6a06fba
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/caching.py
@@ -0,0 +1,191 @@
+import functools
+from typing import TYPE_CHECKING
+from sentry_sdk.integrations.redis.utils import _get_safe_key, _key_as_string
+from urllib3.util import parse_url as urlparse
+
+from django import VERSION as DJANGO_VERSION
+from django.core.cache import CacheHandler
+
+import sentry_sdk
+from sentry_sdk.consts import OP, SPANDATA
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+)
+
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Callable
+    from typing import Optional
+
+
+METHODS_TO_INSTRUMENT = [
+    "set",
+    "set_many",
+    "get",
+    "get_many",
+]
+
+
+def _get_span_description(method_name, args, kwargs):
+    # type: (str, tuple[Any], dict[str, Any]) -> str
+    return _key_as_string(_get_safe_key(method_name, args, kwargs))
+
+
+def _patch_cache_method(cache, method_name, address, port):
+    # type: (CacheHandler, str, Optional[str], Optional[int]) -> None
+    from sentry_sdk.integrations.django import DjangoIntegration
+
+    original_method = getattr(cache, method_name)
+
+    @ensure_integration_enabled(DjangoIntegration, original_method)
+    def _instrument_call(
+        cache, method_name, original_method, args, kwargs, address, port
+    ):
+        # type: (CacheHandler, str, Callable[..., Any], tuple[Any, ...], dict[str, Any], Optional[str], Optional[int]) -> Any
+        is_set_operation = method_name.startswith("set")
+        is_get_operation = not is_set_operation
+
+        op = OP.CACHE_PUT if is_set_operation else OP.CACHE_GET
+        description = _get_span_description(method_name, args, kwargs)
+
+        with sentry_sdk.start_span(
+            op=op,
+            name=description,
+            origin=DjangoIntegration.origin,
+        ) as span:
+            value = original_method(*args, **kwargs)
+
+            with capture_internal_exceptions():
+                if address is not None:
+                    span.set_data(SPANDATA.NETWORK_PEER_ADDRESS, address)
+
+                if port is not None:
+                    span.set_data(SPANDATA.NETWORK_PEER_PORT, port)
+
+                key = _get_safe_key(method_name, args, kwargs)
+                if key is not None:
+                    span.set_data(SPANDATA.CACHE_KEY, key)
+
+                item_size = None
+                if is_get_operation:
+                    if value:
+                        item_size = len(str(value))
+                        span.set_data(SPANDATA.CACHE_HIT, True)
+                    else:
+                        span.set_data(SPANDATA.CACHE_HIT, False)
+                else:  # TODO: We don't handle `get_or_set` which we should
+                    arg_count = len(args)
+                    if arg_count >= 2:
+                        # 'set' command
+                        item_size = len(str(args[1]))
+                    elif arg_count == 1:
+                        # 'set_many' command
+                        item_size = len(str(args[0]))
+
+                if item_size is not None:
+                    span.set_data(SPANDATA.CACHE_ITEM_SIZE, item_size)
+
+            return value
+
+    @functools.wraps(original_method)
+    def sentry_method(*args, **kwargs):
+        # type: (*Any, **Any) -> Any
+        return _instrument_call(
+            cache, method_name, original_method, args, kwargs, address, port
+        )
+
+    setattr(cache, method_name, sentry_method)
+
+
+def _patch_cache(cache, address=None, port=None):
+    # type: (CacheHandler, Optional[str], Optional[int]) -> None
+    if not hasattr(cache, "_sentry_patched"):
+        for method_name in METHODS_TO_INSTRUMENT:
+            _patch_cache_method(cache, method_name, address, port)
+        cache._sentry_patched = True
+
+
+def _get_address_port(settings):
+    # type: (dict[str, Any]) -> tuple[Optional[str], Optional[int]]
+    location = settings.get("LOCATION")
+
+    # TODO: location can also be an array of locations
+    #       see: https://docs.djangoproject.com/en/5.0/topics/cache/#redis
+    #       GitHub issue: https://github.com/getsentry/sentry-python/issues/3062
+    if not isinstance(location, str):
+        return None, None
+
+    if "://" in location:
+        parsed_url = urlparse(location)
+        # remove the username and password from URL to not leak sensitive data.
+        address = "{}://{}{}".format(
+            parsed_url.scheme or "",
+            parsed_url.hostname or "",
+            parsed_url.path or "",
+        )
+        port = parsed_url.port
+    else:
+        address = location
+        port = None
+
+    return address, int(port) if port is not None else None
+
+
+def should_enable_cache_spans():
+    # type: () -> bool
+    from sentry_sdk.integrations.django import DjangoIntegration
+
+    client = sentry_sdk.get_client()
+    integration = client.get_integration(DjangoIntegration)
+    from django.conf import settings
+
+    return integration is not None and (
+        (client.spotlight is not None and settings.DEBUG is True)
+        or integration.cache_spans is True
+    )
+
+
+def patch_caching():
+    # type: () -> None
+    if not hasattr(CacheHandler, "_sentry_patched"):
+        if DJANGO_VERSION < (3, 2):
+            original_get_item = CacheHandler.__getitem__
+
+            @functools.wraps(original_get_item)
+            def sentry_get_item(self, alias):
+                # type: (CacheHandler, str) -> Any
+                cache = original_get_item(self, alias)
+
+                if should_enable_cache_spans():
+                    from django.conf import settings
+
+                    address, port = _get_address_port(
+                        settings.CACHES[alias or "default"]
+                    )
+
+                    _patch_cache(cache, address, port)
+
+                return cache
+
+            CacheHandler.__getitem__ = sentry_get_item
+            CacheHandler._sentry_patched = True
+
+        else:
+            original_create_connection = CacheHandler.create_connection
+
+            @functools.wraps(original_create_connection)
+            def sentry_create_connection(self, alias):
+                # type: (CacheHandler, str) -> Any
+                cache = original_create_connection(self, alias)
+
+                if should_enable_cache_spans():
+                    address, port = _get_address_port(self.settings[alias or "default"])
+
+                    _patch_cache(cache, address, port)
+
+                return cache
+
+            CacheHandler.create_connection = sentry_create_connection
+            CacheHandler._sentry_patched = True
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/middleware.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/middleware.py
new file mode 100644
index 0000000000000000000000000000000000000000..245276566e299012a7e192042ff2ed86e084d954
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/middleware.py
@@ -0,0 +1,187 @@
+"""
+Create spans from Django middleware invocations
+"""
+
+from functools import wraps
+
+from django import VERSION as DJANGO_VERSION
+
+import sentry_sdk
+from sentry_sdk.consts import OP
+from sentry_sdk.utils import (
+    ContextVar,
+    transaction_from_function,
+    capture_internal_exceptions,
+)
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Callable
+    from typing import Optional
+    from typing import TypeVar
+
+    from sentry_sdk.tracing import Span
+
+    F = TypeVar("F", bound=Callable[..., Any])
+
+_import_string_should_wrap_middleware = ContextVar(
+    "import_string_should_wrap_middleware"
+)
+
+DJANGO_SUPPORTS_ASYNC_MIDDLEWARE = DJANGO_VERSION >= (3, 1)
+
+if not DJANGO_SUPPORTS_ASYNC_MIDDLEWARE:
+    _asgi_middleware_mixin_factory = lambda _: object
+else:
+    from .asgi import _asgi_middleware_mixin_factory
+
+
+def patch_django_middlewares():
+    # type: () -> None
+    from django.core.handlers import base
+
+    old_import_string = base.import_string
+
+    def sentry_patched_import_string(dotted_path):
+        # type: (str) -> Any
+        rv = old_import_string(dotted_path)
+
+        if _import_string_should_wrap_middleware.get(None):
+            rv = _wrap_middleware(rv, dotted_path)
+
+        return rv
+
+    base.import_string = sentry_patched_import_string
+
+    old_load_middleware = base.BaseHandler.load_middleware
+
+    def sentry_patched_load_middleware(*args, **kwargs):
+        # type: (Any, Any) -> Any
+        _import_string_should_wrap_middleware.set(True)
+        try:
+            return old_load_middleware(*args, **kwargs)
+        finally:
+            _import_string_should_wrap_middleware.set(False)
+
+    base.BaseHandler.load_middleware = sentry_patched_load_middleware
+
+
+def _wrap_middleware(middleware, middleware_name):
+    # type: (Any, str) -> Any
+    from sentry_sdk.integrations.django import DjangoIntegration
+
+    def _check_middleware_span(old_method):
+        # type: (Callable[..., Any]) -> Optional[Span]
+        integration = sentry_sdk.get_client().get_integration(DjangoIntegration)
+        if integration is None or not integration.middleware_spans:
+            return None
+
+        function_name = transaction_from_function(old_method)
+
+        description = middleware_name
+        function_basename = getattr(old_method, "__name__", None)
+        if function_basename:
+            description = "{}.{}".format(description, function_basename)
+
+        middleware_span = sentry_sdk.start_span(
+            op=OP.MIDDLEWARE_DJANGO,
+            name=description,
+            origin=DjangoIntegration.origin,
+        )
+        middleware_span.set_tag("django.function_name", function_name)
+        middleware_span.set_tag("django.middleware_name", middleware_name)
+
+        return middleware_span
+
+    def _get_wrapped_method(old_method):
+        # type: (F) -> F
+        with capture_internal_exceptions():
+
+            def sentry_wrapped_method(*args, **kwargs):
+                # type: (*Any, **Any) -> Any
+                middleware_span = _check_middleware_span(old_method)
+
+                if middleware_span is None:
+                    return old_method(*args, **kwargs)
+
+                with middleware_span:
+                    return old_method(*args, **kwargs)
+
+            try:
+                # fails for __call__ of function on Python 2 (see py2.7-django-1.11)
+                sentry_wrapped_method = wraps(old_method)(sentry_wrapped_method)
+
+                # Necessary for Django 3.1
+                sentry_wrapped_method.__self__ = old_method.__self__  # type: ignore
+            except Exception:
+                pass
+
+            return sentry_wrapped_method  # type: ignore
+
+        return old_method
+
+    class SentryWrappingMiddleware(
+        _asgi_middleware_mixin_factory(_check_middleware_span)  # type: ignore
+    ):
+        sync_capable = getattr(middleware, "sync_capable", True)
+        async_capable = DJANGO_SUPPORTS_ASYNC_MIDDLEWARE and getattr(
+            middleware, "async_capable", False
+        )
+
+        def __init__(self, get_response=None, *args, **kwargs):
+            # type: (Optional[Callable[..., Any]], *Any, **Any) -> None
+            if get_response:
+                self._inner = middleware(get_response, *args, **kwargs)
+            else:
+                self._inner = middleware(*args, **kwargs)
+            self.get_response = get_response
+            self._call_method = None
+            if self.async_capable:
+                super().__init__(get_response)
+
+        # We need correct behavior for `hasattr()`, which we can only determine
+        # when we have an instance of the middleware we're wrapping.
+        def __getattr__(self, method_name):
+            # type: (str) -> Any
+            if method_name not in (
+                "process_request",
+                "process_view",
+                "process_template_response",
+                "process_response",
+                "process_exception",
+            ):
+                raise AttributeError()
+
+            old_method = getattr(self._inner, method_name)
+            rv = _get_wrapped_method(old_method)
+            self.__dict__[method_name] = rv
+            return rv
+
+        def __call__(self, *args, **kwargs):
+            # type: (*Any, **Any) -> Any
+            if hasattr(self, "async_route_check") and self.async_route_check():
+                return self.__acall__(*args, **kwargs)
+
+            f = self._call_method
+            if f is None:
+                self._call_method = f = self._inner.__call__
+
+            middleware_span = _check_middleware_span(old_method=f)
+
+            if middleware_span is None:
+                return f(*args, **kwargs)
+
+            with middleware_span:
+                return f(*args, **kwargs)
+
+    for attr in (
+        "__name__",
+        "__module__",
+        "__qualname__",
+    ):
+        if hasattr(middleware, attr):
+            setattr(SentryWrappingMiddleware, attr, getattr(middleware, attr))
+
+    return SentryWrappingMiddleware
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/signals_handlers.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/signals_handlers.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb0f8b9d2e146393abc8db3d26b0f45bfbc4a0c6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/signals_handlers.py
@@ -0,0 +1,91 @@
+from functools import wraps
+
+from django.dispatch import Signal
+
+import sentry_sdk
+from sentry_sdk.consts import OP
+from sentry_sdk.integrations.django import DJANGO_VERSION
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from collections.abc import Callable
+    from typing import Any, Union
+
+
+def _get_receiver_name(receiver):
+    # type: (Callable[..., Any]) -> str
+    name = ""
+
+    if hasattr(receiver, "__qualname__"):
+        name = receiver.__qualname__
+    elif hasattr(receiver, "__name__"):  # Python 2.7 has no __qualname__
+        name = receiver.__name__
+    elif hasattr(
+        receiver, "func"
+    ):  # certain functions (like partials) dont have a name
+        if hasattr(receiver, "func") and hasattr(receiver.func, "__name__"):
+            name = "partial()"
+
+    if (
+        name == ""
+    ):  # In case nothing was found, return the string representation (this is the slowest case)
+        return str(receiver)
+
+    if hasattr(receiver, "__module__"):  # prepend with module, if there is one
+        name = receiver.__module__ + "." + name
+
+    return name
+
+
+def patch_signals():
+    # type: () -> None
+    """
+    Patch django signal receivers to create a span.
+
+    This only wraps sync receivers. Django>=5.0 introduced async receivers, but
+    since we don't create transactions for ASGI Django, we don't wrap them.
+    """
+    from sentry_sdk.integrations.django import DjangoIntegration
+
+    old_live_receivers = Signal._live_receivers
+
+    def _sentry_live_receivers(self, sender):
+        # type: (Signal, Any) -> Union[tuple[list[Callable[..., Any]], list[Callable[..., Any]]], list[Callable[..., Any]]]
+        if DJANGO_VERSION >= (5, 0):
+            sync_receivers, async_receivers = old_live_receivers(self, sender)
+        else:
+            sync_receivers = old_live_receivers(self, sender)
+            async_receivers = []
+
+        def sentry_sync_receiver_wrapper(receiver):
+            # type: (Callable[..., Any]) -> Callable[..., Any]
+            @wraps(receiver)
+            def wrapper(*args, **kwargs):
+                # type: (Any, Any) -> Any
+                signal_name = _get_receiver_name(receiver)
+                with sentry_sdk.start_span(
+                    op=OP.EVENT_DJANGO,
+                    name=signal_name,
+                    origin=DjangoIntegration.origin,
+                ) as span:
+                    span.set_data("signal", signal_name)
+                    return receiver(*args, **kwargs)
+
+            return wrapper
+
+        integration = sentry_sdk.get_client().get_integration(DjangoIntegration)
+        if (
+            integration
+            and integration.signals_spans
+            and self not in integration.signals_denylist
+        ):
+            for idx, receiver in enumerate(sync_receivers):
+                sync_receivers[idx] = sentry_sync_receiver_wrapper(receiver)
+
+        if DJANGO_VERSION >= (5, 0):
+            return sync_receivers, async_receivers
+        else:
+            return sync_receivers
+
+    Signal._live_receivers = _sentry_live_receivers
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/templates.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/templates.py
new file mode 100644
index 0000000000000000000000000000000000000000..10e8a924b753ff3d3c6754e2d001f27c086c7cec
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/templates.py
@@ -0,0 +1,188 @@
+import functools
+
+from django.template import TemplateSyntaxError
+from django.utils.safestring import mark_safe
+from django import VERSION as DJANGO_VERSION
+
+import sentry_sdk
+from sentry_sdk.consts import OP
+from sentry_sdk.utils import ensure_integration_enabled
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Dict
+    from typing import Optional
+    from typing import Iterator
+    from typing import Tuple
+
+try:
+    # support Django 1.9
+    from django.template.base import Origin
+except ImportError:
+    # backward compatibility
+    from django.template.loader import LoaderOrigin as Origin
+
+
+def get_template_frame_from_exception(exc_value):
+    # type: (Optional[BaseException]) -> Optional[Dict[str, Any]]
+
+    # As of Django 1.9 or so the new template debug thing showed up.
+    if hasattr(exc_value, "template_debug"):
+        return _get_template_frame_from_debug(exc_value.template_debug)  # type: ignore
+
+    # As of r16833 (Django) all exceptions may contain a
+    # ``django_template_source`` attribute (rather than the legacy
+    # ``TemplateSyntaxError.source`` check)
+    if hasattr(exc_value, "django_template_source"):
+        return _get_template_frame_from_source(
+            exc_value.django_template_source  # type: ignore
+        )
+
+    if isinstance(exc_value, TemplateSyntaxError) and hasattr(exc_value, "source"):
+        source = exc_value.source
+        if isinstance(source, (tuple, list)) and isinstance(source[0], Origin):
+            return _get_template_frame_from_source(source)  # type: ignore
+
+    return None
+
+
+def _get_template_name_description(template_name):
+    # type: (str) -> str
+    if isinstance(template_name, (list, tuple)):
+        if template_name:
+            return "[{}, ...]".format(template_name[0])
+    else:
+        return template_name
+
+
+def patch_templates():
+    # type: () -> None
+    from django.template.response import SimpleTemplateResponse
+    from sentry_sdk.integrations.django import DjangoIntegration
+
+    real_rendered_content = SimpleTemplateResponse.rendered_content
+
+    @property  # type: ignore
+    @ensure_integration_enabled(DjangoIntegration, real_rendered_content.fget)
+    def rendered_content(self):
+        # type: (SimpleTemplateResponse) -> str
+        with sentry_sdk.start_span(
+            op=OP.TEMPLATE_RENDER,
+            name=_get_template_name_description(self.template_name),
+            origin=DjangoIntegration.origin,
+        ) as span:
+            span.set_data("context", self.context_data)
+            return real_rendered_content.fget(self)
+
+    SimpleTemplateResponse.rendered_content = rendered_content
+
+    if DJANGO_VERSION < (1, 7):
+        return
+    import django.shortcuts
+
+    real_render = django.shortcuts.render
+
+    @functools.wraps(real_render)
+    @ensure_integration_enabled(DjangoIntegration, real_render)
+    def render(request, template_name, context=None, *args, **kwargs):
+        # type: (django.http.HttpRequest, str, Optional[Dict[str, Any]], *Any, **Any) -> django.http.HttpResponse
+
+        # Inject trace meta tags into template context
+        context = context or {}
+        if "sentry_trace_meta" not in context:
+            context["sentry_trace_meta"] = mark_safe(
+                sentry_sdk.get_current_scope().trace_propagation_meta()
+            )
+
+        with sentry_sdk.start_span(
+            op=OP.TEMPLATE_RENDER,
+            name=_get_template_name_description(template_name),
+            origin=DjangoIntegration.origin,
+        ) as span:
+            span.set_data("context", context)
+            return real_render(request, template_name, context, *args, **kwargs)
+
+    django.shortcuts.render = render
+
+
+def _get_template_frame_from_debug(debug):
+    # type: (Dict[str, Any]) -> Dict[str, Any]
+    if debug is None:
+        return None
+
+    lineno = debug["line"]
+    filename = debug["name"]
+    if filename is None:
+        filename = ""
+
+    pre_context = []
+    post_context = []
+    context_line = None
+
+    for i, line in debug["source_lines"]:
+        if i < lineno:
+            pre_context.append(line)
+        elif i > lineno:
+            post_context.append(line)
+        else:
+            context_line = line
+
+    return {
+        "filename": filename,
+        "lineno": lineno,
+        "pre_context": pre_context[-5:],
+        "post_context": post_context[:5],
+        "context_line": context_line,
+        "in_app": True,
+    }
+
+
+def _linebreak_iter(template_source):
+    # type: (str) -> Iterator[int]
+    yield 0
+    p = template_source.find("\n")
+    while p >= 0:
+        yield p + 1
+        p = template_source.find("\n", p + 1)
+
+
+def _get_template_frame_from_source(source):
+    # type: (Tuple[Origin, Tuple[int, int]]) -> Optional[Dict[str, Any]]
+    if not source:
+        return None
+
+    origin, (start, end) = source
+    filename = getattr(origin, "loadname", None)
+    if filename is None:
+        filename = ""
+    template_source = origin.reload()
+    lineno = None
+    upto = 0
+    pre_context = []
+    post_context = []
+    context_line = None
+
+    for num, next in enumerate(_linebreak_iter(template_source)):
+        line = template_source[upto:next]
+        if start >= upto and end <= next:
+            lineno = num
+            context_line = line
+        elif lineno is None:
+            pre_context.append(line)
+        else:
+            post_context.append(line)
+
+        upto = next
+
+    if context_line is None or lineno is None:
+        return None
+
+    return {
+        "filename": filename,
+        "lineno": lineno,
+        "pre_context": pre_context[-5:],
+        "post_context": post_context[:5],
+        "context_line": context_line,
+    }
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/transactions.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/transactions.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a7d69f3c95536be46a3d1064fce6e8113b09154
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/transactions.py
@@ -0,0 +1,159 @@
+"""
+Copied from raven-python.
+
+Despite being called "legacy" in some places this resolver is very much still
+in use.
+"""
+
+import re
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from django.urls.resolvers import URLResolver
+    from typing import Dict
+    from typing import List
+    from typing import Optional
+    from django.urls.resolvers import URLPattern
+    from typing import Tuple
+    from typing import Union
+    from re import Pattern
+
+from django import VERSION as DJANGO_VERSION
+
+if DJANGO_VERSION >= (2, 0):
+    from django.urls.resolvers import RoutePattern
+else:
+    RoutePattern = None
+
+try:
+    from django.urls import get_resolver
+except ImportError:
+    from django.core.urlresolvers import get_resolver
+
+
+def get_regex(resolver_or_pattern):
+    # type: (Union[URLPattern, URLResolver]) -> Pattern[str]
+    """Utility method for django's deprecated resolver.regex"""
+    try:
+        regex = resolver_or_pattern.regex
+    except AttributeError:
+        regex = resolver_or_pattern.pattern.regex
+    return regex
+
+
+class RavenResolver:
+    _new_style_group_matcher = re.compile(
+        r"<(?:([^>:]+):)?([^>]+)>"
+    )  # https://github.com/django/django/blob/21382e2743d06efbf5623e7c9b6dccf2a325669b/django/urls/resolvers.py#L245-L247
+    _optional_group_matcher = re.compile(r"\(\?\:([^\)]+)\)")
+    _named_group_matcher = re.compile(r"\(\?P<(\w+)>[^\)]+\)+")
+    _non_named_group_matcher = re.compile(r"\([^\)]+\)")
+    # [foo|bar|baz]
+    _either_option_matcher = re.compile(r"\[([^\]]+)\|([^\]]+)\]")
+    _camel_re = re.compile(r"([A-Z]+)([a-z])")
+
+    _cache = {}  # type: Dict[URLPattern, str]
+
+    def _simplify(self, pattern):
+        # type: (Union[URLPattern, URLResolver]) -> str
+        r"""
+        Clean up urlpattern regexes into something readable by humans:
+
+        From:
+        > "^(?P\w+)/athletes/(?P\w+)/$"
+
+        To:
+        > "{sport_slug}/athletes/{athlete_slug}/"
+        """
+        # "new-style" path patterns can be parsed directly without turning them
+        # into regexes first
+        if (
+            RoutePattern is not None
+            and hasattr(pattern, "pattern")
+            and isinstance(pattern.pattern, RoutePattern)
+        ):
+            return self._new_style_group_matcher.sub(
+                lambda m: "{%s}" % m.group(2), str(pattern.pattern._route)
+            )
+
+        result = get_regex(pattern).pattern
+
+        # remove optional params
+        # TODO(dcramer): it'd be nice to change these into [%s] but it currently
+        # conflicts with the other rules because we're doing regexp matches
+        # rather than parsing tokens
+        result = self._optional_group_matcher.sub(lambda m: "%s" % m.group(1), result)
+
+        # handle named groups first
+        result = self._named_group_matcher.sub(lambda m: "{%s}" % m.group(1), result)
+
+        # handle non-named groups
+        result = self._non_named_group_matcher.sub("{var}", result)
+
+        # handle optional params
+        result = self._either_option_matcher.sub(lambda m: m.group(1), result)
+
+        # clean up any outstanding regex-y characters.
+        result = (
+            result.replace("^", "")
+            .replace("$", "")
+            .replace("?", "")
+            .replace("\\A", "")
+            .replace("\\Z", "")
+            .replace("//", "/")
+            .replace("\\", "")
+        )
+
+        return result
+
+    def _resolve(self, resolver, path, parents=None):
+        # type: (URLResolver, str, Optional[List[URLResolver]]) -> Optional[str]
+
+        match = get_regex(resolver).search(path)  # Django < 2.0
+
+        if not match:
+            return None
+
+        if parents is None:
+            parents = [resolver]
+        elif resolver not in parents:
+            parents = parents + [resolver]
+
+        new_path = path[match.end() :]
+        for pattern in resolver.url_patterns:
+            # this is an include()
+            if not pattern.callback:
+                match_ = self._resolve(pattern, new_path, parents)
+                if match_:
+                    return match_
+                continue
+            elif not get_regex(pattern).search(new_path):
+                continue
+
+            try:
+                return self._cache[pattern]
+            except KeyError:
+                pass
+
+            prefix = "".join(self._simplify(p) for p in parents)
+            result = prefix + self._simplify(pattern)
+            if not result.startswith("/"):
+                result = "/" + result
+            self._cache[pattern] = result
+            return result
+
+        return None
+
+    def resolve(
+        self,
+        path,  # type: str
+        urlconf=None,  # type: Union[None, Tuple[URLPattern, URLPattern, URLResolver], Tuple[URLPattern]]
+    ):
+        # type: (...) -> Optional[str]
+        resolver = get_resolver(urlconf)
+        match = self._resolve(resolver, path)
+        return match
+
+
+LEGACY_RESOLVER = RavenResolver()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/views.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/views.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a9861a6a69137d0608ca92f767593848b226cc9
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/views.py
@@ -0,0 +1,96 @@
+import functools
+
+import sentry_sdk
+from sentry_sdk.consts import OP
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+
+
+try:
+    from asyncio import iscoroutinefunction
+except ImportError:
+    iscoroutinefunction = None  # type: ignore
+
+
+try:
+    from sentry_sdk.integrations.django.asgi import wrap_async_view
+except (ImportError, SyntaxError):
+    wrap_async_view = None  # type: ignore
+
+
+def patch_views():
+    # type: () -> None
+
+    from django.core.handlers.base import BaseHandler
+    from django.template.response import SimpleTemplateResponse
+    from sentry_sdk.integrations.django import DjangoIntegration
+
+    old_make_view_atomic = BaseHandler.make_view_atomic
+    old_render = SimpleTemplateResponse.render
+
+    def sentry_patched_render(self):
+        # type: (SimpleTemplateResponse) -> Any
+        with sentry_sdk.start_span(
+            op=OP.VIEW_RESPONSE_RENDER,
+            name="serialize response",
+            origin=DjangoIntegration.origin,
+        ):
+            return old_render(self)
+
+    @functools.wraps(old_make_view_atomic)
+    def sentry_patched_make_view_atomic(self, *args, **kwargs):
+        # type: (Any, *Any, **Any) -> Any
+        callback = old_make_view_atomic(self, *args, **kwargs)
+
+        # XXX: The wrapper function is created for every request. Find more
+        # efficient way to wrap views (or build a cache?)
+
+        integration = sentry_sdk.get_client().get_integration(DjangoIntegration)
+        if integration is not None and integration.middleware_spans:
+            is_async_view = (
+                iscoroutinefunction is not None
+                and wrap_async_view is not None
+                and iscoroutinefunction(callback)
+            )
+            if is_async_view:
+                sentry_wrapped_callback = wrap_async_view(callback)
+            else:
+                sentry_wrapped_callback = _wrap_sync_view(callback)
+
+        else:
+            sentry_wrapped_callback = callback
+
+        return sentry_wrapped_callback
+
+    SimpleTemplateResponse.render = sentry_patched_render
+    BaseHandler.make_view_atomic = sentry_patched_make_view_atomic
+
+
+def _wrap_sync_view(callback):
+    # type: (Any) -> Any
+    from sentry_sdk.integrations.django import DjangoIntegration
+
+    @functools.wraps(callback)
+    def sentry_wrapped_callback(request, *args, **kwargs):
+        # type: (Any, *Any, **Any) -> Any
+        current_scope = sentry_sdk.get_current_scope()
+        if current_scope.transaction is not None:
+            current_scope.transaction.update_active_thread()
+
+        sentry_scope = sentry_sdk.get_isolation_scope()
+        # set the active thread id to the handler thread for sync views
+        # this isn't necessary for async views since that runs on main
+        if sentry_scope.profile is not None:
+            sentry_scope.profile.update_active_thread_id()
+
+        with sentry_sdk.start_span(
+            op=OP.VIEW_RENDER,
+            name=request.resolver_match.view_name,
+            origin=DjangoIntegration.origin,
+        ):
+            return callback(request, *args, **kwargs)
+
+    return sentry_wrapped_callback
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/dramatiq.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/dramatiq.py
new file mode 100644
index 0000000000000000000000000000000000000000..a756b4c669e0b5cf10aec64c75ce118d7138e9e2
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/dramatiq.py
@@ -0,0 +1,168 @@
+import json
+
+import sentry_sdk
+from sentry_sdk.integrations import Integration
+from sentry_sdk.integrations._wsgi_common import request_body_within_bounds
+from sentry_sdk.utils import (
+    AnnotatedValue,
+    capture_internal_exceptions,
+    event_from_exception,
+)
+
+from dramatiq.broker import Broker  # type: ignore
+from dramatiq.message import Message  # type: ignore
+from dramatiq.middleware import Middleware, default_middleware  # type: ignore
+from dramatiq.errors import Retry  # type: ignore
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Callable, Dict, Optional, Union
+    from sentry_sdk._types import Event, Hint
+
+
+class DramatiqIntegration(Integration):
+    """
+    Dramatiq integration for Sentry
+
+    Please make sure that you call `sentry_sdk.init` *before* initializing
+    your broker, as it monkey patches `Broker.__init__`.
+
+    This integration was originally developed and maintained
+    by https://github.com/jacobsvante and later donated to the Sentry
+    project.
+    """
+
+    identifier = "dramatiq"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        _patch_dramatiq_broker()
+
+
+def _patch_dramatiq_broker():
+    # type: () -> None
+    original_broker__init__ = Broker.__init__
+
+    def sentry_patched_broker__init__(self, *args, **kw):
+        # type: (Broker, *Any, **Any) -> None
+        integration = sentry_sdk.get_client().get_integration(DramatiqIntegration)
+
+        try:
+            middleware = kw.pop("middleware")
+        except KeyError:
+            # Unfortunately Broker and StubBroker allows middleware to be
+            # passed in as positional arguments, whilst RabbitmqBroker and
+            # RedisBroker does not.
+            if len(args) == 1:
+                middleware = args[0]
+                args = []  # type: ignore
+            else:
+                middleware = None
+
+        if middleware is None:
+            middleware = list(m() for m in default_middleware)
+        else:
+            middleware = list(middleware)
+
+        if integration is not None:
+            middleware = [m for m in middleware if not isinstance(m, SentryMiddleware)]
+            middleware.insert(0, SentryMiddleware())
+
+        kw["middleware"] = middleware
+        original_broker__init__(self, *args, **kw)
+
+    Broker.__init__ = sentry_patched_broker__init__
+
+
+class SentryMiddleware(Middleware):  # type: ignore[misc]
+    """
+    A Dramatiq middleware that automatically captures and sends
+    exceptions to Sentry.
+
+    This is automatically added to every instantiated broker via the
+    DramatiqIntegration.
+    """
+
+    def before_process_message(self, broker, message):
+        # type: (Broker, Message) -> None
+        integration = sentry_sdk.get_client().get_integration(DramatiqIntegration)
+        if integration is None:
+            return
+
+        message._scope_manager = sentry_sdk.new_scope()
+        message._scope_manager.__enter__()
+
+        scope = sentry_sdk.get_current_scope()
+        scope.set_transaction_name(message.actor_name)
+        scope.set_extra("dramatiq_message_id", message.message_id)
+        scope.add_event_processor(_make_message_event_processor(message, integration))
+
+    def after_process_message(self, broker, message, *, result=None, exception=None):
+        # type: (Broker, Message, Any, Optional[Any], Optional[Exception]) -> None
+        integration = sentry_sdk.get_client().get_integration(DramatiqIntegration)
+        if integration is None:
+            return
+
+        actor = broker.get_actor(message.actor_name)
+        throws = message.options.get("throws") or actor.options.get("throws")
+
+        try:
+            if (
+                exception is not None
+                and not (throws and isinstance(exception, throws))
+                and not isinstance(exception, Retry)
+            ):
+                event, hint = event_from_exception(
+                    exception,
+                    client_options=sentry_sdk.get_client().options,
+                    mechanism={
+                        "type": DramatiqIntegration.identifier,
+                        "handled": False,
+                    },
+                )
+                sentry_sdk.capture_event(event, hint=hint)
+        finally:
+            message._scope_manager.__exit__(None, None, None)
+
+
+def _make_message_event_processor(message, integration):
+    # type: (Message, DramatiqIntegration) -> Callable[[Event, Hint], Optional[Event]]
+
+    def inner(event, hint):
+        # type: (Event, Hint) -> Optional[Event]
+        with capture_internal_exceptions():
+            DramatiqMessageExtractor(message).extract_into_event(event)
+
+        return event
+
+    return inner
+
+
+class DramatiqMessageExtractor:
+    def __init__(self, message):
+        # type: (Message) -> None
+        self.message_data = dict(message.asdict())
+
+    def content_length(self):
+        # type: () -> int
+        return len(json.dumps(self.message_data))
+
+    def extract_into_event(self, event):
+        # type: (Event) -> None
+        client = sentry_sdk.get_client()
+        if not client.is_active():
+            return
+
+        contexts = event.setdefault("contexts", {})
+        request_info = contexts.setdefault("dramatiq", {})
+        request_info["type"] = "dramatiq"
+
+        data = None  # type: Optional[Union[AnnotatedValue, Dict[str, Any]]]
+        if not request_body_within_bounds(client, self.content_length()):
+            data = AnnotatedValue.removed_because_over_size_limit()
+        else:
+            data = self.message_data
+
+        request_info["data"] = data
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/excepthook.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/excepthook.py
new file mode 100644
index 0000000000000000000000000000000000000000..61c7e460bf85aaf9081cf9939ffe497ce905f0bf
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/excepthook.py
@@ -0,0 +1,83 @@
+import sys
+
+import sentry_sdk
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    event_from_exception,
+)
+from sentry_sdk.integrations import Integration
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Callable
+    from typing import Any
+    from typing import Type
+    from typing import Optional
+
+    from types import TracebackType
+
+    Excepthook = Callable[
+        [Type[BaseException], BaseException, Optional[TracebackType]],
+        Any,
+    ]
+
+
+class ExcepthookIntegration(Integration):
+    identifier = "excepthook"
+
+    always_run = False
+
+    def __init__(self, always_run=False):
+        # type: (bool) -> None
+
+        if not isinstance(always_run, bool):
+            raise ValueError(
+                "Invalid value for always_run: %s (must be type boolean)"
+                % (always_run,)
+            )
+        self.always_run = always_run
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        sys.excepthook = _make_excepthook(sys.excepthook)
+
+
+def _make_excepthook(old_excepthook):
+    # type: (Excepthook) -> Excepthook
+    def sentry_sdk_excepthook(type_, value, traceback):
+        # type: (Type[BaseException], BaseException, Optional[TracebackType]) -> None
+        integration = sentry_sdk.get_client().get_integration(ExcepthookIntegration)
+
+        # Note: If  we replace this with ensure_integration_enabled then
+        # we break the exceptiongroup backport;
+        # See: https://github.com/getsentry/sentry-python/issues/3097
+        if integration is None:
+            return old_excepthook(type_, value, traceback)
+
+        if _should_send(integration.always_run):
+            with capture_internal_exceptions():
+                event, hint = event_from_exception(
+                    (type_, value, traceback),
+                    client_options=sentry_sdk.get_client().options,
+                    mechanism={"type": "excepthook", "handled": False},
+                )
+                sentry_sdk.capture_event(event, hint=hint)
+
+        return old_excepthook(type_, value, traceback)
+
+    return sentry_sdk_excepthook
+
+
+def _should_send(always_run=False):
+    # type: (bool) -> bool
+    if always_run:
+        return True
+
+    if hasattr(sys, "ps1"):
+        # Disable the excepthook for interactive Python shells, otherwise
+        # every typo gets sent to Sentry.
+        return False
+
+    return True
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/executing.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/executing.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e68b8c0c7e8acfa19157d042ce8cfc4fd314c9b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/executing.py
@@ -0,0 +1,67 @@
+import sentry_sdk
+from sentry_sdk.integrations import Integration, DidNotEnable
+from sentry_sdk.scope import add_global_event_processor
+from sentry_sdk.utils import walk_exception_chain, iter_stacks
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Optional
+
+    from sentry_sdk._types import Event, Hint
+
+try:
+    import executing
+except ImportError:
+    raise DidNotEnable("executing is not installed")
+
+
+class ExecutingIntegration(Integration):
+    identifier = "executing"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+
+        @add_global_event_processor
+        def add_executing_info(event, hint):
+            # type: (Event, Optional[Hint]) -> Optional[Event]
+            if sentry_sdk.get_client().get_integration(ExecutingIntegration) is None:
+                return event
+
+            if hint is None:
+                return event
+
+            exc_info = hint.get("exc_info", None)
+
+            if exc_info is None:
+                return event
+
+            exception = event.get("exception", None)
+
+            if exception is None:
+                return event
+
+            values = exception.get("values", None)
+
+            if values is None:
+                return event
+
+            for exception, (_exc_type, _exc_value, exc_tb) in zip(
+                reversed(values), walk_exception_chain(exc_info)
+            ):
+                sentry_frames = [
+                    frame
+                    for frame in exception.get("stacktrace", {}).get("frames", [])
+                    if frame.get("function")
+                ]
+                tbs = list(iter_stacks(exc_tb))
+                if len(sentry_frames) != len(tbs):
+                    continue
+
+                for sentry_frame, tb in zip(sentry_frames, tbs):
+                    frame = tb.tb_frame
+                    source = executing.Source.for_frame(frame)
+                    sentry_frame["function"] = source.code_qualname(frame.f_code)
+
+            return event
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/falcon.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/falcon.py
new file mode 100644
index 0000000000000000000000000000000000000000..ddedcb10de7d6a0ba01f24109a91b71007f9331d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/falcon.py
@@ -0,0 +1,272 @@
+import sentry_sdk
+from sentry_sdk.integrations import _check_minimum_version, Integration, DidNotEnable
+from sentry_sdk.integrations._wsgi_common import RequestExtractor
+from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware
+from sentry_sdk.tracing import SOURCE_FOR_STYLE
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    event_from_exception,
+    parse_version,
+)
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Dict
+    from typing import Optional
+
+    from sentry_sdk._types import Event, EventProcessor
+
+# In Falcon 3.0 `falcon.api_helpers` is renamed to `falcon.app_helpers`
+# and `falcon.API` to `falcon.App`
+
+try:
+    import falcon  # type: ignore
+
+    from falcon import __version__ as FALCON_VERSION
+except ImportError:
+    raise DidNotEnable("Falcon not installed")
+
+try:
+    import falcon.app_helpers  # type: ignore
+
+    falcon_helpers = falcon.app_helpers
+    falcon_app_class = falcon.App
+    FALCON3 = True
+except ImportError:
+    import falcon.api_helpers  # type: ignore
+
+    falcon_helpers = falcon.api_helpers
+    falcon_app_class = falcon.API
+    FALCON3 = False
+
+
+_FALCON_UNSET = None  # type: Optional[object]
+if FALCON3:  # falcon.request._UNSET is only available in Falcon 3.0+
+    with capture_internal_exceptions():
+        from falcon.request import _UNSET as _FALCON_UNSET  # type: ignore[import-not-found, no-redef]
+
+
+class FalconRequestExtractor(RequestExtractor):
+    def env(self):
+        # type: () -> Dict[str, Any]
+        return self.request.env
+
+    def cookies(self):
+        # type: () -> Dict[str, Any]
+        return self.request.cookies
+
+    def form(self):
+        # type: () -> None
+        return None  # No such concept in Falcon
+
+    def files(self):
+        # type: () -> None
+        return None  # No such concept in Falcon
+
+    def raw_data(self):
+        # type: () -> Optional[str]
+
+        # As request data can only be read once we won't make this available
+        # to Sentry. Just send back a dummy string in case there was a
+        # content length.
+        # TODO(jmagnusson): Figure out if there's a way to support this
+        content_length = self.content_length()
+        if content_length > 0:
+            return "[REQUEST_CONTAINING_RAW_DATA]"
+        else:
+            return None
+
+    def json(self):
+        # type: () -> Optional[Dict[str, Any]]
+        # fallback to cached_media = None if self.request._media is not available
+        cached_media = None
+        with capture_internal_exceptions():
+            # self.request._media is the cached self.request.media
+            # value. It is only available if self.request.media
+            # has already been accessed. Therefore, reading
+            # self.request._media will not exhaust the raw request
+            # stream (self.request.bounded_stream) because it has
+            # already been read if self.request._media is set.
+            cached_media = self.request._media
+
+        if cached_media is not _FALCON_UNSET:
+            return cached_media
+
+        return None
+
+
+class SentryFalconMiddleware:
+    """Captures exceptions in Falcon requests and send to Sentry"""
+
+    def process_request(self, req, resp, *args, **kwargs):
+        # type: (Any, Any, *Any, **Any) -> None
+        integration = sentry_sdk.get_client().get_integration(FalconIntegration)
+        if integration is None:
+            return
+
+        scope = sentry_sdk.get_isolation_scope()
+        scope._name = "falcon"
+        scope.add_event_processor(_make_request_event_processor(req, integration))
+
+
+TRANSACTION_STYLE_VALUES = ("uri_template", "path")
+
+
+class FalconIntegration(Integration):
+    identifier = "falcon"
+    origin = f"auto.http.{identifier}"
+
+    transaction_style = ""
+
+    def __init__(self, transaction_style="uri_template"):
+        # type: (str) -> None
+        if transaction_style not in TRANSACTION_STYLE_VALUES:
+            raise ValueError(
+                "Invalid value for transaction_style: %s (must be in %s)"
+                % (transaction_style, TRANSACTION_STYLE_VALUES)
+            )
+        self.transaction_style = transaction_style
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+
+        version = parse_version(FALCON_VERSION)
+        _check_minimum_version(FalconIntegration, version)
+
+        _patch_wsgi_app()
+        _patch_handle_exception()
+        _patch_prepare_middleware()
+
+
+def _patch_wsgi_app():
+    # type: () -> None
+    original_wsgi_app = falcon_app_class.__call__
+
+    def sentry_patched_wsgi_app(self, env, start_response):
+        # type: (falcon.API, Any, Any) -> Any
+        integration = sentry_sdk.get_client().get_integration(FalconIntegration)
+        if integration is None:
+            return original_wsgi_app(self, env, start_response)
+
+        sentry_wrapped = SentryWsgiMiddleware(
+            lambda envi, start_resp: original_wsgi_app(self, envi, start_resp),
+            span_origin=FalconIntegration.origin,
+        )
+
+        return sentry_wrapped(env, start_response)
+
+    falcon_app_class.__call__ = sentry_patched_wsgi_app
+
+
+def _patch_handle_exception():
+    # type: () -> None
+    original_handle_exception = falcon_app_class._handle_exception
+
+    @ensure_integration_enabled(FalconIntegration, original_handle_exception)
+    def sentry_patched_handle_exception(self, *args):
+        # type: (falcon.API, *Any) -> Any
+        # NOTE(jmagnusson): falcon 2.0 changed falcon.API._handle_exception
+        # method signature from `(ex, req, resp, params)` to
+        # `(req, resp, ex, params)`
+        ex = response = None
+        with capture_internal_exceptions():
+            ex = next(argument for argument in args if isinstance(argument, Exception))
+            response = next(
+                argument for argument in args if isinstance(argument, falcon.Response)
+            )
+
+        was_handled = original_handle_exception(self, *args)
+
+        if ex is None or response is None:
+            # Both ex and response should have a non-None value at this point; otherwise,
+            # there is an error with the SDK that will have been captured in the
+            # capture_internal_exceptions block above.
+            return was_handled
+
+        if _exception_leads_to_http_5xx(ex, response):
+            event, hint = event_from_exception(
+                ex,
+                client_options=sentry_sdk.get_client().options,
+                mechanism={"type": "falcon", "handled": False},
+            )
+            sentry_sdk.capture_event(event, hint=hint)
+
+        return was_handled
+
+    falcon_app_class._handle_exception = sentry_patched_handle_exception
+
+
+def _patch_prepare_middleware():
+    # type: () -> None
+    original_prepare_middleware = falcon_helpers.prepare_middleware
+
+    def sentry_patched_prepare_middleware(
+        middleware=None, independent_middleware=False, asgi=False
+    ):
+        # type: (Any, Any, bool) -> Any
+        if asgi:
+            # We don't support ASGI Falcon apps, so we don't patch anything here
+            return original_prepare_middleware(middleware, independent_middleware, asgi)
+
+        integration = sentry_sdk.get_client().get_integration(FalconIntegration)
+        if integration is not None:
+            middleware = [SentryFalconMiddleware()] + (middleware or [])
+
+        # We intentionally omit the asgi argument here, since the default is False anyways,
+        # and this way, we remain backwards-compatible with pre-3.0.0 Falcon versions.
+        return original_prepare_middleware(middleware, independent_middleware)
+
+    falcon_helpers.prepare_middleware = sentry_patched_prepare_middleware
+
+
+def _exception_leads_to_http_5xx(ex, response):
+    # type: (Exception, falcon.Response) -> bool
+    is_server_error = isinstance(ex, falcon.HTTPError) and (ex.status or "").startswith(
+        "5"
+    )
+    is_unhandled_error = not isinstance(
+        ex, (falcon.HTTPError, falcon.http_status.HTTPStatus)
+    )
+
+    # We only check the HTTP status on Falcon 3 because in Falcon 2, the status on the response
+    # at the stage where we capture it is listed as 200, even though we would expect to see a 500
+    # status. Since at the time of this change, Falcon 2 is ca. 4 years old, we have decided to
+    # only perform this check on Falcon 3+, despite the risk that some handled errors might be
+    # reported to Sentry as unhandled on Falcon 2.
+    return (is_server_error or is_unhandled_error) and (
+        not FALCON3 or _has_http_5xx_status(response)
+    )
+
+
+def _has_http_5xx_status(response):
+    # type: (falcon.Response) -> bool
+    return response.status.startswith("5")
+
+
+def _set_transaction_name_and_source(event, transaction_style, request):
+    # type: (Event, str, falcon.Request) -> None
+    name_for_style = {
+        "uri_template": request.uri_template,
+        "path": request.path,
+    }
+    event["transaction"] = name_for_style[transaction_style]
+    event["transaction_info"] = {"source": SOURCE_FOR_STYLE[transaction_style]}
+
+
+def _make_request_event_processor(req, integration):
+    # type: (falcon.Request, FalconIntegration) -> EventProcessor
+
+    def event_processor(event, hint):
+        # type: (Event, dict[str, Any]) -> Event
+        _set_transaction_name_and_source(event, integration.transaction_style, req)
+
+        with capture_internal_exceptions():
+            FalconRequestExtractor(req).extract_into_event(event)
+
+        return event
+
+    return event_processor
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/fastapi.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/fastapi.py
new file mode 100644
index 0000000000000000000000000000000000000000..1473cbcab7ec69668562c14d7e4a141765737b2a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/fastapi.py
@@ -0,0 +1,141 @@
+import asyncio
+from copy import deepcopy
+from functools import wraps
+
+import sentry_sdk
+from sentry_sdk.integrations import DidNotEnable
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.tracing import SOURCE_FOR_STYLE, TransactionSource
+from sentry_sdk.utils import transaction_from_function
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Callable, Dict
+    from sentry_sdk._types import Event
+
+try:
+    from sentry_sdk.integrations.starlette import (
+        StarletteIntegration,
+        StarletteRequestExtractor,
+    )
+except DidNotEnable:
+    raise DidNotEnable("Starlette is not installed")
+
+try:
+    import fastapi  # type: ignore
+except ImportError:
+    raise DidNotEnable("FastAPI is not installed")
+
+
+_DEFAULT_TRANSACTION_NAME = "generic FastAPI request"
+
+
+class FastApiIntegration(StarletteIntegration):
+    identifier = "fastapi"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        patch_get_request_handler()
+
+
+def _set_transaction_name_and_source(scope, transaction_style, request):
+    # type: (sentry_sdk.Scope, str, Any) -> None
+    name = ""
+
+    if transaction_style == "endpoint":
+        endpoint = request.scope.get("endpoint")
+        if endpoint:
+            name = transaction_from_function(endpoint) or ""
+
+    elif transaction_style == "url":
+        route = request.scope.get("route")
+        if route:
+            path = getattr(route, "path", None)
+            if path is not None:
+                name = path
+
+    if not name:
+        name = _DEFAULT_TRANSACTION_NAME
+        source = TransactionSource.ROUTE
+    else:
+        source = SOURCE_FOR_STYLE[transaction_style]
+
+    scope.set_transaction_name(name, source=source)
+
+
+def patch_get_request_handler():
+    # type: () -> None
+    old_get_request_handler = fastapi.routing.get_request_handler
+
+    def _sentry_get_request_handler(*args, **kwargs):
+        # type: (*Any, **Any) -> Any
+        dependant = kwargs.get("dependant")
+        if (
+            dependant
+            and dependant.call is not None
+            and not asyncio.iscoroutinefunction(dependant.call)
+        ):
+            old_call = dependant.call
+
+            @wraps(old_call)
+            def _sentry_call(*args, **kwargs):
+                # type: (*Any, **Any) -> Any
+                current_scope = sentry_sdk.get_current_scope()
+                if current_scope.transaction is not None:
+                    current_scope.transaction.update_active_thread()
+
+                sentry_scope = sentry_sdk.get_isolation_scope()
+                if sentry_scope.profile is not None:
+                    sentry_scope.profile.update_active_thread_id()
+
+                return old_call(*args, **kwargs)
+
+            dependant.call = _sentry_call
+
+        old_app = old_get_request_handler(*args, **kwargs)
+
+        async def _sentry_app(*args, **kwargs):
+            # type: (*Any, **Any) -> Any
+            integration = sentry_sdk.get_client().get_integration(FastApiIntegration)
+            if integration is None:
+                return await old_app(*args, **kwargs)
+
+            request = args[0]
+
+            _set_transaction_name_and_source(
+                sentry_sdk.get_current_scope(), integration.transaction_style, request
+            )
+            sentry_scope = sentry_sdk.get_isolation_scope()
+            extractor = StarletteRequestExtractor(request)
+            info = await extractor.extract_request_info()
+
+            def _make_request_event_processor(req, integration):
+                # type: (Any, Any) -> Callable[[Event, Dict[str, Any]], Event]
+                def event_processor(event, hint):
+                    # type: (Event, Dict[str, Any]) -> Event
+
+                    # Extract information from request
+                    request_info = event.get("request", {})
+                    if info:
+                        if "cookies" in info and should_send_default_pii():
+                            request_info["cookies"] = info["cookies"]
+                        if "data" in info:
+                            request_info["data"] = info["data"]
+                    event["request"] = deepcopy(request_info)
+
+                    return event
+
+                return event_processor
+
+            sentry_scope._name = FastApiIntegration.identifier
+            sentry_scope.add_event_processor(
+                _make_request_event_processor(request, integration)
+            )
+
+            return await old_app(*args, **kwargs)
+
+        return _sentry_app
+
+    fastapi.routing.get_request_handler = _sentry_get_request_handler
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/flask.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/flask.py
new file mode 100644
index 0000000000000000000000000000000000000000..f45ec6db2030bde46a753326354abad4d0252938
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/flask.py
@@ -0,0 +1,275 @@
+import sentry_sdk
+from sentry_sdk.integrations import _check_minimum_version, DidNotEnable, Integration
+from sentry_sdk.integrations._wsgi_common import (
+    DEFAULT_HTTP_METHODS_TO_CAPTURE,
+    RequestExtractor,
+)
+from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.tracing import SOURCE_FOR_STYLE
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    event_from_exception,
+    package_version,
+)
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Callable, Dict, Union
+
+    from sentry_sdk._types import Event, EventProcessor
+    from sentry_sdk.integrations.wsgi import _ScopedResponse
+    from werkzeug.datastructures import FileStorage, ImmutableMultiDict
+
+
+try:
+    import flask_login  # type: ignore
+except ImportError:
+    flask_login = None
+
+try:
+    from flask import Flask, Request  # type: ignore
+    from flask import request as flask_request
+    from flask.signals import (
+        before_render_template,
+        got_request_exception,
+        request_started,
+    )
+    from markupsafe import Markup
+except ImportError:
+    raise DidNotEnable("Flask is not installed")
+
+try:
+    import blinker  # noqa
+except ImportError:
+    raise DidNotEnable("blinker is not installed")
+
+TRANSACTION_STYLE_VALUES = ("endpoint", "url")
+
+
+class FlaskIntegration(Integration):
+    identifier = "flask"
+    origin = f"auto.http.{identifier}"
+
+    transaction_style = ""
+
+    def __init__(
+        self,
+        transaction_style="endpoint",  # type: str
+        http_methods_to_capture=DEFAULT_HTTP_METHODS_TO_CAPTURE,  # type: tuple[str, ...]
+    ):
+        # type: (...) -> None
+        if transaction_style not in TRANSACTION_STYLE_VALUES:
+            raise ValueError(
+                "Invalid value for transaction_style: %s (must be in %s)"
+                % (transaction_style, TRANSACTION_STYLE_VALUES)
+            )
+        self.transaction_style = transaction_style
+        self.http_methods_to_capture = tuple(map(str.upper, http_methods_to_capture))
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        try:
+            from quart import Quart  # type: ignore
+
+            if Flask == Quart:
+                # This is Quart masquerading as Flask, don't enable the Flask
+                # integration. See https://github.com/getsentry/sentry-python/issues/2709
+                raise DidNotEnable(
+                    "This is not a Flask app but rather Quart pretending to be Flask"
+                )
+        except ImportError:
+            pass
+
+        version = package_version("flask")
+        _check_minimum_version(FlaskIntegration, version)
+
+        before_render_template.connect(_add_sentry_trace)
+        request_started.connect(_request_started)
+        got_request_exception.connect(_capture_exception)
+
+        old_app = Flask.__call__
+
+        def sentry_patched_wsgi_app(self, environ, start_response):
+            # type: (Any, Dict[str, str], Callable[..., Any]) -> _ScopedResponse
+            if sentry_sdk.get_client().get_integration(FlaskIntegration) is None:
+                return old_app(self, environ, start_response)
+
+            integration = sentry_sdk.get_client().get_integration(FlaskIntegration)
+
+            middleware = SentryWsgiMiddleware(
+                lambda *a, **kw: old_app(self, *a, **kw),
+                span_origin=FlaskIntegration.origin,
+                http_methods_to_capture=(
+                    integration.http_methods_to_capture
+                    if integration
+                    else DEFAULT_HTTP_METHODS_TO_CAPTURE
+                ),
+            )
+            return middleware(environ, start_response)
+
+        Flask.__call__ = sentry_patched_wsgi_app
+
+
+def _add_sentry_trace(sender, template, context, **extra):
+    # type: (Flask, Any, Dict[str, Any], **Any) -> None
+    if "sentry_trace" in context:
+        return
+
+    scope = sentry_sdk.get_current_scope()
+    trace_meta = Markup(scope.trace_propagation_meta())
+    context["sentry_trace"] = trace_meta  # for backwards compatibility
+    context["sentry_trace_meta"] = trace_meta
+
+
+def _set_transaction_name_and_source(scope, transaction_style, request):
+    # type: (sentry_sdk.Scope, str, Request) -> None
+    try:
+        name_for_style = {
+            "url": request.url_rule.rule,
+            "endpoint": request.url_rule.endpoint,
+        }
+        scope.set_transaction_name(
+            name_for_style[transaction_style],
+            source=SOURCE_FOR_STYLE[transaction_style],
+        )
+    except Exception:
+        pass
+
+
+def _request_started(app, **kwargs):
+    # type: (Flask, **Any) -> None
+    integration = sentry_sdk.get_client().get_integration(FlaskIntegration)
+    if integration is None:
+        return
+
+    request = flask_request._get_current_object()
+
+    # Set the transaction name and source here,
+    # but rely on WSGI middleware to actually start the transaction
+    _set_transaction_name_and_source(
+        sentry_sdk.get_current_scope(), integration.transaction_style, request
+    )
+
+    scope = sentry_sdk.get_isolation_scope()
+    evt_processor = _make_request_event_processor(app, request, integration)
+    scope.add_event_processor(evt_processor)
+
+
+class FlaskRequestExtractor(RequestExtractor):
+    def env(self):
+        # type: () -> Dict[str, str]
+        return self.request.environ
+
+    def cookies(self):
+        # type: () -> Dict[Any, Any]
+        return {
+            k: v[0] if isinstance(v, list) and len(v) == 1 else v
+            for k, v in self.request.cookies.items()
+        }
+
+    def raw_data(self):
+        # type: () -> bytes
+        return self.request.get_data()
+
+    def form(self):
+        # type: () -> ImmutableMultiDict[str, Any]
+        return self.request.form
+
+    def files(self):
+        # type: () -> ImmutableMultiDict[str, Any]
+        return self.request.files
+
+    def is_json(self):
+        # type: () -> bool
+        return self.request.is_json
+
+    def json(self):
+        # type: () -> Any
+        return self.request.get_json(silent=True)
+
+    def size_of_file(self, file):
+        # type: (FileStorage) -> int
+        return file.content_length
+
+
+def _make_request_event_processor(app, request, integration):
+    # type: (Flask, Callable[[], Request], FlaskIntegration) -> EventProcessor
+
+    def inner(event, hint):
+        # type: (Event, dict[str, Any]) -> Event
+
+        # if the request is gone we are fine not logging the data from
+        # it.  This might happen if the processor is pushed away to
+        # another thread.
+        if request is None:
+            return event
+
+        with capture_internal_exceptions():
+            FlaskRequestExtractor(request).extract_into_event(event)
+
+        if should_send_default_pii():
+            with capture_internal_exceptions():
+                _add_user_to_event(event)
+
+        return event
+
+    return inner
+
+
+@ensure_integration_enabled(FlaskIntegration)
+def _capture_exception(sender, exception, **kwargs):
+    # type: (Flask, Union[ValueError, BaseException], **Any) -> None
+    event, hint = event_from_exception(
+        exception,
+        client_options=sentry_sdk.get_client().options,
+        mechanism={"type": "flask", "handled": False},
+    )
+
+    sentry_sdk.capture_event(event, hint=hint)
+
+
+def _add_user_to_event(event):
+    # type: (Event) -> None
+    if flask_login is None:
+        return
+
+    user = flask_login.current_user
+    if user is None:
+        return
+
+    with capture_internal_exceptions():
+        # Access this object as late as possible as accessing the user
+        # is relatively costly
+
+        user_info = event.setdefault("user", {})
+
+        try:
+            user_info.setdefault("id", user.get_id())
+            # TODO: more configurable user attrs here
+        except AttributeError:
+            # might happen if:
+            # - flask_login could not be imported
+            # - flask_login is not configured
+            # - no user is logged in
+            pass
+
+        # The following attribute accesses are ineffective for the general
+        # Flask-Login case, because the User interface of Flask-Login does not
+        # care about anything but the ID. However, Flask-User (based on
+        # Flask-Login) documents a few optional extra attributes.
+        #
+        # https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/docs/source/data_models.rst#fixed-data-model-property-names
+
+        try:
+            user_info.setdefault("email", user.email)
+        except Exception:
+            pass
+
+        try:
+            user_info.setdefault("username", user.username)
+        except Exception:
+            pass
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/gcp.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/gcp.py
new file mode 100644
index 0000000000000000000000000000000000000000..c637b7414a6bfa9692789b16cac8b06b7f3c52da
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/gcp.py
@@ -0,0 +1,234 @@
+import functools
+import sys
+from copy import deepcopy
+from datetime import datetime, timedelta, timezone
+from os import environ
+
+import sentry_sdk
+from sentry_sdk.api import continue_trace
+from sentry_sdk.consts import OP
+from sentry_sdk.integrations import Integration
+from sentry_sdk.integrations._wsgi_common import _filter_headers
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.tracing import TransactionSource
+from sentry_sdk.utils import (
+    AnnotatedValue,
+    capture_internal_exceptions,
+    event_from_exception,
+    logger,
+    TimeoutThread,
+    reraise,
+)
+
+from typing import TYPE_CHECKING
+
+# Constants
+TIMEOUT_WARNING_BUFFER = 1.5  # Buffer time required to send timeout warning to Sentry
+MILLIS_TO_SECONDS = 1000.0
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import TypeVar
+    from typing import Callable
+    from typing import Optional
+
+    from sentry_sdk._types import EventProcessor, Event, Hint
+
+    F = TypeVar("F", bound=Callable[..., Any])
+
+
+def _wrap_func(func):
+    # type: (F) -> F
+    @functools.wraps(func)
+    def sentry_func(functionhandler, gcp_event, *args, **kwargs):
+        # type: (Any, Any, *Any, **Any) -> Any
+        client = sentry_sdk.get_client()
+
+        integration = client.get_integration(GcpIntegration)
+        if integration is None:
+            return func(functionhandler, gcp_event, *args, **kwargs)
+
+        configured_time = environ.get("FUNCTION_TIMEOUT_SEC")
+        if not configured_time:
+            logger.debug(
+                "The configured timeout could not be fetched from Cloud Functions configuration."
+            )
+            return func(functionhandler, gcp_event, *args, **kwargs)
+
+        configured_time = int(configured_time)
+
+        initial_time = datetime.now(timezone.utc)
+
+        with sentry_sdk.isolation_scope() as scope:
+            with capture_internal_exceptions():
+                scope.clear_breadcrumbs()
+                scope.add_event_processor(
+                    _make_request_event_processor(
+                        gcp_event, configured_time, initial_time
+                    )
+                )
+                scope.set_tag("gcp_region", environ.get("FUNCTION_REGION"))
+                timeout_thread = None
+                if (
+                    integration.timeout_warning
+                    and configured_time > TIMEOUT_WARNING_BUFFER
+                ):
+                    waiting_time = configured_time - TIMEOUT_WARNING_BUFFER
+
+                    timeout_thread = TimeoutThread(waiting_time, configured_time)
+
+                    # Starting the thread to raise timeout warning exception
+                    timeout_thread.start()
+
+            headers = {}
+            if hasattr(gcp_event, "headers"):
+                headers = gcp_event.headers
+
+            transaction = continue_trace(
+                headers,
+                op=OP.FUNCTION_GCP,
+                name=environ.get("FUNCTION_NAME", ""),
+                source=TransactionSource.COMPONENT,
+                origin=GcpIntegration.origin,
+            )
+            sampling_context = {
+                "gcp_env": {
+                    "function_name": environ.get("FUNCTION_NAME"),
+                    "function_entry_point": environ.get("ENTRY_POINT"),
+                    "function_identity": environ.get("FUNCTION_IDENTITY"),
+                    "function_region": environ.get("FUNCTION_REGION"),
+                    "function_project": environ.get("GCP_PROJECT"),
+                },
+                "gcp_event": gcp_event,
+            }
+            with sentry_sdk.start_transaction(
+                transaction, custom_sampling_context=sampling_context
+            ):
+                try:
+                    return func(functionhandler, gcp_event, *args, **kwargs)
+                except Exception:
+                    exc_info = sys.exc_info()
+                    sentry_event, hint = event_from_exception(
+                        exc_info,
+                        client_options=client.options,
+                        mechanism={"type": "gcp", "handled": False},
+                    )
+                    sentry_sdk.capture_event(sentry_event, hint=hint)
+                    reraise(*exc_info)
+                finally:
+                    if timeout_thread:
+                        timeout_thread.stop()
+                    # Flush out the event queue
+                    client.flush()
+
+    return sentry_func  # type: ignore
+
+
+class GcpIntegration(Integration):
+    identifier = "gcp"
+    origin = f"auto.function.{identifier}"
+
+    def __init__(self, timeout_warning=False):
+        # type: (bool) -> None
+        self.timeout_warning = timeout_warning
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        import __main__ as gcp_functions
+
+        if not hasattr(gcp_functions, "worker_v1"):
+            logger.warning(
+                "GcpIntegration currently supports only Python 3.7 runtime environment."
+            )
+            return
+
+        worker1 = gcp_functions.worker_v1
+
+        worker1.FunctionHandler.invoke_user_function = _wrap_func(
+            worker1.FunctionHandler.invoke_user_function
+        )
+
+
+def _make_request_event_processor(gcp_event, configured_timeout, initial_time):
+    # type: (Any, Any, Any) -> EventProcessor
+
+    def event_processor(event, hint):
+        # type: (Event, Hint) -> Optional[Event]
+
+        final_time = datetime.now(timezone.utc)
+        time_diff = final_time - initial_time
+
+        execution_duration_in_millis = time_diff / timedelta(milliseconds=1)
+
+        extra = event.setdefault("extra", {})
+        extra["google cloud functions"] = {
+            "function_name": environ.get("FUNCTION_NAME"),
+            "function_entry_point": environ.get("ENTRY_POINT"),
+            "function_identity": environ.get("FUNCTION_IDENTITY"),
+            "function_region": environ.get("FUNCTION_REGION"),
+            "function_project": environ.get("GCP_PROJECT"),
+            "execution_duration_in_millis": execution_duration_in_millis,
+            "configured_timeout_in_seconds": configured_timeout,
+        }
+
+        extra["google cloud logs"] = {
+            "url": _get_google_cloud_logs_url(final_time),
+        }
+
+        request = event.get("request", {})
+
+        request["url"] = "gcp:///{}".format(environ.get("FUNCTION_NAME"))
+
+        if hasattr(gcp_event, "method"):
+            request["method"] = gcp_event.method
+
+        if hasattr(gcp_event, "query_string"):
+            request["query_string"] = gcp_event.query_string.decode("utf-8")
+
+        if hasattr(gcp_event, "headers"):
+            request["headers"] = _filter_headers(gcp_event.headers)
+
+        if should_send_default_pii():
+            if hasattr(gcp_event, "data"):
+                request["data"] = gcp_event.data
+        else:
+            if hasattr(gcp_event, "data"):
+                # Unfortunately couldn't find a way to get structured body from GCP
+                # event. Meaning every body is unstructured to us.
+                request["data"] = AnnotatedValue.removed_because_raw_data()
+
+        event["request"] = deepcopy(request)
+
+        return event
+
+    return event_processor
+
+
+def _get_google_cloud_logs_url(final_time):
+    # type: (datetime) -> str
+    """
+    Generates a Google Cloud Logs console URL based on the environment variables
+    Arguments:
+        final_time {datetime} -- Final time
+    Returns:
+        str -- Google Cloud Logs Console URL to logs.
+    """
+    hour_ago = final_time - timedelta(hours=1)
+    formatstring = "%Y-%m-%dT%H:%M:%SZ"
+
+    url = (
+        "https://console.cloud.google.com/logs/viewer?project={project}&resource=cloud_function"
+        "%2Ffunction_name%2F{function_name}%2Fregion%2F{region}&minLogLevel=0&expandAll=false"
+        "×tamp={timestamp_end}&customFacets=&limitCustomFacetWidth=true"
+        "&dateRangeStart={timestamp_start}&dateRangeEnd={timestamp_end}"
+        "&interval=PT1H&scrollTimestamp={timestamp_end}"
+    ).format(
+        project=environ.get("GCP_PROJECT"),
+        function_name=environ.get("FUNCTION_NAME"),
+        region=environ.get("FUNCTION_REGION"),
+        timestamp_end=final_time.strftime(formatstring),
+        timestamp_start=hour_ago.strftime(formatstring),
+    )
+
+    return url
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/gnu_backtrace.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/gnu_backtrace.py
new file mode 100644
index 0000000000000000000000000000000000000000..8241e27f13e4728c231405af1a94479e11ac71c9
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/gnu_backtrace.py
@@ -0,0 +1,99 @@
+import re
+
+import sentry_sdk
+from sentry_sdk.integrations import Integration
+from sentry_sdk.scope import add_global_event_processor
+from sentry_sdk.utils import capture_internal_exceptions
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from sentry_sdk._types import Event
+
+# function is everything between index at @
+# and then we match on the @ plus the hex val
+FUNCTION_RE = r"[^@]+?"
+HEX_ADDRESS = r"\s+@\s+0x[0-9a-fA-F]+"
+
+FRAME_RE = r"""
+^(?P\d+)\.\s+(?P{FUNCTION_RE}){HEX_ADDRESS}(?:\s+in\s+(?P.+))?$
+""".format(
+    FUNCTION_RE=FUNCTION_RE,
+    HEX_ADDRESS=HEX_ADDRESS,
+)
+
+FRAME_RE = re.compile(FRAME_RE, re.MULTILINE | re.VERBOSE)
+
+
+class GnuBacktraceIntegration(Integration):
+    identifier = "gnu_backtrace"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        @add_global_event_processor
+        def process_gnu_backtrace(event, hint):
+            # type: (Event, dict[str, Any]) -> Event
+            with capture_internal_exceptions():
+                return _process_gnu_backtrace(event, hint)
+
+
+def _process_gnu_backtrace(event, hint):
+    # type: (Event, dict[str, Any]) -> Event
+    if sentry_sdk.get_client().get_integration(GnuBacktraceIntegration) is None:
+        return event
+
+    exc_info = hint.get("exc_info", None)
+
+    if exc_info is None:
+        return event
+
+    exception = event.get("exception", None)
+
+    if exception is None:
+        return event
+
+    values = exception.get("values", None)
+
+    if values is None:
+        return event
+
+    for exception in values:
+        frames = exception.get("stacktrace", {}).get("frames", [])
+        if not frames:
+            continue
+
+        msg = exception.get("value", None)
+        if not msg:
+            continue
+
+        additional_frames = []
+        new_msg = []
+
+        for line in msg.splitlines():
+            match = FRAME_RE.match(line)
+            if match:
+                additional_frames.append(
+                    (
+                        int(match.group("index")),
+                        {
+                            "package": match.group("package") or None,
+                            "function": match.group("function") or None,
+                            "platform": "native",
+                        },
+                    )
+                )
+            else:
+                # Put garbage lines back into message, not sure what to do with them.
+                new_msg.append(line)
+
+        if additional_frames:
+            additional_frames.sort(key=lambda x: -x[0])
+            for _, frame in additional_frames:
+                frames.append(frame)
+
+            new_msg.append("")
+            exception["value"] = "\n".join(new_msg)
+
+    return event
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/gql.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/gql.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f4436f5b2ad7958a9c0e580d6fb40ce58f707ae
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/gql.py
@@ -0,0 +1,145 @@
+import sentry_sdk
+from sentry_sdk.utils import (
+    event_from_exception,
+    ensure_integration_enabled,
+    parse_version,
+)
+
+from sentry_sdk.integrations import _check_minimum_version, DidNotEnable, Integration
+from sentry_sdk.scope import should_send_default_pii
+
+try:
+    import gql  # type: ignore[import-not-found]
+    from graphql import (
+        print_ast,
+        get_operation_ast,
+        DocumentNode,
+        VariableDefinitionNode,
+    )
+    from gql.transport import Transport, AsyncTransport  # type: ignore[import-not-found]
+    from gql.transport.exceptions import TransportQueryError  # type: ignore[import-not-found]
+except ImportError:
+    raise DidNotEnable("gql is not installed")
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Dict, Tuple, Union
+    from sentry_sdk._types import Event, EventProcessor
+
+    EventDataType = Dict[str, Union[str, Tuple[VariableDefinitionNode, ...]]]
+
+
+class GQLIntegration(Integration):
+    identifier = "gql"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        gql_version = parse_version(gql.__version__)
+        _check_minimum_version(GQLIntegration, gql_version)
+
+        _patch_execute()
+
+
+def _data_from_document(document):
+    # type: (DocumentNode) -> EventDataType
+    try:
+        operation_ast = get_operation_ast(document)
+        data = {"query": print_ast(document)}  # type: EventDataType
+
+        if operation_ast is not None:
+            data["variables"] = operation_ast.variable_definitions
+            if operation_ast.name is not None:
+                data["operationName"] = operation_ast.name.value
+
+        return data
+    except (AttributeError, TypeError):
+        return dict()
+
+
+def _transport_method(transport):
+    # type: (Union[Transport, AsyncTransport]) -> str
+    """
+    The RequestsHTTPTransport allows defining the HTTP method; all
+    other transports use POST.
+    """
+    try:
+        return transport.method
+    except AttributeError:
+        return "POST"
+
+
+def _request_info_from_transport(transport):
+    # type: (Union[Transport, AsyncTransport, None]) -> Dict[str, str]
+    if transport is None:
+        return {}
+
+    request_info = {
+        "method": _transport_method(transport),
+    }
+
+    try:
+        request_info["url"] = transport.url
+    except AttributeError:
+        pass
+
+    return request_info
+
+
+def _patch_execute():
+    # type: () -> None
+    real_execute = gql.Client.execute
+
+    @ensure_integration_enabled(GQLIntegration, real_execute)
+    def sentry_patched_execute(self, document, *args, **kwargs):
+        # type: (gql.Client, DocumentNode, Any, Any) -> Any
+        scope = sentry_sdk.get_isolation_scope()
+        scope.add_event_processor(_make_gql_event_processor(self, document))
+
+        try:
+            return real_execute(self, document, *args, **kwargs)
+        except TransportQueryError as e:
+            event, hint = event_from_exception(
+                e,
+                client_options=sentry_sdk.get_client().options,
+                mechanism={"type": "gql", "handled": False},
+            )
+
+            sentry_sdk.capture_event(event, hint)
+            raise e
+
+    gql.Client.execute = sentry_patched_execute
+
+
+def _make_gql_event_processor(client, document):
+    # type: (gql.Client, DocumentNode) -> EventProcessor
+    def processor(event, hint):
+        # type: (Event, dict[str, Any]) -> Event
+        try:
+            errors = hint["exc_info"][1].errors
+        except (AttributeError, KeyError):
+            errors = None
+
+        request = event.setdefault("request", {})
+        request.update(
+            {
+                "api_target": "graphql",
+                **_request_info_from_transport(client.transport),
+            }
+        )
+
+        if should_send_default_pii():
+            request["data"] = _data_from_document(document)
+            contexts = event.setdefault("contexts", {})
+            response = contexts.setdefault("response", {})
+            response.update(
+                {
+                    "data": {"errors": errors},
+                    "type": response,
+                }
+            )
+
+        return event
+
+    return processor
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/graphene.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/graphene.py
new file mode 100644
index 0000000000000000000000000000000000000000..00a8d155d46c86614db87ae2fc44bc0a39df65a4
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/graphene.py
@@ -0,0 +1,151 @@
+from contextlib import contextmanager
+
+import sentry_sdk
+from sentry_sdk.consts import OP
+from sentry_sdk.integrations import _check_minimum_version, DidNotEnable, Integration
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    event_from_exception,
+    package_version,
+)
+
+try:
+    from graphene.types import schema as graphene_schema  # type: ignore
+except ImportError:
+    raise DidNotEnable("graphene is not installed")
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from collections.abc import Generator
+    from typing import Any, Dict, Union
+    from graphene.language.source import Source  # type: ignore
+    from graphql.execution import ExecutionResult
+    from graphql.type import GraphQLSchema
+    from sentry_sdk._types import Event
+
+
+class GrapheneIntegration(Integration):
+    identifier = "graphene"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        version = package_version("graphene")
+        _check_minimum_version(GrapheneIntegration, version)
+
+        _patch_graphql()
+
+
+def _patch_graphql():
+    # type: () -> None
+    old_graphql_sync = graphene_schema.graphql_sync
+    old_graphql_async = graphene_schema.graphql
+
+    @ensure_integration_enabled(GrapheneIntegration, old_graphql_sync)
+    def _sentry_patched_graphql_sync(schema, source, *args, **kwargs):
+        # type: (GraphQLSchema, Union[str, Source], Any, Any) -> ExecutionResult
+        scope = sentry_sdk.get_isolation_scope()
+        scope.add_event_processor(_event_processor)
+
+        with graphql_span(schema, source, kwargs):
+            result = old_graphql_sync(schema, source, *args, **kwargs)
+
+        with capture_internal_exceptions():
+            client = sentry_sdk.get_client()
+            for error in result.errors or []:
+                event, hint = event_from_exception(
+                    error,
+                    client_options=client.options,
+                    mechanism={
+                        "type": GrapheneIntegration.identifier,
+                        "handled": False,
+                    },
+                )
+                sentry_sdk.capture_event(event, hint=hint)
+
+        return result
+
+    async def _sentry_patched_graphql_async(schema, source, *args, **kwargs):
+        # type: (GraphQLSchema, Union[str, Source], Any, Any) -> ExecutionResult
+        integration = sentry_sdk.get_client().get_integration(GrapheneIntegration)
+        if integration is None:
+            return await old_graphql_async(schema, source, *args, **kwargs)
+
+        scope = sentry_sdk.get_isolation_scope()
+        scope.add_event_processor(_event_processor)
+
+        with graphql_span(schema, source, kwargs):
+            result = await old_graphql_async(schema, source, *args, **kwargs)
+
+        with capture_internal_exceptions():
+            client = sentry_sdk.get_client()
+            for error in result.errors or []:
+                event, hint = event_from_exception(
+                    error,
+                    client_options=client.options,
+                    mechanism={
+                        "type": GrapheneIntegration.identifier,
+                        "handled": False,
+                    },
+                )
+                sentry_sdk.capture_event(event, hint=hint)
+
+        return result
+
+    graphene_schema.graphql_sync = _sentry_patched_graphql_sync
+    graphene_schema.graphql = _sentry_patched_graphql_async
+
+
+def _event_processor(event, hint):
+    # type: (Event, Dict[str, Any]) -> Event
+    if should_send_default_pii():
+        request_info = event.setdefault("request", {})
+        request_info["api_target"] = "graphql"
+
+    elif event.get("request", {}).get("data"):
+        del event["request"]["data"]
+
+    return event
+
+
+@contextmanager
+def graphql_span(schema, source, kwargs):
+    # type: (GraphQLSchema, Union[str, Source], Dict[str, Any]) -> Generator[None, None, None]
+    operation_name = kwargs.get("operation_name")
+
+    operation_type = "query"
+    op = OP.GRAPHQL_QUERY
+    if source.strip().startswith("mutation"):
+        operation_type = "mutation"
+        op = OP.GRAPHQL_MUTATION
+    elif source.strip().startswith("subscription"):
+        operation_type = "subscription"
+        op = OP.GRAPHQL_SUBSCRIPTION
+
+    sentry_sdk.add_breadcrumb(
+        crumb={
+            "data": {
+                "operation_name": operation_name,
+                "operation_type": operation_type,
+            },
+            "category": "graphql.operation",
+        },
+    )
+
+    scope = sentry_sdk.get_current_scope()
+    if scope.span:
+        _graphql_span = scope.span.start_child(op=op, name=operation_name)
+    else:
+        _graphql_span = sentry_sdk.start_span(op=op, name=operation_name)
+
+    _graphql_span.set_data("graphql.document", source)
+    _graphql_span.set_data("graphql.operation.name", operation_name)
+    _graphql_span.set_data("graphql.operation.type", operation_type)
+
+    try:
+        yield
+    finally:
+        _graphql_span.finish()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e15f95ae5a7949911cea926714ecdab209ebd9c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/__init__.py
@@ -0,0 +1,168 @@
+from functools import wraps
+
+import grpc
+from grpc import Channel, Server, intercept_channel
+from grpc.aio import Channel as AsyncChannel
+from grpc.aio import Server as AsyncServer
+
+from sentry_sdk.integrations import Integration
+from sentry_sdk.utils import parse_version
+
+from .client import ClientInterceptor
+from .server import ServerInterceptor
+from .aio.server import ServerInterceptor as AsyncServerInterceptor
+from .aio.client import (
+    SentryUnaryUnaryClientInterceptor as AsyncUnaryUnaryClientInterceptor,
+)
+from .aio.client import (
+    SentryUnaryStreamClientInterceptor as AsyncUnaryStreamClientIntercetor,
+)
+
+from typing import TYPE_CHECKING, Any, Optional, Sequence
+
+# Hack to get new Python features working in older versions
+# without introducing a hard dependency on `typing_extensions`
+# from: https://stackoverflow.com/a/71944042/300572
+if TYPE_CHECKING:
+    from typing import ParamSpec, Callable
+else:
+    # Fake ParamSpec
+    class ParamSpec:
+        def __init__(self, _):
+            self.args = None
+            self.kwargs = None
+
+    # Callable[anything] will return None
+    class _Callable:
+        def __getitem__(self, _):
+            return None
+
+    # Make instances
+    Callable = _Callable()
+
+P = ParamSpec("P")
+
+GRPC_VERSION = parse_version(grpc.__version__)
+
+
+def _wrap_channel_sync(func: Callable[P, Channel]) -> Callable[P, Channel]:
+    "Wrapper for synchronous secure and insecure channel."
+
+    @wraps(func)
+    def patched_channel(*args: Any, **kwargs: Any) -> Channel:
+        channel = func(*args, **kwargs)
+        if not ClientInterceptor._is_intercepted:
+            ClientInterceptor._is_intercepted = True
+            return intercept_channel(channel, ClientInterceptor())
+        else:
+            return channel
+
+    return patched_channel
+
+
+def _wrap_intercept_channel(func: Callable[P, Channel]) -> Callable[P, Channel]:
+    @wraps(func)
+    def patched_intercept_channel(
+        channel: Channel, *interceptors: grpc.ServerInterceptor
+    ) -> Channel:
+        if ClientInterceptor._is_intercepted:
+            interceptors = tuple(
+                [
+                    interceptor
+                    for interceptor in interceptors
+                    if not isinstance(interceptor, ClientInterceptor)
+                ]
+            )
+        else:
+            interceptors = interceptors
+        return intercept_channel(channel, *interceptors)
+
+    return patched_intercept_channel  # type: ignore
+
+
+def _wrap_channel_async(func: Callable[P, AsyncChannel]) -> Callable[P, AsyncChannel]:
+    "Wrapper for asynchronous secure and insecure channel."
+
+    @wraps(func)
+    def patched_channel(  # type: ignore
+        *args: P.args,
+        interceptors: Optional[Sequence[grpc.aio.ClientInterceptor]] = None,
+        **kwargs: P.kwargs,
+    ) -> Channel:
+        sentry_interceptors = [
+            AsyncUnaryUnaryClientInterceptor(),
+            AsyncUnaryStreamClientIntercetor(),
+        ]
+        interceptors = [*sentry_interceptors, *(interceptors or [])]
+        return func(*args, interceptors=interceptors, **kwargs)  # type: ignore
+
+    return patched_channel  # type: ignore
+
+
+def _wrap_sync_server(func: Callable[P, Server]) -> Callable[P, Server]:
+    """Wrapper for synchronous server."""
+
+    @wraps(func)
+    def patched_server(  # type: ignore
+        *args: P.args,
+        interceptors: Optional[Sequence[grpc.ServerInterceptor]] = None,
+        **kwargs: P.kwargs,
+    ) -> Server:
+        interceptors = [
+            interceptor
+            for interceptor in interceptors or []
+            if not isinstance(interceptor, ServerInterceptor)
+        ]
+        server_interceptor = ServerInterceptor()
+        interceptors = [server_interceptor, *(interceptors or [])]
+        return func(*args, interceptors=interceptors, **kwargs)  # type: ignore
+
+    return patched_server  # type: ignore
+
+
+def _wrap_async_server(func: Callable[P, AsyncServer]) -> Callable[P, AsyncServer]:
+    """Wrapper for asynchronous server."""
+
+    @wraps(func)
+    def patched_aio_server(  # type: ignore
+        *args: P.args,
+        interceptors: Optional[Sequence[grpc.ServerInterceptor]] = None,
+        **kwargs: P.kwargs,
+    ) -> Server:
+        server_interceptor = AsyncServerInterceptor()
+        interceptors = [
+            server_interceptor,
+            *(interceptors or []),
+        ]  # type: Sequence[grpc.ServerInterceptor]
+
+        try:
+            # We prefer interceptors as a list because of compatibility with
+            # opentelemetry https://github.com/getsentry/sentry-python/issues/4389
+            # However, prior to grpc 1.42.0, only tuples were accepted, so we
+            # have no choice there.
+            if GRPC_VERSION is not None and GRPC_VERSION < (1, 42, 0):
+                interceptors = tuple(interceptors)
+        except Exception:
+            pass
+
+        return func(*args, interceptors=interceptors, **kwargs)  # type: ignore
+
+    return patched_aio_server  # type: ignore
+
+
+class GRPCIntegration(Integration):
+    identifier = "grpc"
+
+    @staticmethod
+    def setup_once() -> None:
+        import grpc
+
+        grpc.insecure_channel = _wrap_channel_sync(grpc.insecure_channel)
+        grpc.secure_channel = _wrap_channel_sync(grpc.secure_channel)
+        grpc.intercept_channel = _wrap_intercept_channel(grpc.intercept_channel)
+
+        grpc.aio.insecure_channel = _wrap_channel_async(grpc.aio.insecure_channel)
+        grpc.aio.secure_channel = _wrap_channel_async(grpc.aio.secure_channel)
+
+        grpc.server = _wrap_sync_server(grpc.server)
+        grpc.aio.server = _wrap_async_server(grpc.aio.server)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..77f03f0f12f70d7caddebb1dbafb578dbc5ed0ea
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/__pycache__/client.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/__pycache__/client.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b44024b17ba20e911cf5dba47821f7475f7eec21
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/__pycache__/client.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/__pycache__/consts.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/__pycache__/consts.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1d5d49a593d36c4e8c1f3ea0fe82caa2a58128ac
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/__pycache__/consts.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/__pycache__/server.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/__pycache__/server.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..72310e1818a03f6a54908c3e0732b4a57922125d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/__pycache__/server.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/aio/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/aio/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b9e3b99495673a081f5f6d9cdf5907e70a8ff9d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/aio/__init__.py
@@ -0,0 +1,7 @@
+from .server import ServerInterceptor
+from .client import ClientInterceptor
+
+__all__ = [
+    "ClientInterceptor",
+    "ServerInterceptor",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/aio/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/aio/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..54919f39ad86b7139146f0e759e346eecc0e3668
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/aio/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/aio/__pycache__/client.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/aio/__pycache__/client.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..18b4621cee71ab24a45e0eb440369f8ab12417ce
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/aio/__pycache__/client.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/aio/__pycache__/server.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/aio/__pycache__/server.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7fd70ee98e630d39a036af7722ef7aea81cc6986
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/aio/__pycache__/server.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/aio/client.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/aio/client.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff3c21317643f56a5c888bdd3475b1f19b9686cd
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/aio/client.py
@@ -0,0 +1,94 @@
+from typing import Callable, Union, AsyncIterable, Any
+
+from grpc.aio import (
+    UnaryUnaryClientInterceptor,
+    UnaryStreamClientInterceptor,
+    ClientCallDetails,
+    UnaryUnaryCall,
+    UnaryStreamCall,
+    Metadata,
+)
+from google.protobuf.message import Message
+
+import sentry_sdk
+from sentry_sdk.consts import OP
+from sentry_sdk.integrations.grpc.consts import SPAN_ORIGIN
+
+
+class ClientInterceptor:
+    @staticmethod
+    def _update_client_call_details_metadata_from_scope(
+        client_call_details: ClientCallDetails,
+    ) -> ClientCallDetails:
+        if client_call_details.metadata is None:
+            client_call_details = client_call_details._replace(metadata=Metadata())
+        elif not isinstance(client_call_details.metadata, Metadata):
+            # This is a workaround for a GRPC bug, which was fixed in grpcio v1.60.0
+            # See https://github.com/grpc/grpc/issues/34298.
+            client_call_details = client_call_details._replace(
+                metadata=Metadata.from_tuple(client_call_details.metadata)
+            )
+        for (
+            key,
+            value,
+        ) in sentry_sdk.get_current_scope().iter_trace_propagation_headers():
+            client_call_details.metadata.add(key, value)
+        return client_call_details
+
+
+class SentryUnaryUnaryClientInterceptor(ClientInterceptor, UnaryUnaryClientInterceptor):  # type: ignore
+    async def intercept_unary_unary(
+        self,
+        continuation: Callable[[ClientCallDetails, Message], UnaryUnaryCall],
+        client_call_details: ClientCallDetails,
+        request: Message,
+    ) -> Union[UnaryUnaryCall, Message]:
+        method = client_call_details.method
+
+        with sentry_sdk.start_span(
+            op=OP.GRPC_CLIENT,
+            name="unary unary call to %s" % method.decode(),
+            origin=SPAN_ORIGIN,
+        ) as span:
+            span.set_data("type", "unary unary")
+            span.set_data("method", method)
+
+            client_call_details = self._update_client_call_details_metadata_from_scope(
+                client_call_details
+            )
+
+            response = await continuation(client_call_details, request)
+            status_code = await response.code()
+            span.set_data("code", status_code.name)
+
+            return response
+
+
+class SentryUnaryStreamClientInterceptor(
+    ClientInterceptor, UnaryStreamClientInterceptor  # type: ignore
+):
+    async def intercept_unary_stream(
+        self,
+        continuation: Callable[[ClientCallDetails, Message], UnaryStreamCall],
+        client_call_details: ClientCallDetails,
+        request: Message,
+    ) -> Union[AsyncIterable[Any], UnaryStreamCall]:
+        method = client_call_details.method
+
+        with sentry_sdk.start_span(
+            op=OP.GRPC_CLIENT,
+            name="unary stream call to %s" % method.decode(),
+            origin=SPAN_ORIGIN,
+        ) as span:
+            span.set_data("type", "unary stream")
+            span.set_data("method", method)
+
+            client_call_details = self._update_client_call_details_metadata_from_scope(
+                client_call_details
+            )
+
+            response = await continuation(client_call_details, request)
+            # status_code = await response.code()
+            # span.set_data("code", status_code)
+
+            return response
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/aio/server.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/aio/server.py
new file mode 100644
index 0000000000000000000000000000000000000000..381c63103ea3a065d6a70a126fe880a184645510
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/aio/server.py
@@ -0,0 +1,100 @@
+import sentry_sdk
+from sentry_sdk.consts import OP
+from sentry_sdk.integrations import DidNotEnable
+from sentry_sdk.integrations.grpc.consts import SPAN_ORIGIN
+from sentry_sdk.tracing import Transaction, TransactionSource
+from sentry_sdk.utils import event_from_exception
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from collections.abc import Awaitable, Callable
+    from typing import Any, Optional
+
+
+try:
+    import grpc
+    from grpc import HandlerCallDetails, RpcMethodHandler
+    from grpc.aio import AbortError, ServicerContext
+except ImportError:
+    raise DidNotEnable("grpcio is not installed")
+
+
+class ServerInterceptor(grpc.aio.ServerInterceptor):  # type: ignore
+    def __init__(self, find_name=None):
+        # type: (ServerInterceptor, Callable[[ServicerContext], str] | None) -> None
+        self._find_method_name = find_name or self._find_name
+
+        super().__init__()
+
+    async def intercept_service(self, continuation, handler_call_details):
+        # type: (ServerInterceptor, Callable[[HandlerCallDetails], Awaitable[RpcMethodHandler]], HandlerCallDetails) -> Optional[Awaitable[RpcMethodHandler]]
+        self._handler_call_details = handler_call_details
+        handler = await continuation(handler_call_details)
+        if handler is None:
+            return None
+
+        if not handler.request_streaming and not handler.response_streaming:
+            handler_factory = grpc.unary_unary_rpc_method_handler
+
+            async def wrapped(request, context):
+                # type: (Any, ServicerContext) -> Any
+                name = self._find_method_name(context)
+                if not name:
+                    return await handler(request, context)
+
+                # What if the headers are empty?
+                transaction = Transaction.continue_from_headers(
+                    dict(context.invocation_metadata()),
+                    op=OP.GRPC_SERVER,
+                    name=name,
+                    source=TransactionSource.CUSTOM,
+                    origin=SPAN_ORIGIN,
+                )
+
+                with sentry_sdk.start_transaction(transaction=transaction):
+                    try:
+                        return await handler.unary_unary(request, context)
+                    except AbortError:
+                        raise
+                    except Exception as exc:
+                        event, hint = event_from_exception(
+                            exc,
+                            mechanism={"type": "grpc", "handled": False},
+                        )
+                        sentry_sdk.capture_event(event, hint=hint)
+                        raise
+
+        elif not handler.request_streaming and handler.response_streaming:
+            handler_factory = grpc.unary_stream_rpc_method_handler
+
+            async def wrapped(request, context):  # type: ignore
+                # type: (Any, ServicerContext) -> Any
+                async for r in handler.unary_stream(request, context):
+                    yield r
+
+        elif handler.request_streaming and not handler.response_streaming:
+            handler_factory = grpc.stream_unary_rpc_method_handler
+
+            async def wrapped(request, context):
+                # type: (Any, ServicerContext) -> Any
+                response = handler.stream_unary(request, context)
+                return await response
+
+        elif handler.request_streaming and handler.response_streaming:
+            handler_factory = grpc.stream_stream_rpc_method_handler
+
+            async def wrapped(request, context):  # type: ignore
+                # type: (Any, ServicerContext) -> Any
+                async for r in handler.stream_stream(request, context):
+                    yield r
+
+        return handler_factory(
+            wrapped,
+            request_deserializer=handler.request_deserializer,
+            response_serializer=handler.response_serializer,
+        )
+
+    def _find_name(self, context):
+        # type: (ServicerContext) -> str
+        return self._handler_call_details.method
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/client.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/client.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5b4f9f52e044d4780780e5d0cb41de65e010d42
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/client.py
@@ -0,0 +1,92 @@
+import sentry_sdk
+from sentry_sdk.consts import OP
+from sentry_sdk.integrations import DidNotEnable
+from sentry_sdk.integrations.grpc.consts import SPAN_ORIGIN
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Callable, Iterator, Iterable, Union
+
+try:
+    import grpc
+    from grpc import ClientCallDetails, Call
+    from grpc._interceptor import _UnaryOutcome
+    from grpc.aio._interceptor import UnaryStreamCall
+    from google.protobuf.message import Message
+except ImportError:
+    raise DidNotEnable("grpcio is not installed")
+
+
+class ClientInterceptor(
+    grpc.UnaryUnaryClientInterceptor, grpc.UnaryStreamClientInterceptor  # type: ignore
+):
+    _is_intercepted = False
+
+    def intercept_unary_unary(self, continuation, client_call_details, request):
+        # type: (ClientInterceptor, Callable[[ClientCallDetails, Message], _UnaryOutcome], ClientCallDetails, Message) -> _UnaryOutcome
+        method = client_call_details.method
+
+        with sentry_sdk.start_span(
+            op=OP.GRPC_CLIENT,
+            name="unary unary call to %s" % method,
+            origin=SPAN_ORIGIN,
+        ) as span:
+            span.set_data("type", "unary unary")
+            span.set_data("method", method)
+
+            client_call_details = self._update_client_call_details_metadata_from_scope(
+                client_call_details
+            )
+
+            response = continuation(client_call_details, request)
+            span.set_data("code", response.code().name)
+
+            return response
+
+    def intercept_unary_stream(self, continuation, client_call_details, request):
+        # type: (ClientInterceptor, Callable[[ClientCallDetails, Message], Union[Iterable[Any], UnaryStreamCall]], ClientCallDetails, Message) -> Union[Iterator[Message], Call]
+        method = client_call_details.method
+
+        with sentry_sdk.start_span(
+            op=OP.GRPC_CLIENT,
+            name="unary stream call to %s" % method,
+            origin=SPAN_ORIGIN,
+        ) as span:
+            span.set_data("type", "unary stream")
+            span.set_data("method", method)
+
+            client_call_details = self._update_client_call_details_metadata_from_scope(
+                client_call_details
+            )
+
+            response = continuation(
+                client_call_details, request
+            )  # type: UnaryStreamCall
+            # Setting code on unary-stream leads to execution getting stuck
+            # span.set_data("code", response.code().name)
+
+            return response
+
+    @staticmethod
+    def _update_client_call_details_metadata_from_scope(client_call_details):
+        # type: (ClientCallDetails) -> ClientCallDetails
+        metadata = (
+            list(client_call_details.metadata) if client_call_details.metadata else []
+        )
+        for (
+            key,
+            value,
+        ) in sentry_sdk.get_current_scope().iter_trace_propagation_headers():
+            metadata.append((key, value))
+
+        client_call_details = grpc._interceptor._ClientCallDetails(
+            method=client_call_details.method,
+            timeout=client_call_details.timeout,
+            metadata=metadata,
+            credentials=client_call_details.credentials,
+            wait_for_ready=client_call_details.wait_for_ready,
+            compression=client_call_details.compression,
+        )
+
+        return client_call_details
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/consts.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/consts.py
new file mode 100644
index 0000000000000000000000000000000000000000..9fdb975caf4cb43463844bddc3d411ae6d974e5a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/consts.py
@@ -0,0 +1 @@
+SPAN_ORIGIN = "auto.grpc.grpc"
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/server.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/server.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d2792d1b772164bdf5f22c0d9d382c7b8297017
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/grpc/server.py
@@ -0,0 +1,66 @@
+import sentry_sdk
+from sentry_sdk.consts import OP
+from sentry_sdk.integrations import DidNotEnable
+from sentry_sdk.integrations.grpc.consts import SPAN_ORIGIN
+from sentry_sdk.tracing import Transaction, TransactionSource
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Callable, Optional
+    from google.protobuf.message import Message
+
+try:
+    import grpc
+    from grpc import ServicerContext, HandlerCallDetails, RpcMethodHandler
+except ImportError:
+    raise DidNotEnable("grpcio is not installed")
+
+
+class ServerInterceptor(grpc.ServerInterceptor):  # type: ignore
+    def __init__(self, find_name=None):
+        # type: (ServerInterceptor, Optional[Callable[[ServicerContext], str]]) -> None
+        self._find_method_name = find_name or ServerInterceptor._find_name
+
+        super().__init__()
+
+    def intercept_service(self, continuation, handler_call_details):
+        # type: (ServerInterceptor, Callable[[HandlerCallDetails], RpcMethodHandler], HandlerCallDetails) -> RpcMethodHandler
+        handler = continuation(handler_call_details)
+        if not handler or not handler.unary_unary:
+            return handler
+
+        def behavior(request, context):
+            # type: (Message, ServicerContext) -> Message
+            with sentry_sdk.isolation_scope():
+                name = self._find_method_name(context)
+
+                if name:
+                    metadata = dict(context.invocation_metadata())
+
+                    transaction = Transaction.continue_from_headers(
+                        metadata,
+                        op=OP.GRPC_SERVER,
+                        name=name,
+                        source=TransactionSource.CUSTOM,
+                        origin=SPAN_ORIGIN,
+                    )
+
+                    with sentry_sdk.start_transaction(transaction=transaction):
+                        try:
+                            return handler.unary_unary(request, context)
+                        except BaseException as e:
+                            raise e
+                else:
+                    return handler.unary_unary(request, context)
+
+        return grpc.unary_unary_rpc_method_handler(
+            behavior,
+            request_deserializer=handler.request_deserializer,
+            response_serializer=handler.response_serializer,
+        )
+
+    @staticmethod
+    def _find_name(context):
+        # type: (ServicerContext) -> str
+        return context._rpc_event.call_details.method.decode()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/httpx.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/httpx.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ddd44489fa38c8f3f62648cd9763fcd72bcf112
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/httpx.py
@@ -0,0 +1,167 @@
+import sentry_sdk
+from sentry_sdk.consts import OP, SPANDATA
+from sentry_sdk.integrations import Integration, DidNotEnable
+from sentry_sdk.tracing import BAGGAGE_HEADER_NAME
+from sentry_sdk.tracing_utils import Baggage, should_propagate_trace
+from sentry_sdk.utils import (
+    SENSITIVE_DATA_SUBSTITUTE,
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    logger,
+    parse_url,
+)
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from collections.abc import MutableMapping
+    from typing import Any
+
+
+try:
+    from httpx import AsyncClient, Client, Request, Response  # type: ignore
+except ImportError:
+    raise DidNotEnable("httpx is not installed")
+
+__all__ = ["HttpxIntegration"]
+
+
+class HttpxIntegration(Integration):
+    identifier = "httpx"
+    origin = f"auto.http.{identifier}"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        """
+        httpx has its own transport layer and can be customized when needed,
+        so patch Client.send and AsyncClient.send to support both synchronous and async interfaces.
+        """
+        _install_httpx_client()
+        _install_httpx_async_client()
+
+
+def _install_httpx_client():
+    # type: () -> None
+    real_send = Client.send
+
+    @ensure_integration_enabled(HttpxIntegration, real_send)
+    def send(self, request, **kwargs):
+        # type: (Client, Request, **Any) -> Response
+        parsed_url = None
+        with capture_internal_exceptions():
+            parsed_url = parse_url(str(request.url), sanitize=False)
+
+        with sentry_sdk.start_span(
+            op=OP.HTTP_CLIENT,
+            name="%s %s"
+            % (
+                request.method,
+                parsed_url.url if parsed_url else SENSITIVE_DATA_SUBSTITUTE,
+            ),
+            origin=HttpxIntegration.origin,
+        ) as span:
+            span.set_data(SPANDATA.HTTP_METHOD, request.method)
+            if parsed_url is not None:
+                span.set_data("url", parsed_url.url)
+                span.set_data(SPANDATA.HTTP_QUERY, parsed_url.query)
+                span.set_data(SPANDATA.HTTP_FRAGMENT, parsed_url.fragment)
+
+            if should_propagate_trace(sentry_sdk.get_client(), str(request.url)):
+                for (
+                    key,
+                    value,
+                ) in sentry_sdk.get_current_scope().iter_trace_propagation_headers():
+                    logger.debug(
+                        "[Tracing] Adding `{key}` header {value} to outgoing request to {url}.".format(
+                            key=key, value=value, url=request.url
+                        )
+                    )
+
+                    if key == BAGGAGE_HEADER_NAME:
+                        _add_sentry_baggage_to_headers(request.headers, value)
+                    else:
+                        request.headers[key] = value
+
+            rv = real_send(self, request, **kwargs)
+
+            span.set_http_status(rv.status_code)
+            span.set_data("reason", rv.reason_phrase)
+
+            return rv
+
+    Client.send = send
+
+
+def _install_httpx_async_client():
+    # type: () -> None
+    real_send = AsyncClient.send
+
+    async def send(self, request, **kwargs):
+        # type: (AsyncClient, Request, **Any) -> Response
+        if sentry_sdk.get_client().get_integration(HttpxIntegration) is None:
+            return await real_send(self, request, **kwargs)
+
+        parsed_url = None
+        with capture_internal_exceptions():
+            parsed_url = parse_url(str(request.url), sanitize=False)
+
+        with sentry_sdk.start_span(
+            op=OP.HTTP_CLIENT,
+            name="%s %s"
+            % (
+                request.method,
+                parsed_url.url if parsed_url else SENSITIVE_DATA_SUBSTITUTE,
+            ),
+            origin=HttpxIntegration.origin,
+        ) as span:
+            span.set_data(SPANDATA.HTTP_METHOD, request.method)
+            if parsed_url is not None:
+                span.set_data("url", parsed_url.url)
+                span.set_data(SPANDATA.HTTP_QUERY, parsed_url.query)
+                span.set_data(SPANDATA.HTTP_FRAGMENT, parsed_url.fragment)
+
+            if should_propagate_trace(sentry_sdk.get_client(), str(request.url)):
+                for (
+                    key,
+                    value,
+                ) in sentry_sdk.get_current_scope().iter_trace_propagation_headers():
+                    logger.debug(
+                        "[Tracing] Adding `{key}` header {value} to outgoing request to {url}.".format(
+                            key=key, value=value, url=request.url
+                        )
+                    )
+                    if key == BAGGAGE_HEADER_NAME and request.headers.get(
+                        BAGGAGE_HEADER_NAME
+                    ):
+                        # do not overwrite any existing baggage, just append to it
+                        request.headers[key] += "," + value
+                    else:
+                        request.headers[key] = value
+
+            rv = await real_send(self, request, **kwargs)
+
+            span.set_http_status(rv.status_code)
+            span.set_data("reason", rv.reason_phrase)
+
+            return rv
+
+    AsyncClient.send = send
+
+
+def _add_sentry_baggage_to_headers(headers, sentry_baggage):
+    # type: (MutableMapping[str, str], str) -> None
+    """Add the Sentry baggage to the headers.
+
+    This function directly mutates the provided headers. The provided sentry_baggage
+    is appended to the existing baggage. If the baggage already contains Sentry items,
+    they are stripped out first.
+    """
+    existing_baggage = headers.get(BAGGAGE_HEADER_NAME, "")
+    stripped_existing_baggage = Baggage.strip_sentry_baggage(existing_baggage)
+
+    separator = "," if len(stripped_existing_baggage) > 0 else ""
+
+    headers[BAGGAGE_HEADER_NAME] = (
+        stripped_existing_baggage + separator + sentry_baggage
+    )
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/huey.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/huey.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0aff4c0dd29ac43380e6b222b757351862e9319
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/huey.py
@@ -0,0 +1,174 @@
+import sys
+from datetime import datetime
+
+import sentry_sdk
+from sentry_sdk.api import continue_trace, get_baggage, get_traceparent
+from sentry_sdk.consts import OP, SPANSTATUS
+from sentry_sdk.integrations import DidNotEnable, Integration
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.tracing import (
+    BAGGAGE_HEADER_NAME,
+    SENTRY_TRACE_HEADER_NAME,
+    TransactionSource,
+)
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    event_from_exception,
+    SENSITIVE_DATA_SUBSTITUTE,
+    reraise,
+)
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Callable, Optional, Union, TypeVar
+
+    from sentry_sdk._types import EventProcessor, Event, Hint
+    from sentry_sdk.utils import ExcInfo
+
+    F = TypeVar("F", bound=Callable[..., Any])
+
+try:
+    from huey.api import Huey, Result, ResultGroup, Task, PeriodicTask
+    from huey.exceptions import CancelExecution, RetryTask, TaskLockedException
+except ImportError:
+    raise DidNotEnable("Huey is not installed")
+
+
+HUEY_CONTROL_FLOW_EXCEPTIONS = (CancelExecution, RetryTask, TaskLockedException)
+
+
+class HueyIntegration(Integration):
+    identifier = "huey"
+    origin = f"auto.queue.{identifier}"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        patch_enqueue()
+        patch_execute()
+
+
+def patch_enqueue():
+    # type: () -> None
+    old_enqueue = Huey.enqueue
+
+    @ensure_integration_enabled(HueyIntegration, old_enqueue)
+    def _sentry_enqueue(self, task):
+        # type: (Huey, Task) -> Optional[Union[Result, ResultGroup]]
+        with sentry_sdk.start_span(
+            op=OP.QUEUE_SUBMIT_HUEY,
+            name=task.name,
+            origin=HueyIntegration.origin,
+        ):
+            if not isinstance(task, PeriodicTask):
+                # Attach trace propagation data to task kwargs. We do
+                # not do this for periodic tasks, as these don't
+                # really have an originating transaction.
+                task.kwargs["sentry_headers"] = {
+                    BAGGAGE_HEADER_NAME: get_baggage(),
+                    SENTRY_TRACE_HEADER_NAME: get_traceparent(),
+                }
+            return old_enqueue(self, task)
+
+    Huey.enqueue = _sentry_enqueue
+
+
+def _make_event_processor(task):
+    # type: (Any) -> EventProcessor
+    def event_processor(event, hint):
+        # type: (Event, Hint) -> Optional[Event]
+
+        with capture_internal_exceptions():
+            tags = event.setdefault("tags", {})
+            tags["huey_task_id"] = task.id
+            tags["huey_task_retry"] = task.default_retries > task.retries
+            extra = event.setdefault("extra", {})
+            extra["huey-job"] = {
+                "task": task.name,
+                "args": (
+                    task.args
+                    if should_send_default_pii()
+                    else SENSITIVE_DATA_SUBSTITUTE
+                ),
+                "kwargs": (
+                    task.kwargs
+                    if should_send_default_pii()
+                    else SENSITIVE_DATA_SUBSTITUTE
+                ),
+                "retry": (task.default_retries or 0) - task.retries,
+            }
+
+        return event
+
+    return event_processor
+
+
+def _capture_exception(exc_info):
+    # type: (ExcInfo) -> None
+    scope = sentry_sdk.get_current_scope()
+
+    if exc_info[0] in HUEY_CONTROL_FLOW_EXCEPTIONS:
+        scope.transaction.set_status(SPANSTATUS.ABORTED)
+        return
+
+    scope.transaction.set_status(SPANSTATUS.INTERNAL_ERROR)
+    event, hint = event_from_exception(
+        exc_info,
+        client_options=sentry_sdk.get_client().options,
+        mechanism={"type": HueyIntegration.identifier, "handled": False},
+    )
+    scope.capture_event(event, hint=hint)
+
+
+def _wrap_task_execute(func):
+    # type: (F) -> F
+
+    @ensure_integration_enabled(HueyIntegration, func)
+    def _sentry_execute(*args, **kwargs):
+        # type: (*Any, **Any) -> Any
+        try:
+            result = func(*args, **kwargs)
+        except Exception:
+            exc_info = sys.exc_info()
+            _capture_exception(exc_info)
+            reraise(*exc_info)
+
+        return result
+
+    return _sentry_execute  # type: ignore
+
+
+def patch_execute():
+    # type: () -> None
+    old_execute = Huey._execute
+
+    @ensure_integration_enabled(HueyIntegration, old_execute)
+    def _sentry_execute(self, task, timestamp=None):
+        # type: (Huey, Task, Optional[datetime]) -> Any
+        with sentry_sdk.isolation_scope() as scope:
+            with capture_internal_exceptions():
+                scope._name = "huey"
+                scope.clear_breadcrumbs()
+                scope.add_event_processor(_make_event_processor(task))
+
+            sentry_headers = task.kwargs.pop("sentry_headers", None)
+
+            transaction = continue_trace(
+                sentry_headers or {},
+                name=task.name,
+                op=OP.QUEUE_TASK_HUEY,
+                source=TransactionSource.TASK,
+                origin=HueyIntegration.origin,
+            )
+            transaction.set_status(SPANSTATUS.OK)
+
+            if not getattr(task, "_sentry_is_patched", False):
+                task.execute = _wrap_task_execute(task.execute)
+                task._sentry_is_patched = True
+
+            with sentry_sdk.start_transaction(transaction):
+                return old_execute(self, task, timestamp)
+
+    Huey._execute = _sentry_execute
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/huggingface_hub.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/huggingface_hub.py
new file mode 100644
index 0000000000000000000000000000000000000000..2dfcb5925a1bb597fca3a30045916245b86b6348
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/huggingface_hub.py
@@ -0,0 +1,181 @@
+from functools import wraps
+
+from sentry_sdk import consts
+from sentry_sdk.ai.monitoring import record_token_usage
+from sentry_sdk.ai.utils import set_data_normalized
+from sentry_sdk.consts import SPANDATA
+
+from typing import Any, Iterable, Callable
+
+import sentry_sdk
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.integrations import DidNotEnable, Integration
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    event_from_exception,
+)
+
+try:
+    import huggingface_hub.inference._client
+
+    from huggingface_hub import ChatCompletionStreamOutput, TextGenerationOutput
+except ImportError:
+    raise DidNotEnable("Huggingface not installed")
+
+
+class HuggingfaceHubIntegration(Integration):
+    identifier = "huggingface_hub"
+    origin = f"auto.ai.{identifier}"
+
+    def __init__(self, include_prompts=True):
+        # type: (HuggingfaceHubIntegration, bool) -> None
+        self.include_prompts = include_prompts
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        huggingface_hub.inference._client.InferenceClient.text_generation = (
+            _wrap_text_generation(
+                huggingface_hub.inference._client.InferenceClient.text_generation
+            )
+        )
+
+
+def _capture_exception(exc):
+    # type: (Any) -> None
+    event, hint = event_from_exception(
+        exc,
+        client_options=sentry_sdk.get_client().options,
+        mechanism={"type": "huggingface_hub", "handled": False},
+    )
+    sentry_sdk.capture_event(event, hint=hint)
+
+
+def _wrap_text_generation(f):
+    # type: (Callable[..., Any]) -> Callable[..., Any]
+    @wraps(f)
+    def new_text_generation(*args, **kwargs):
+        # type: (*Any, **Any) -> Any
+        integration = sentry_sdk.get_client().get_integration(HuggingfaceHubIntegration)
+        if integration is None:
+            return f(*args, **kwargs)
+
+        if "prompt" in kwargs:
+            prompt = kwargs["prompt"]
+        elif len(args) >= 2:
+            kwargs["prompt"] = args[1]
+            prompt = kwargs["prompt"]
+            args = (args[0],) + args[2:]
+        else:
+            # invalid call, let it return error
+            return f(*args, **kwargs)
+
+        model = kwargs.get("model")
+        streaming = kwargs.get("stream")
+
+        span = sentry_sdk.start_span(
+            op=consts.OP.HUGGINGFACE_HUB_CHAT_COMPLETIONS_CREATE,
+            name="Text Generation",
+            origin=HuggingfaceHubIntegration.origin,
+        )
+        span.__enter__()
+        try:
+            res = f(*args, **kwargs)
+        except Exception as e:
+            _capture_exception(e)
+            span.__exit__(None, None, None)
+            raise e from None
+
+        with capture_internal_exceptions():
+            if should_send_default_pii() and integration.include_prompts:
+                set_data_normalized(span, SPANDATA.AI_INPUT_MESSAGES, prompt)
+
+            set_data_normalized(span, SPANDATA.AI_MODEL_ID, model)
+            set_data_normalized(span, SPANDATA.AI_STREAMING, streaming)
+
+            if isinstance(res, str):
+                if should_send_default_pii() and integration.include_prompts:
+                    set_data_normalized(
+                        span,
+                        SPANDATA.AI_RESPONSES,
+                        [res],
+                    )
+                span.__exit__(None, None, None)
+                return res
+
+            if isinstance(res, TextGenerationOutput):
+                if should_send_default_pii() and integration.include_prompts:
+                    set_data_normalized(
+                        span,
+                        SPANDATA.AI_RESPONSES,
+                        [res.generated_text],
+                    )
+                if res.details is not None and res.details.generated_tokens > 0:
+                    record_token_usage(
+                        span,
+                        total_tokens=res.details.generated_tokens,
+                    )
+                span.__exit__(None, None, None)
+                return res
+
+            if not isinstance(res, Iterable):
+                # we only know how to deal with strings and iterables, ignore
+                set_data_normalized(span, "unknown_response", True)
+                span.__exit__(None, None, None)
+                return res
+
+            if kwargs.get("details", False):
+                # res is Iterable[TextGenerationStreamOutput]
+                def new_details_iterator():
+                    # type: () -> Iterable[ChatCompletionStreamOutput]
+                    with capture_internal_exceptions():
+                        tokens_used = 0
+                        data_buf: list[str] = []
+                        for x in res:
+                            if hasattr(x, "token") and hasattr(x.token, "text"):
+                                data_buf.append(x.token.text)
+                            if hasattr(x, "details") and hasattr(
+                                x.details, "generated_tokens"
+                            ):
+                                tokens_used = x.details.generated_tokens
+                            yield x
+                        if (
+                            len(data_buf) > 0
+                            and should_send_default_pii()
+                            and integration.include_prompts
+                        ):
+                            set_data_normalized(
+                                span, SPANDATA.AI_RESPONSES, "".join(data_buf)
+                            )
+                        if tokens_used > 0:
+                            record_token_usage(
+                                span,
+                                total_tokens=tokens_used,
+                            )
+                    span.__exit__(None, None, None)
+
+                return new_details_iterator()
+            else:
+                # res is Iterable[str]
+
+                def new_iterator():
+                    # type: () -> Iterable[str]
+                    data_buf: list[str] = []
+                    with capture_internal_exceptions():
+                        for s in res:
+                            if isinstance(s, str):
+                                data_buf.append(s)
+                            yield s
+                        if (
+                            len(data_buf) > 0
+                            and should_send_default_pii()
+                            and integration.include_prompts
+                        ):
+                            set_data_normalized(
+                                span, SPANDATA.AI_RESPONSES, "".join(data_buf)
+                            )
+                        span.__exit__(None, None, None)
+
+                return new_iterator()
+
+    return new_text_generation
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/langchain.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/langchain.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e04a740edbb084d5ec4f28b114f2e463e97666f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/langchain.py
@@ -0,0 +1,770 @@
+import itertools
+from collections import OrderedDict
+from functools import wraps
+
+import sentry_sdk
+from sentry_sdk.ai.monitoring import set_ai_pipeline_name
+from sentry_sdk.ai.utils import set_data_normalized
+from sentry_sdk.consts import OP, SPANDATA
+from sentry_sdk.integrations import DidNotEnable, Integration
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.tracing import Span
+from sentry_sdk.tracing_utils import _get_value
+from sentry_sdk.utils import logger, capture_internal_exceptions
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import (
+        Any,
+        AsyncIterator,
+        Callable,
+        Dict,
+        Iterator,
+        List,
+        Optional,
+        Union,
+    )
+    from uuid import UUID
+
+
+try:
+    from langchain.agents import AgentExecutor
+    from langchain_core.agents import AgentFinish
+    from langchain_core.callbacks import (
+        BaseCallbackHandler,
+        BaseCallbackManager,
+        Callbacks,
+        manager,
+    )
+    from langchain_core.messages import BaseMessage
+    from langchain_core.outputs import LLMResult
+
+except ImportError:
+    raise DidNotEnable("langchain not installed")
+
+
+DATA_FIELDS = {
+    "frequency_penalty": SPANDATA.GEN_AI_REQUEST_FREQUENCY_PENALTY,
+    "function_call": SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS,
+    "max_tokens": SPANDATA.GEN_AI_REQUEST_MAX_TOKENS,
+    "presence_penalty": SPANDATA.GEN_AI_REQUEST_PRESENCE_PENALTY,
+    "temperature": SPANDATA.GEN_AI_REQUEST_TEMPERATURE,
+    "tool_calls": SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS,
+    "tools": SPANDATA.GEN_AI_REQUEST_AVAILABLE_TOOLS,
+    "top_k": SPANDATA.GEN_AI_REQUEST_TOP_K,
+    "top_p": SPANDATA.GEN_AI_REQUEST_TOP_P,
+}
+
+
+class LangchainIntegration(Integration):
+    identifier = "langchain"
+    origin = f"auto.ai.{identifier}"
+
+    # The most number of spans (e.g., LLM calls) that can be processed at the same time.
+    max_spans = 1024
+
+    def __init__(self, include_prompts=True, max_spans=1024):
+        # type: (LangchainIntegration, bool, int) -> None
+        self.include_prompts = include_prompts
+        self.max_spans = max_spans
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        manager._configure = _wrap_configure(manager._configure)
+
+        if AgentExecutor is not None:
+            AgentExecutor.invoke = _wrap_agent_executor_invoke(AgentExecutor.invoke)
+            AgentExecutor.stream = _wrap_agent_executor_stream(AgentExecutor.stream)
+
+
+class WatchedSpan:
+    span = None  # type: Span
+    children = []  # type: List[WatchedSpan]
+    is_pipeline = False  # type: bool
+
+    def __init__(self, span):
+        # type: (Span) -> None
+        self.span = span
+
+
+class SentryLangchainCallback(BaseCallbackHandler):  # type: ignore[misc]
+    """Callback handler that creates Sentry spans."""
+
+    def __init__(self, max_span_map_size, include_prompts):
+        # type: (int, bool) -> None
+        self.span_map = OrderedDict()  # type: OrderedDict[UUID, WatchedSpan]
+        self.max_span_map_size = max_span_map_size
+        self.include_prompts = include_prompts
+
+    def gc_span_map(self):
+        # type: () -> None
+
+        while len(self.span_map) > self.max_span_map_size:
+            run_id, watched_span = self.span_map.popitem(last=False)
+            self._exit_span(watched_span, run_id)
+
+    def _handle_error(self, run_id, error):
+        # type: (UUID, Any) -> None
+        with capture_internal_exceptions():
+            if not run_id or run_id not in self.span_map:
+                return
+
+            span_data = self.span_map[run_id]
+            span = span_data.span
+            span.set_status("unknown")
+
+            sentry_sdk.capture_exception(error, span.scope)
+
+            span.__exit__(None, None, None)
+            del self.span_map[run_id]
+
+    def _normalize_langchain_message(self, message):
+        # type: (BaseMessage) -> Any
+        parsed = {"role": message.type, "content": message.content}
+        parsed.update(message.additional_kwargs)
+        return parsed
+
+    def _create_span(self, run_id, parent_id, **kwargs):
+        # type: (SentryLangchainCallback, UUID, Optional[Any], Any) -> WatchedSpan
+        watched_span = None  # type: Optional[WatchedSpan]
+        if parent_id:
+            parent_span = self.span_map.get(parent_id)  # type: Optional[WatchedSpan]
+            if parent_span:
+                watched_span = WatchedSpan(parent_span.span.start_child(**kwargs))
+                parent_span.children.append(watched_span)
+
+        if watched_span is None:
+            watched_span = WatchedSpan(sentry_sdk.start_span(**kwargs))
+
+        watched_span.span.__enter__()
+        self.span_map[run_id] = watched_span
+        self.gc_span_map()
+        return watched_span
+
+    def _exit_span(self, span_data, run_id):
+        # type: (SentryLangchainCallback, WatchedSpan, UUID) -> None
+        if span_data.is_pipeline:
+            set_ai_pipeline_name(None)
+
+        span_data.span.__exit__(None, None, None)
+        del self.span_map[run_id]
+
+    def on_llm_start(
+        self,
+        serialized,
+        prompts,
+        *,
+        run_id,
+        tags=None,
+        parent_run_id=None,
+        metadata=None,
+        **kwargs,
+    ):
+        # type: (SentryLangchainCallback, Dict[str, Any], List[str], UUID, Optional[List[str]], Optional[UUID], Optional[Dict[str, Any]], Any) -> Any
+        """Run when LLM starts running."""
+        with capture_internal_exceptions():
+            if not run_id:
+                return
+
+            all_params = kwargs.get("invocation_params", {})
+            all_params.update(serialized.get("kwargs", {}))
+
+            model = (
+                all_params.get("model")
+                or all_params.get("model_name")
+                or all_params.get("model_id")
+                or ""
+            )
+
+            watched_span = self._create_span(
+                run_id,
+                parent_run_id,
+                op=OP.GEN_AI_PIPELINE,
+                name=kwargs.get("name") or "Langchain LLM call",
+                origin=LangchainIntegration.origin,
+            )
+            span = watched_span.span
+
+            if model:
+                span.set_data(
+                    SPANDATA.GEN_AI_REQUEST_MODEL,
+                    model,
+                )
+
+            ai_type = all_params.get("_type", "")
+            if "anthropic" in ai_type:
+                span.set_data(SPANDATA.GEN_AI_SYSTEM, "anthropic")
+            elif "openai" in ai_type:
+                span.set_data(SPANDATA.GEN_AI_SYSTEM, "openai")
+
+            for key, attribute in DATA_FIELDS.items():
+                if key in all_params and all_params[key] is not None:
+                    set_data_normalized(span, attribute, all_params[key], unpack=False)
+
+            if should_send_default_pii() and self.include_prompts:
+                set_data_normalized(span, SPANDATA.GEN_AI_REQUEST_MESSAGES, prompts)
+
+    def on_chat_model_start(self, serialized, messages, *, run_id, **kwargs):
+        # type: (SentryLangchainCallback, Dict[str, Any], List[List[BaseMessage]], UUID, Any) -> Any
+        """Run when Chat Model starts running."""
+        with capture_internal_exceptions():
+            if not run_id:
+                return
+
+            all_params = kwargs.get("invocation_params", {})
+            all_params.update(serialized.get("kwargs", {}))
+
+            model = (
+                all_params.get("model")
+                or all_params.get("model_name")
+                or all_params.get("model_id")
+                or ""
+            )
+
+            watched_span = self._create_span(
+                run_id,
+                kwargs.get("parent_run_id"),
+                op=OP.GEN_AI_CHAT,
+                name=f"chat {model}".strip(),
+                origin=LangchainIntegration.origin,
+            )
+            span = watched_span.span
+
+            span.set_data(SPANDATA.GEN_AI_OPERATION_NAME, "chat")
+            if model:
+                span.set_data(SPANDATA.GEN_AI_REQUEST_MODEL, model)
+
+            ai_type = all_params.get("_type", "")
+            if "anthropic" in ai_type:
+                span.set_data(SPANDATA.GEN_AI_SYSTEM, "anthropic")
+            elif "openai" in ai_type:
+                span.set_data(SPANDATA.GEN_AI_SYSTEM, "openai")
+
+            for key, attribute in DATA_FIELDS.items():
+                if key in all_params and all_params[key] is not None:
+                    set_data_normalized(span, attribute, all_params[key], unpack=False)
+
+            if should_send_default_pii() and self.include_prompts:
+                set_data_normalized(
+                    span,
+                    SPANDATA.GEN_AI_REQUEST_MESSAGES,
+                    [
+                        [self._normalize_langchain_message(x) for x in list_]
+                        for list_ in messages
+                    ],
+                )
+
+    def on_chat_model_end(self, response, *, run_id, **kwargs):
+        # type: (SentryLangchainCallback, LLMResult, UUID, Any) -> Any
+        """Run when Chat Model ends running."""
+        with capture_internal_exceptions():
+            if not run_id or run_id not in self.span_map:
+                return
+
+            span_data = self.span_map[run_id]
+            span = span_data.span
+
+            if should_send_default_pii() and self.include_prompts:
+                set_data_normalized(
+                    span,
+                    SPANDATA.GEN_AI_RESPONSE_TEXT,
+                    [[x.text for x in list_] for list_ in response.generations],
+                )
+
+            _record_token_usage(span, response)
+            self._exit_span(span_data, run_id)
+
+    def on_llm_end(self, response, *, run_id, **kwargs):
+        # type: (SentryLangchainCallback, LLMResult, UUID, Any) -> Any
+        """Run when LLM ends running."""
+        with capture_internal_exceptions():
+            if not run_id or run_id not in self.span_map:
+                return
+
+            span_data = self.span_map[run_id]
+            span = span_data.span
+
+            try:
+                generation = response.generations[0][0]
+            except IndexError:
+                generation = None
+
+            if generation is not None:
+                try:
+                    response_model = generation.generation_info.get("model_name")
+                    if response_model is not None:
+                        span.set_data(SPANDATA.GEN_AI_RESPONSE_MODEL, response_model)
+                except AttributeError:
+                    pass
+
+                try:
+                    finish_reason = generation.generation_info.get("finish_reason")
+                    if finish_reason is not None:
+                        span.set_data(
+                            SPANDATA.GEN_AI_RESPONSE_FINISH_REASONS, finish_reason
+                        )
+                except AttributeError:
+                    pass
+
+                try:
+                    tool_calls = getattr(generation.message, "tool_calls", None)
+                    if tool_calls is not None and tool_calls != []:
+                        set_data_normalized(
+                            span,
+                            SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS,
+                            tool_calls,
+                            unpack=False,
+                        )
+                except AttributeError:
+                    pass
+
+            if should_send_default_pii() and self.include_prompts:
+                set_data_normalized(
+                    span,
+                    SPANDATA.GEN_AI_RESPONSE_TEXT,
+                    [[x.text for x in list_] for list_ in response.generations],
+                )
+
+            _record_token_usage(span, response)
+            self._exit_span(span_data, run_id)
+
+    def on_llm_error(self, error, *, run_id, **kwargs):
+        # type: (SentryLangchainCallback, Union[Exception, KeyboardInterrupt], UUID, Any) -> Any
+        """Run when LLM errors."""
+        self._handle_error(run_id, error)
+
+    def on_chat_model_error(self, error, *, run_id, **kwargs):
+        # type: (SentryLangchainCallback, Union[Exception, KeyboardInterrupt], UUID, Any) -> Any
+        """Run when Chat Model errors."""
+        self._handle_error(run_id, error)
+
+    def on_agent_finish(self, finish, *, run_id, **kwargs):
+        # type: (SentryLangchainCallback, AgentFinish, UUID, Any) -> Any
+        with capture_internal_exceptions():
+            if not run_id or run_id not in self.span_map:
+                return
+
+            span_data = self.span_map[run_id]
+            span = span_data.span
+
+            if should_send_default_pii() and self.include_prompts:
+                set_data_normalized(
+                    span,
+                    SPANDATA.GEN_AI_RESPONSE_TEXT,
+                    finish.return_values.items(),
+                )
+
+            self._exit_span(span_data, run_id)
+
+    def on_tool_start(self, serialized, input_str, *, run_id, **kwargs):
+        # type: (SentryLangchainCallback, Dict[str, Any], str, UUID, Any) -> Any
+        """Run when tool starts running."""
+        with capture_internal_exceptions():
+            if not run_id:
+                return
+
+            tool_name = serialized.get("name") or kwargs.get("name") or ""
+
+            watched_span = self._create_span(
+                run_id,
+                kwargs.get("parent_run_id"),
+                op=OP.GEN_AI_EXECUTE_TOOL,
+                name=f"execute_tool {tool_name}".strip(),
+                origin=LangchainIntegration.origin,
+            )
+            span = watched_span.span
+
+            span.set_data(SPANDATA.GEN_AI_OPERATION_NAME, "execute_tool")
+            span.set_data(SPANDATA.GEN_AI_TOOL_NAME, tool_name)
+
+            tool_description = serialized.get("description")
+            if tool_description is not None:
+                span.set_data(SPANDATA.GEN_AI_TOOL_DESCRIPTION, tool_description)
+
+            if should_send_default_pii() and self.include_prompts:
+                set_data_normalized(
+                    span,
+                    SPANDATA.GEN_AI_TOOL_INPUT,
+                    kwargs.get("inputs", [input_str]),
+                )
+
+    def on_tool_end(self, output, *, run_id, **kwargs):
+        # type: (SentryLangchainCallback, str, UUID, Any) -> Any
+        """Run when tool ends running."""
+        with capture_internal_exceptions():
+            if not run_id or run_id not in self.span_map:
+                return
+
+            span_data = self.span_map[run_id]
+            span = span_data.span
+
+            if should_send_default_pii() and self.include_prompts:
+                set_data_normalized(span, SPANDATA.GEN_AI_TOOL_OUTPUT, output)
+
+            self._exit_span(span_data, run_id)
+
+    def on_tool_error(self, error, *args, run_id, **kwargs):
+        # type: (SentryLangchainCallback, Union[Exception, KeyboardInterrupt], UUID, Any) -> Any
+        """Run when tool errors."""
+        self._handle_error(run_id, error)
+
+
+def _extract_tokens(token_usage):
+    # type: (Any) -> tuple[Optional[int], Optional[int], Optional[int]]
+    if not token_usage:
+        return None, None, None
+
+    input_tokens = _get_value(token_usage, "prompt_tokens") or _get_value(
+        token_usage, "input_tokens"
+    )
+    output_tokens = _get_value(token_usage, "completion_tokens") or _get_value(
+        token_usage, "output_tokens"
+    )
+    total_tokens = _get_value(token_usage, "total_tokens")
+
+    return input_tokens, output_tokens, total_tokens
+
+
+def _extract_tokens_from_generations(generations):
+    # type: (Any) -> tuple[Optional[int], Optional[int], Optional[int]]
+    """Extract token usage from response.generations structure."""
+    if not generations:
+        return None, None, None
+
+    total_input = 0
+    total_output = 0
+    total_total = 0
+
+    for gen_list in generations:
+        for gen in gen_list:
+            token_usage = _get_token_usage(gen)
+            input_tokens, output_tokens, total_tokens = _extract_tokens(token_usage)
+            total_input += input_tokens if input_tokens is not None else 0
+            total_output += output_tokens if output_tokens is not None else 0
+            total_total += total_tokens if total_tokens is not None else 0
+
+    return (
+        total_input if total_input > 0 else None,
+        total_output if total_output > 0 else None,
+        total_total if total_total > 0 else None,
+    )
+
+
+def _get_token_usage(obj):
+    # type: (Any) -> Optional[Dict[str, Any]]
+    """
+    Check multiple paths to extract token usage from different objects.
+    """
+    possible_names = ("usage", "token_usage", "usage_metadata")
+
+    message = _get_value(obj, "message")
+    if message is not None:
+        for name in possible_names:
+            usage = _get_value(message, name)
+            if usage is not None:
+                return usage
+
+    llm_output = _get_value(obj, "llm_output")
+    if llm_output is not None:
+        for name in possible_names:
+            usage = _get_value(llm_output, name)
+            if usage is not None:
+                return usage
+
+    # check for usage in the object itself
+    for name in possible_names:
+        usage = _get_value(obj, name)
+        if usage is not None:
+            return usage
+
+    # no usage found anywhere
+    return None
+
+
+def _record_token_usage(span, response):
+    # type: (Span, Any) -> None
+    token_usage = _get_token_usage(response)
+    if token_usage:
+        input_tokens, output_tokens, total_tokens = _extract_tokens(token_usage)
+    else:
+        input_tokens, output_tokens, total_tokens = _extract_tokens_from_generations(
+            response.generations
+        )
+
+    if input_tokens is not None:
+        span.set_data(SPANDATA.GEN_AI_USAGE_INPUT_TOKENS, input_tokens)
+
+    if output_tokens is not None:
+        span.set_data(SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS, output_tokens)
+
+    if total_tokens is not None:
+        span.set_data(SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS, total_tokens)
+
+
+def _get_request_data(obj, args, kwargs):
+    # type: (Any, Any, Any) -> tuple[Optional[str], Optional[List[Any]]]
+    """
+    Get the agent name and available tools for the agent.
+    """
+    agent = getattr(obj, "agent", None)
+    runnable = getattr(agent, "runnable", None)
+    runnable_config = getattr(runnable, "config", {})
+    tools = (
+        getattr(obj, "tools", None)
+        or getattr(agent, "tools", None)
+        or runnable_config.get("tools")
+        or runnable_config.get("available_tools")
+    )
+    tools = tools if tools and len(tools) > 0 else None
+
+    try:
+        agent_name = None
+        if len(args) > 1:
+            agent_name = args[1].get("run_name")
+        if agent_name is None:
+            agent_name = runnable_config.get("run_name")
+    except Exception:
+        pass
+
+    return (agent_name, tools)
+
+
+def _wrap_configure(f):
+    # type: (Callable[..., Any]) -> Callable[..., Any]
+
+    @wraps(f)
+    def new_configure(
+        callback_manager_cls,  # type: type
+        inheritable_callbacks=None,  # type: Callbacks
+        local_callbacks=None,  # type: Callbacks
+        *args,  # type: Any
+        **kwargs,  # type: Any
+    ):
+        # type: (...) -> Any
+
+        integration = sentry_sdk.get_client().get_integration(LangchainIntegration)
+        if integration is None:
+            return f(
+                callback_manager_cls,
+                inheritable_callbacks,
+                local_callbacks,
+                *args,
+                **kwargs,
+            )
+
+        local_callbacks = local_callbacks or []
+
+        # Handle each possible type of local_callbacks. For each type, we
+        # extract the list of callbacks to check for SentryLangchainCallback,
+        # and define a function that would add the SentryLangchainCallback
+        # to the existing callbacks list.
+        if isinstance(local_callbacks, BaseCallbackManager):
+            callbacks_list = local_callbacks.handlers
+        elif isinstance(local_callbacks, BaseCallbackHandler):
+            callbacks_list = [local_callbacks]
+        elif isinstance(local_callbacks, list):
+            callbacks_list = local_callbacks
+        else:
+            logger.debug("Unknown callback type: %s", local_callbacks)
+            # Just proceed with original function call
+            return f(
+                callback_manager_cls,
+                inheritable_callbacks,
+                local_callbacks,
+                *args,
+                **kwargs,
+            )
+
+        # Handle each possible type of inheritable_callbacks.
+        if isinstance(inheritable_callbacks, BaseCallbackManager):
+            inheritable_callbacks_list = inheritable_callbacks.handlers
+        elif isinstance(inheritable_callbacks, list):
+            inheritable_callbacks_list = inheritable_callbacks
+        else:
+            inheritable_callbacks_list = []
+
+        if not any(
+            isinstance(cb, SentryLangchainCallback)
+            for cb in itertools.chain(callbacks_list, inheritable_callbacks_list)
+        ):
+            sentry_handler = SentryLangchainCallback(
+                integration.max_spans,
+                integration.include_prompts,
+            )
+            if isinstance(local_callbacks, BaseCallbackManager):
+                local_callbacks = local_callbacks.copy()
+                local_callbacks.handlers = [
+                    *local_callbacks.handlers,
+                    sentry_handler,
+                ]
+            elif isinstance(local_callbacks, BaseCallbackHandler):
+                local_callbacks = [local_callbacks, sentry_handler]
+            else:  # local_callbacks is a list
+                local_callbacks = [*local_callbacks, sentry_handler]
+
+        return f(
+            callback_manager_cls,
+            inheritable_callbacks,
+            local_callbacks,
+            *args,
+            **kwargs,
+        )
+
+    return new_configure
+
+
+def _wrap_agent_executor_invoke(f):
+    # type: (Callable[..., Any]) -> Callable[..., Any]
+
+    @wraps(f)
+    def new_invoke(self, *args, **kwargs):
+        # type: (Any, Any, Any) -> Any
+        integration = sentry_sdk.get_client().get_integration(LangchainIntegration)
+        if integration is None:
+            return f(self, *args, **kwargs)
+
+        agent_name, tools = _get_request_data(self, args, kwargs)
+
+        with sentry_sdk.start_span(
+            op=OP.GEN_AI_INVOKE_AGENT,
+            name=f"invoke_agent {agent_name}" if agent_name else "invoke_agent",
+            origin=LangchainIntegration.origin,
+        ) as span:
+            if agent_name:
+                span.set_data(SPANDATA.GEN_AI_AGENT_NAME, agent_name)
+
+            span.set_data(SPANDATA.GEN_AI_OPERATION_NAME, "invoke_agent")
+            span.set_data(SPANDATA.GEN_AI_RESPONSE_STREAMING, False)
+
+            if tools:
+                set_data_normalized(
+                    span, SPANDATA.GEN_AI_REQUEST_AVAILABLE_TOOLS, tools, unpack=False
+                )
+
+            # Run the agent
+            result = f(self, *args, **kwargs)
+
+            input = result.get("input")
+            if (
+                input is not None
+                and should_send_default_pii()
+                and integration.include_prompts
+            ):
+                set_data_normalized(
+                    span,
+                    SPANDATA.GEN_AI_REQUEST_MESSAGES,
+                    [
+                        input,
+                    ],
+                )
+
+            output = result.get("output")
+            if (
+                output is not None
+                and should_send_default_pii()
+                and integration.include_prompts
+            ):
+                span.set_data(SPANDATA.GEN_AI_RESPONSE_TEXT, output)
+
+            return result
+
+    return new_invoke
+
+
+def _wrap_agent_executor_stream(f):
+    # type: (Callable[..., Any]) -> Callable[..., Any]
+
+    @wraps(f)
+    def new_stream(self, *args, **kwargs):
+        # type: (Any, Any, Any) -> Any
+        integration = sentry_sdk.get_client().get_integration(LangchainIntegration)
+        if integration is None:
+            return f(self, *args, **kwargs)
+
+        agent_name, tools = _get_request_data(self, args, kwargs)
+
+        span = sentry_sdk.start_span(
+            op=OP.GEN_AI_INVOKE_AGENT,
+            name=f"invoke_agent {agent_name}".strip(),
+            origin=LangchainIntegration.origin,
+        )
+        span.__enter__()
+
+        if agent_name:
+            span.set_data(SPANDATA.GEN_AI_AGENT_NAME, agent_name)
+
+        span.set_data(SPANDATA.GEN_AI_OPERATION_NAME, "invoke_agent")
+        span.set_data(SPANDATA.GEN_AI_RESPONSE_STREAMING, True)
+
+        if tools:
+            set_data_normalized(
+                span, SPANDATA.GEN_AI_REQUEST_AVAILABLE_TOOLS, tools, unpack=False
+            )
+
+        input = args[0].get("input") if len(args) >= 1 else None
+        if (
+            input is not None
+            and should_send_default_pii()
+            and integration.include_prompts
+        ):
+            set_data_normalized(
+                span,
+                SPANDATA.GEN_AI_REQUEST_MESSAGES,
+                [
+                    input,
+                ],
+            )
+
+        # Run the agent
+        result = f(self, *args, **kwargs)
+
+        old_iterator = result
+
+        def new_iterator():
+            # type: () -> Iterator[Any]
+            for event in old_iterator:
+                yield event
+
+            try:
+                output = event.get("output")
+            except Exception:
+                output = None
+
+            if (
+                output is not None
+                and should_send_default_pii()
+                and integration.include_prompts
+            ):
+                span.set_data(SPANDATA.GEN_AI_RESPONSE_TEXT, output)
+
+            span.__exit__(None, None, None)
+
+        async def new_iterator_async():
+            # type: () -> AsyncIterator[Any]
+            async for event in old_iterator:
+                yield event
+
+            try:
+                output = event.get("output")
+            except Exception:
+                output = None
+
+            if (
+                output is not None
+                and should_send_default_pii()
+                and integration.include_prompts
+            ):
+                span.set_data(SPANDATA.GEN_AI_RESPONSE_TEXT, output)
+
+            span.__exit__(None, None, None)
+
+        if str(type(result)) == "":
+            result = new_iterator_async()
+        else:
+            result = new_iterator()
+
+        return result
+
+    return new_stream
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/launchdarkly.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/launchdarkly.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3c423e7be7878077823b2af930c1b00d805c558
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/launchdarkly.py
@@ -0,0 +1,62 @@
+from typing import TYPE_CHECKING
+
+from sentry_sdk.feature_flags import add_feature_flag
+from sentry_sdk.integrations import DidNotEnable, Integration
+
+try:
+    import ldclient
+    from ldclient.hook import Hook, Metadata
+
+    if TYPE_CHECKING:
+        from ldclient import LDClient
+        from ldclient.hook import EvaluationSeriesContext
+        from ldclient.evaluation import EvaluationDetail
+
+        from typing import Any
+except ImportError:
+    raise DidNotEnable("LaunchDarkly is not installed")
+
+
+class LaunchDarklyIntegration(Integration):
+    identifier = "launchdarkly"
+
+    def __init__(self, ld_client=None):
+        # type: (LDClient | None) -> None
+        """
+        :param client: An initialized LDClient instance. If a client is not provided, this
+            integration will attempt to use the shared global instance.
+        """
+        try:
+            client = ld_client or ldclient.get()
+        except Exception as exc:
+            raise DidNotEnable("Error getting LaunchDarkly client. " + repr(exc))
+
+        if not client.is_initialized():
+            raise DidNotEnable("LaunchDarkly client is not initialized.")
+
+        # Register the flag collection hook with the LD client.
+        client.add_hook(LaunchDarklyHook())
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        pass
+
+
+class LaunchDarklyHook(Hook):
+
+    @property
+    def metadata(self):
+        # type: () -> Metadata
+        return Metadata(name="sentry-flag-auditor")
+
+    def after_evaluation(self, series_context, data, detail):
+        # type: (EvaluationSeriesContext, dict[Any, Any], EvaluationDetail) -> dict[Any, Any]
+        if isinstance(detail.value, bool):
+            add_feature_flag(series_context.key, detail.value)
+
+        return data
+
+    def before_evaluation(self, series_context, data):
+        # type: (EvaluationSeriesContext, dict[Any, Any]) -> dict[Any, Any]
+        return data  # No-op.
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/litestar.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/litestar.py
new file mode 100644
index 0000000000000000000000000000000000000000..2be4d376e0db715ea24b6288cffae230eec4a863
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/litestar.py
@@ -0,0 +1,315 @@
+from collections.abc import Set
+import sentry_sdk
+from sentry_sdk.consts import OP
+from sentry_sdk.integrations import (
+    _DEFAULT_FAILED_REQUEST_STATUS_CODES,
+    DidNotEnable,
+    Integration,
+)
+from sentry_sdk.integrations.asgi import SentryAsgiMiddleware
+from sentry_sdk.integrations.logging import ignore_logger
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.tracing import TransactionSource, SOURCE_FOR_STYLE
+from sentry_sdk.utils import (
+    ensure_integration_enabled,
+    event_from_exception,
+    transaction_from_function,
+)
+
+try:
+    from litestar import Request, Litestar  # type: ignore
+    from litestar.handlers.base import BaseRouteHandler  # type: ignore
+    from litestar.middleware import DefineMiddleware  # type: ignore
+    from litestar.routes.http import HTTPRoute  # type: ignore
+    from litestar.data_extractors import ConnectionDataExtractor  # type: ignore
+    from litestar.exceptions import HTTPException  # type: ignore
+except ImportError:
+    raise DidNotEnable("Litestar is not installed")
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Optional, Union
+    from litestar.types.asgi_types import ASGIApp  # type: ignore
+    from litestar.types import (  # type: ignore
+        HTTPReceiveMessage,
+        HTTPScope,
+        Message,
+        Middleware,
+        Receive,
+        Scope as LitestarScope,
+        Send,
+        WebSocketReceiveMessage,
+    )
+    from litestar.middleware import MiddlewareProtocol
+    from sentry_sdk._types import Event, Hint
+
+_DEFAULT_TRANSACTION_NAME = "generic Litestar request"
+
+
+class LitestarIntegration(Integration):
+    identifier = "litestar"
+    origin = f"auto.http.{identifier}"
+
+    def __init__(
+        self,
+        failed_request_status_codes=_DEFAULT_FAILED_REQUEST_STATUS_CODES,  # type: Set[int]
+    ) -> None:
+        self.failed_request_status_codes = failed_request_status_codes
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        patch_app_init()
+        patch_middlewares()
+        patch_http_route_handle()
+
+        # The following line follows the pattern found in other integrations such as `DjangoIntegration.setup_once`.
+        # The Litestar `ExceptionHandlerMiddleware.__call__` catches exceptions and does the following
+        # (among other things):
+        #   1. Logs them, some at least (such as 500s) as errors
+        #   2. Calls after_exception hooks
+        # The `LitestarIntegration`` provides an after_exception hook (see `patch_app_init` below) to create a Sentry event
+        # from an exception, which ends up being called during step 2 above. However, the Sentry `LoggingIntegration` will
+        # by default create a Sentry event from error logs made in step 1 if we do not prevent it from doing so.
+        ignore_logger("litestar")
+
+
+class SentryLitestarASGIMiddleware(SentryAsgiMiddleware):
+    def __init__(self, app, span_origin=LitestarIntegration.origin):
+        # type: (ASGIApp, str) -> None
+
+        super().__init__(
+            app=app,
+            unsafe_context_data=False,
+            transaction_style="endpoint",
+            mechanism_type="asgi",
+            span_origin=span_origin,
+            asgi_version=3,
+        )
+
+    def _capture_request_exception(self, exc):
+        # type: (Exception) -> None
+        """Avoid catching exceptions from request handlers.
+
+        Those exceptions are already handled in Litestar.after_exception handler.
+        We still catch exceptions from application lifespan handlers.
+        """
+        pass
+
+
+def patch_app_init():
+    # type: () -> None
+    """
+    Replaces the Litestar class's `__init__` function in order to inject `after_exception` handlers and set the
+    `SentryLitestarASGIMiddleware` as the outmost middleware in the stack.
+    See:
+    - https://docs.litestar.dev/2/usage/applications.html#after-exception
+    - https://docs.litestar.dev/2/usage/middleware/using-middleware.html
+    """
+    old__init__ = Litestar.__init__
+
+    @ensure_integration_enabled(LitestarIntegration, old__init__)
+    def injection_wrapper(self, *args, **kwargs):
+        # type: (Litestar, *Any, **Any) -> None
+        kwargs["after_exception"] = [
+            exception_handler,
+            *(kwargs.get("after_exception") or []),
+        ]
+
+        middleware = kwargs.get("middleware") or []
+        kwargs["middleware"] = [SentryLitestarASGIMiddleware, *middleware]
+        old__init__(self, *args, **kwargs)
+
+    Litestar.__init__ = injection_wrapper
+
+
+def patch_middlewares():
+    # type: () -> None
+    old_resolve_middleware_stack = BaseRouteHandler.resolve_middleware
+
+    @ensure_integration_enabled(LitestarIntegration, old_resolve_middleware_stack)
+    def resolve_middleware_wrapper(self):
+        # type: (BaseRouteHandler) -> list[Middleware]
+        return [
+            enable_span_for_middleware(middleware)
+            for middleware in old_resolve_middleware_stack(self)
+        ]
+
+    BaseRouteHandler.resolve_middleware = resolve_middleware_wrapper
+
+
+def enable_span_for_middleware(middleware):
+    # type: (Middleware) -> Middleware
+    if (
+        not hasattr(middleware, "__call__")  # noqa: B004
+        or middleware is SentryLitestarASGIMiddleware
+    ):
+        return middleware
+
+    if isinstance(middleware, DefineMiddleware):
+        old_call = middleware.middleware.__call__  # type: ASGIApp
+    else:
+        old_call = middleware.__call__
+
+    async def _create_span_call(self, scope, receive, send):
+        # type: (MiddlewareProtocol, LitestarScope, Receive, Send) -> None
+        if sentry_sdk.get_client().get_integration(LitestarIntegration) is None:
+            return await old_call(self, scope, receive, send)
+
+        middleware_name = self.__class__.__name__
+        with sentry_sdk.start_span(
+            op=OP.MIDDLEWARE_LITESTAR,
+            name=middleware_name,
+            origin=LitestarIntegration.origin,
+        ) as middleware_span:
+            middleware_span.set_tag("litestar.middleware_name", middleware_name)
+
+            # Creating spans for the "receive" callback
+            async def _sentry_receive(*args, **kwargs):
+                # type: (*Any, **Any) -> Union[HTTPReceiveMessage, WebSocketReceiveMessage]
+                if sentry_sdk.get_client().get_integration(LitestarIntegration) is None:
+                    return await receive(*args, **kwargs)
+                with sentry_sdk.start_span(
+                    op=OP.MIDDLEWARE_LITESTAR_RECEIVE,
+                    name=getattr(receive, "__qualname__", str(receive)),
+                    origin=LitestarIntegration.origin,
+                ) as span:
+                    span.set_tag("litestar.middleware_name", middleware_name)
+                    return await receive(*args, **kwargs)
+
+            receive_name = getattr(receive, "__name__", str(receive))
+            receive_patched = receive_name == "_sentry_receive"
+            new_receive = _sentry_receive if not receive_patched else receive
+
+            # Creating spans for the "send" callback
+            async def _sentry_send(message):
+                # type: (Message) -> None
+                if sentry_sdk.get_client().get_integration(LitestarIntegration) is None:
+                    return await send(message)
+                with sentry_sdk.start_span(
+                    op=OP.MIDDLEWARE_LITESTAR_SEND,
+                    name=getattr(send, "__qualname__", str(send)),
+                    origin=LitestarIntegration.origin,
+                ) as span:
+                    span.set_tag("litestar.middleware_name", middleware_name)
+                    return await send(message)
+
+            send_name = getattr(send, "__name__", str(send))
+            send_patched = send_name == "_sentry_send"
+            new_send = _sentry_send if not send_patched else send
+
+            return await old_call(self, scope, new_receive, new_send)
+
+    not_yet_patched = old_call.__name__ not in ["_create_span_call"]
+
+    if not_yet_patched:
+        if isinstance(middleware, DefineMiddleware):
+            middleware.middleware.__call__ = _create_span_call
+        else:
+            middleware.__call__ = _create_span_call
+
+    return middleware
+
+
+def patch_http_route_handle():
+    # type: () -> None
+    old_handle = HTTPRoute.handle
+
+    async def handle_wrapper(self, scope, receive, send):
+        # type: (HTTPRoute, HTTPScope, Receive, Send) -> None
+        if sentry_sdk.get_client().get_integration(LitestarIntegration) is None:
+            return await old_handle(self, scope, receive, send)
+
+        sentry_scope = sentry_sdk.get_isolation_scope()
+        request = scope["app"].request_class(
+            scope=scope, receive=receive, send=send
+        )  # type: Request[Any, Any]
+        extracted_request_data = ConnectionDataExtractor(
+            parse_body=True, parse_query=True
+        )(request)
+        body = extracted_request_data.pop("body")
+
+        request_data = await body
+
+        def event_processor(event, _):
+            # type: (Event, Hint) -> Event
+            route_handler = scope.get("route_handler")
+
+            request_info = event.get("request", {})
+            request_info["content_length"] = len(scope.get("_body", b""))
+            if should_send_default_pii():
+                request_info["cookies"] = extracted_request_data["cookies"]
+            if request_data is not None:
+                request_info["data"] = request_data
+
+            func = None
+            if route_handler.name is not None:
+                tx_name = route_handler.name
+            # Accounts for use of type `Ref` in earlier versions of litestar without the need to reference it as a type
+            elif hasattr(route_handler.fn, "value"):
+                func = route_handler.fn.value
+            else:
+                func = route_handler.fn
+            if func is not None:
+                tx_name = transaction_from_function(func)
+
+            tx_info = {"source": SOURCE_FOR_STYLE["endpoint"]}
+
+            if not tx_name:
+                tx_name = _DEFAULT_TRANSACTION_NAME
+                tx_info = {"source": TransactionSource.ROUTE}
+
+            event.update(
+                {
+                    "request": request_info,
+                    "transaction": tx_name,
+                    "transaction_info": tx_info,
+                }
+            )
+            return event
+
+        sentry_scope._name = LitestarIntegration.identifier
+        sentry_scope.add_event_processor(event_processor)
+
+        return await old_handle(self, scope, receive, send)
+
+    HTTPRoute.handle = handle_wrapper
+
+
+def retrieve_user_from_scope(scope):
+    # type: (LitestarScope) -> Optional[dict[str, Any]]
+    scope_user = scope.get("user")
+    if isinstance(scope_user, dict):
+        return scope_user
+    if hasattr(scope_user, "asdict"):  # dataclasses
+        return scope_user.asdict()
+
+    return None
+
+
+@ensure_integration_enabled(LitestarIntegration)
+def exception_handler(exc, scope):
+    # type: (Exception, LitestarScope) -> None
+    user_info = None  # type: Optional[dict[str, Any]]
+    if should_send_default_pii():
+        user_info = retrieve_user_from_scope(scope)
+    if user_info and isinstance(user_info, dict):
+        sentry_scope = sentry_sdk.get_isolation_scope()
+        sentry_scope.set_user(user_info)
+
+    if isinstance(exc, HTTPException):
+        integration = sentry_sdk.get_client().get_integration(LitestarIntegration)
+        if (
+            integration is not None
+            and exc.status_code not in integration.failed_request_status_codes
+        ):
+            return
+
+    event, hint = event_from_exception(
+        exc,
+        client_options=sentry_sdk.get_client().options,
+        mechanism={"type": LitestarIntegration.identifier, "handled": False},
+    )
+
+    sentry_sdk.capture_event(event, hint=hint)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/logging.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/logging.py
new file mode 100644
index 0000000000000000000000000000000000000000..bfb30fc67b1c36d55d2883f24c8f6e6fa19f3ba5
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/logging.py
@@ -0,0 +1,421 @@
+import logging
+import sys
+from datetime import datetime, timezone
+from fnmatch import fnmatch
+
+import sentry_sdk
+from sentry_sdk.client import BaseClient
+from sentry_sdk.logger import _log_level_to_otel
+from sentry_sdk.utils import (
+    safe_repr,
+    to_string,
+    event_from_exception,
+    current_stacktrace,
+    capture_internal_exceptions,
+    has_logs_enabled,
+)
+from sentry_sdk.integrations import Integration
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from collections.abc import MutableMapping
+    from logging import LogRecord
+    from typing import Any
+    from typing import Dict
+    from typing import Optional
+
+DEFAULT_LEVEL = logging.INFO
+DEFAULT_EVENT_LEVEL = logging.ERROR
+LOGGING_TO_EVENT_LEVEL = {
+    logging.NOTSET: "notset",
+    logging.DEBUG: "debug",
+    logging.INFO: "info",
+    logging.WARN: "warning",  # WARN is same a WARNING
+    logging.WARNING: "warning",
+    logging.ERROR: "error",
+    logging.FATAL: "fatal",
+    logging.CRITICAL: "fatal",  # CRITICAL is same as FATAL
+}
+
+# Map logging level numbers to corresponding OTel level numbers
+SEVERITY_TO_OTEL_SEVERITY = {
+    logging.CRITICAL: 21,  # fatal
+    logging.ERROR: 17,  # error
+    logging.WARNING: 13,  # warn
+    logging.INFO: 9,  # info
+    logging.DEBUG: 5,  # debug
+}
+
+
+# Capturing events from those loggers causes recursion errors. We cannot allow
+# the user to unconditionally create events from those loggers under any
+# circumstances.
+#
+# Note: Ignoring by logger name here is better than mucking with thread-locals.
+# We do not necessarily know whether thread-locals work 100% correctly in the user's environment.
+_IGNORED_LOGGERS = set(
+    ["sentry_sdk.errors", "urllib3.connectionpool", "urllib3.connection"]
+)
+
+
+def ignore_logger(
+    name,  # type: str
+):
+    # type: (...) -> None
+    """This disables recording (both in breadcrumbs and as events) calls to
+    a logger of a specific name.  Among other uses, many of our integrations
+    use this to prevent their actions being recorded as breadcrumbs. Exposed
+    to users as a way to quiet spammy loggers.
+
+    :param name: The name of the logger to ignore (same string you would pass to ``logging.getLogger``).
+    """
+    _IGNORED_LOGGERS.add(name)
+
+
+class LoggingIntegration(Integration):
+    identifier = "logging"
+
+    def __init__(
+        self,
+        level=DEFAULT_LEVEL,
+        event_level=DEFAULT_EVENT_LEVEL,
+        sentry_logs_level=DEFAULT_LEVEL,
+    ):
+        # type: (Optional[int], Optional[int], Optional[int]) -> None
+        self._handler = None
+        self._breadcrumb_handler = None
+        self._sentry_logs_handler = None
+
+        if level is not None:
+            self._breadcrumb_handler = BreadcrumbHandler(level=level)
+
+        if sentry_logs_level is not None:
+            self._sentry_logs_handler = SentryLogsHandler(level=sentry_logs_level)
+
+        if event_level is not None:
+            self._handler = EventHandler(level=event_level)
+
+    def _handle_record(self, record):
+        # type: (LogRecord) -> None
+        if self._handler is not None and record.levelno >= self._handler.level:
+            self._handler.handle(record)
+
+        if (
+            self._breadcrumb_handler is not None
+            and record.levelno >= self._breadcrumb_handler.level
+        ):
+            self._breadcrumb_handler.handle(record)
+
+        if (
+            self._sentry_logs_handler is not None
+            and record.levelno >= self._sentry_logs_handler.level
+        ):
+            self._sentry_logs_handler.handle(record)
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        old_callhandlers = logging.Logger.callHandlers
+
+        def sentry_patched_callhandlers(self, record):
+            # type: (Any, LogRecord) -> Any
+            # keeping a local reference because the
+            # global might be discarded on shutdown
+            ignored_loggers = _IGNORED_LOGGERS
+
+            try:
+                return old_callhandlers(self, record)
+            finally:
+                # This check is done twice, once also here before we even get
+                # the integration.  Otherwise we have a high chance of getting
+                # into a recursion error when the integration is resolved
+                # (this also is slower).
+                if (
+                    ignored_loggers is not None
+                    and record.name.strip() not in ignored_loggers
+                ):
+                    integration = sentry_sdk.get_client().get_integration(
+                        LoggingIntegration
+                    )
+                    if integration is not None:
+                        integration._handle_record(record)
+
+        logging.Logger.callHandlers = sentry_patched_callhandlers  # type: ignore
+
+
+class _BaseHandler(logging.Handler):
+    COMMON_RECORD_ATTRS = frozenset(
+        (
+            "args",
+            "created",
+            "exc_info",
+            "exc_text",
+            "filename",
+            "funcName",
+            "levelname",
+            "levelno",
+            "linenno",
+            "lineno",
+            "message",
+            "module",
+            "msecs",
+            "msg",
+            "name",
+            "pathname",
+            "process",
+            "processName",
+            "relativeCreated",
+            "stack",
+            "tags",
+            "taskName",
+            "thread",
+            "threadName",
+            "stack_info",
+        )
+    )
+
+    def _can_record(self, record):
+        # type: (LogRecord) -> bool
+        """Prevents ignored loggers from recording"""
+        for logger in _IGNORED_LOGGERS:
+            if fnmatch(record.name.strip(), logger):
+                return False
+        return True
+
+    def _logging_to_event_level(self, record):
+        # type: (LogRecord) -> str
+        return LOGGING_TO_EVENT_LEVEL.get(
+            record.levelno, record.levelname.lower() if record.levelname else ""
+        )
+
+    def _extra_from_record(self, record):
+        # type: (LogRecord) -> MutableMapping[str, object]
+        return {
+            k: v
+            for k, v in vars(record).items()
+            if k not in self.COMMON_RECORD_ATTRS
+            and (not isinstance(k, str) or not k.startswith("_"))
+        }
+
+
+class EventHandler(_BaseHandler):
+    """
+    A logging handler that emits Sentry events for each log record
+
+    Note that you do not have to use this class if the logging integration is enabled, which it is by default.
+    """
+
+    def emit(self, record):
+        # type: (LogRecord) -> Any
+        with capture_internal_exceptions():
+            self.format(record)
+            return self._emit(record)
+
+    def _emit(self, record):
+        # type: (LogRecord) -> None
+        if not self._can_record(record):
+            return
+
+        client = sentry_sdk.get_client()
+        if not client.is_active():
+            return
+
+        client_options = client.options
+
+        # exc_info might be None or (None, None, None)
+        #
+        # exc_info may also be any falsy value due to Python stdlib being
+        # liberal with what it receives and Celery's billiard being "liberal"
+        # with what it sends. See
+        # https://github.com/getsentry/sentry-python/issues/904
+        if record.exc_info and record.exc_info[0] is not None:
+            event, hint = event_from_exception(
+                record.exc_info,
+                client_options=client_options,
+                mechanism={"type": "logging", "handled": True},
+            )
+        elif (record.exc_info and record.exc_info[0] is None) or record.stack_info:
+            event = {}
+            hint = {}
+            with capture_internal_exceptions():
+                event["threads"] = {
+                    "values": [
+                        {
+                            "stacktrace": current_stacktrace(
+                                include_local_variables=client_options[
+                                    "include_local_variables"
+                                ],
+                                max_value_length=client_options["max_value_length"],
+                            ),
+                            "crashed": False,
+                            "current": True,
+                        }
+                    ]
+                }
+        else:
+            event = {}
+            hint = {}
+
+        hint["log_record"] = record
+
+        level = self._logging_to_event_level(record)
+        if level in {"debug", "info", "warning", "error", "critical", "fatal"}:
+            event["level"] = level  # type: ignore[typeddict-item]
+        event["logger"] = record.name
+
+        if (
+            sys.version_info < (3, 11)
+            and record.name == "py.warnings"
+            and record.msg == "%s"
+        ):
+            # warnings module on Python 3.10 and below sets record.msg to "%s"
+            # and record.args[0] to the actual warning message.
+            # This was fixed in https://github.com/python/cpython/pull/30975.
+            message = record.args[0]
+            params = ()
+        else:
+            message = record.msg
+            params = record.args
+
+        event["logentry"] = {
+            "message": to_string(message),
+            "formatted": record.getMessage(),
+            "params": params,
+        }
+
+        event["extra"] = self._extra_from_record(record)
+
+        sentry_sdk.capture_event(event, hint=hint)
+
+
+# Legacy name
+SentryHandler = EventHandler
+
+
+class BreadcrumbHandler(_BaseHandler):
+    """
+    A logging handler that records breadcrumbs for each log record.
+
+    Note that you do not have to use this class if the logging integration is enabled, which it is by default.
+    """
+
+    def emit(self, record):
+        # type: (LogRecord) -> Any
+        with capture_internal_exceptions():
+            self.format(record)
+            return self._emit(record)
+
+    def _emit(self, record):
+        # type: (LogRecord) -> None
+        if not self._can_record(record):
+            return
+
+        sentry_sdk.add_breadcrumb(
+            self._breadcrumb_from_record(record), hint={"log_record": record}
+        )
+
+    def _breadcrumb_from_record(self, record):
+        # type: (LogRecord) -> Dict[str, Any]
+        return {
+            "type": "log",
+            "level": self._logging_to_event_level(record),
+            "category": record.name,
+            "message": record.message,
+            "timestamp": datetime.fromtimestamp(record.created, timezone.utc),
+            "data": self._extra_from_record(record),
+        }
+
+
+class SentryLogsHandler(_BaseHandler):
+    """
+    A logging handler that records Sentry logs for each Python log record.
+
+    Note that you do not have to use this class if the logging integration is enabled, which it is by default.
+    """
+
+    def emit(self, record):
+        # type: (LogRecord) -> Any
+        with capture_internal_exceptions():
+            self.format(record)
+            if not self._can_record(record):
+                return
+
+            client = sentry_sdk.get_client()
+            if not client.is_active():
+                return
+
+            if not has_logs_enabled(client.options):
+                return
+
+            self._capture_log_from_record(client, record)
+
+    def _capture_log_from_record(self, client, record):
+        # type: (BaseClient, LogRecord) -> None
+        otel_severity_number, otel_severity_text = _log_level_to_otel(
+            record.levelno, SEVERITY_TO_OTEL_SEVERITY
+        )
+        project_root = client.options["project_root"]
+
+        attrs = self._extra_from_record(record)  # type: Any
+        attrs["sentry.origin"] = "auto.logger.log"
+
+        parameters_set = False
+        if record.args is not None:
+            if isinstance(record.args, tuple):
+                parameters_set = bool(record.args)
+                for i, arg in enumerate(record.args):
+                    attrs[f"sentry.message.parameter.{i}"] = (
+                        arg
+                        if isinstance(arg, (str, float, int, bool))
+                        else safe_repr(arg)
+                    )
+            elif isinstance(record.args, dict):
+                parameters_set = bool(record.args)
+                for key, value in record.args.items():
+                    attrs[f"sentry.message.parameter.{key}"] = (
+                        value
+                        if isinstance(value, (str, float, int, bool))
+                        else safe_repr(value)
+                    )
+
+        if parameters_set and isinstance(record.msg, str):
+            # only include template if there is at least one
+            # sentry.message.parameter.X set
+            attrs["sentry.message.template"] = record.msg
+
+        if record.lineno:
+            attrs["code.line.number"] = record.lineno
+
+        if record.pathname:
+            if project_root is not None and record.pathname.startswith(project_root):
+                attrs["code.file.path"] = record.pathname[len(project_root) + 1 :]
+            else:
+                attrs["code.file.path"] = record.pathname
+
+        if record.funcName:
+            attrs["code.function.name"] = record.funcName
+
+        if record.thread:
+            attrs["thread.id"] = record.thread
+        if record.threadName:
+            attrs["thread.name"] = record.threadName
+
+        if record.process:
+            attrs["process.pid"] = record.process
+        if record.processName:
+            attrs["process.executable.name"] = record.processName
+        if record.name:
+            attrs["logger.name"] = record.name
+
+        # noinspection PyProtectedMember
+        client._capture_experimental_log(
+            {
+                "severity_text": otel_severity_text,
+                "severity_number": otel_severity_number,
+                "body": record.message,
+                "attributes": attrs,
+                "time_unix_nano": int(record.created * 1e9),
+                "trace_id": None,
+            },
+        )
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/loguru.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/loguru.py
new file mode 100644
index 0000000000000000000000000000000000000000..b910b9a407f3641fb21635b1524d1cb2571b8d19
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/loguru.py
@@ -0,0 +1,205 @@
+import enum
+
+import sentry_sdk
+from sentry_sdk.integrations import Integration, DidNotEnable
+from sentry_sdk.integrations.logging import (
+    BreadcrumbHandler,
+    EventHandler,
+    _BaseHandler,
+)
+from sentry_sdk.logger import _log_level_to_otel
+from sentry_sdk.utils import has_logs_enabled
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from logging import LogRecord
+    from typing import Any, Optional
+
+try:
+    import loguru
+    from loguru import logger
+    from loguru._defaults import LOGURU_FORMAT as DEFAULT_FORMAT
+
+    if TYPE_CHECKING:
+        from loguru import Message
+except ImportError:
+    raise DidNotEnable("LOGURU is not installed")
+
+
+class LoggingLevels(enum.IntEnum):
+    TRACE = 5
+    DEBUG = 10
+    INFO = 20
+    SUCCESS = 25
+    WARNING = 30
+    ERROR = 40
+    CRITICAL = 50
+
+
+DEFAULT_LEVEL = LoggingLevels.INFO.value
+DEFAULT_EVENT_LEVEL = LoggingLevels.ERROR.value
+
+
+SENTRY_LEVEL_FROM_LOGURU_LEVEL = {
+    "TRACE": "DEBUG",
+    "DEBUG": "DEBUG",
+    "INFO": "INFO",
+    "SUCCESS": "INFO",
+    "WARNING": "WARNING",
+    "ERROR": "ERROR",
+    "CRITICAL": "CRITICAL",
+}
+
+# Map Loguru level numbers to corresponding OTel level numbers
+SEVERITY_TO_OTEL_SEVERITY = {
+    LoggingLevels.CRITICAL: 21,  # fatal
+    LoggingLevels.ERROR: 17,  # error
+    LoggingLevels.WARNING: 13,  # warn
+    LoggingLevels.SUCCESS: 11,  # info
+    LoggingLevels.INFO: 9,  # info
+    LoggingLevels.DEBUG: 5,  # debug
+    LoggingLevels.TRACE: 1,  # trace
+}
+
+
+class LoguruIntegration(Integration):
+    identifier = "loguru"
+
+    level = DEFAULT_LEVEL  # type: Optional[int]
+    event_level = DEFAULT_EVENT_LEVEL  # type: Optional[int]
+    breadcrumb_format = DEFAULT_FORMAT
+    event_format = DEFAULT_FORMAT
+    sentry_logs_level = DEFAULT_LEVEL  # type: Optional[int]
+
+    def __init__(
+        self,
+        level=DEFAULT_LEVEL,
+        event_level=DEFAULT_EVENT_LEVEL,
+        breadcrumb_format=DEFAULT_FORMAT,
+        event_format=DEFAULT_FORMAT,
+        sentry_logs_level=DEFAULT_LEVEL,
+    ):
+        # type: (Optional[int], Optional[int], str | loguru.FormatFunction, str | loguru.FormatFunction, Optional[int]) -> None
+        LoguruIntegration.level = level
+        LoguruIntegration.event_level = event_level
+        LoguruIntegration.breadcrumb_format = breadcrumb_format
+        LoguruIntegration.event_format = event_format
+        LoguruIntegration.sentry_logs_level = sentry_logs_level
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        if LoguruIntegration.level is not None:
+            logger.add(
+                LoguruBreadcrumbHandler(level=LoguruIntegration.level),
+                level=LoguruIntegration.level,
+                format=LoguruIntegration.breadcrumb_format,
+            )
+
+        if LoguruIntegration.event_level is not None:
+            logger.add(
+                LoguruEventHandler(level=LoguruIntegration.event_level),
+                level=LoguruIntegration.event_level,
+                format=LoguruIntegration.event_format,
+            )
+
+        if LoguruIntegration.sentry_logs_level is not None:
+            logger.add(
+                loguru_sentry_logs_handler,
+                level=LoguruIntegration.sentry_logs_level,
+            )
+
+
+class _LoguruBaseHandler(_BaseHandler):
+    def __init__(self, *args, **kwargs):
+        # type: (*Any, **Any) -> None
+        if kwargs.get("level"):
+            kwargs["level"] = SENTRY_LEVEL_FROM_LOGURU_LEVEL.get(
+                kwargs.get("level", ""), DEFAULT_LEVEL
+            )
+
+        super().__init__(*args, **kwargs)
+
+    def _logging_to_event_level(self, record):
+        # type: (LogRecord) -> str
+        try:
+            return SENTRY_LEVEL_FROM_LOGURU_LEVEL[
+                LoggingLevels(record.levelno).name
+            ].lower()
+        except (ValueError, KeyError):
+            return record.levelname.lower() if record.levelname else ""
+
+
+class LoguruEventHandler(_LoguruBaseHandler, EventHandler):
+    """Modified version of :class:`sentry_sdk.integrations.logging.EventHandler` to use loguru's level names."""
+
+    pass
+
+
+class LoguruBreadcrumbHandler(_LoguruBaseHandler, BreadcrumbHandler):
+    """Modified version of :class:`sentry_sdk.integrations.logging.BreadcrumbHandler` to use loguru's level names."""
+
+    pass
+
+
+def loguru_sentry_logs_handler(message):
+    # type: (Message) -> None
+    # This is intentionally a callable sink instead of a standard logging handler
+    # since otherwise we wouldn't get direct access to message.record
+    client = sentry_sdk.get_client()
+
+    if not client.is_active():
+        return
+
+    if not has_logs_enabled(client.options):
+        return
+
+    record = message.record
+
+    if (
+        LoguruIntegration.sentry_logs_level is None
+        or record["level"].no < LoguruIntegration.sentry_logs_level
+    ):
+        return
+
+    otel_severity_number, otel_severity_text = _log_level_to_otel(
+        record["level"].no, SEVERITY_TO_OTEL_SEVERITY
+    )
+
+    attrs = {"sentry.origin": "auto.logger.loguru"}  # type: dict[str, Any]
+
+    project_root = client.options["project_root"]
+    if record.get("file"):
+        if project_root is not None and record["file"].path.startswith(project_root):
+            attrs["code.file.path"] = record["file"].path[len(project_root) + 1 :]
+        else:
+            attrs["code.file.path"] = record["file"].path
+
+    if record.get("line") is not None:
+        attrs["code.line.number"] = record["line"]
+
+    if record.get("function"):
+        attrs["code.function.name"] = record["function"]
+
+    if record.get("thread"):
+        attrs["thread.name"] = record["thread"].name
+        attrs["thread.id"] = record["thread"].id
+
+    if record.get("process"):
+        attrs["process.pid"] = record["process"].id
+        attrs["process.executable.name"] = record["process"].name
+
+    if record.get("name"):
+        attrs["logger.name"] = record["name"]
+
+    client._capture_experimental_log(
+        {
+            "severity_text": otel_severity_text,
+            "severity_number": otel_severity_number,
+            "body": record["message"],
+            "attributes": attrs,
+            "time_unix_nano": int(record["time"].timestamp() * 1e9),
+            "trace_id": None,
+        }
+    )
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/modules.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/modules.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce3ee786651e0524a0750c700c649bcf1bcde8dc
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/modules.py
@@ -0,0 +1,29 @@
+import sentry_sdk
+from sentry_sdk.integrations import Integration
+from sentry_sdk.scope import add_global_event_processor
+from sentry_sdk.utils import _get_installed_modules
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from sentry_sdk._types import Event
+
+
+class ModulesIntegration(Integration):
+    identifier = "modules"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        @add_global_event_processor
+        def processor(event, hint):
+            # type: (Event, Any) -> Event
+            if event.get("type") == "transaction":
+                return event
+
+            if sentry_sdk.get_client().get_integration(ModulesIntegration) is None:
+                return event
+
+            event["modules"] = _get_installed_modules()
+            return event
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai.py
new file mode 100644
index 0000000000000000000000000000000000000000..187f79580768d2bcbc12ebda267fcc8a5ef8d40c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai.py
@@ -0,0 +1,662 @@
+from functools import wraps
+
+import sentry_sdk
+from sentry_sdk import consts
+from sentry_sdk.ai.monitoring import record_token_usage
+from sentry_sdk.ai.utils import set_data_normalized
+from sentry_sdk.consts import SPANDATA
+from sentry_sdk.integrations import DidNotEnable, Integration
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    event_from_exception,
+    safe_serialize,
+)
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Iterable, List, Optional, Callable, AsyncIterator, Iterator
+    from sentry_sdk.tracing import Span
+
+try:
+    try:
+        from openai import NOT_GIVEN
+    except ImportError:
+        NOT_GIVEN = None
+
+    from openai.resources.chat.completions import Completions, AsyncCompletions
+    from openai.resources import Embeddings, AsyncEmbeddings
+
+    if TYPE_CHECKING:
+        from openai.types.chat import ChatCompletionMessageParam, ChatCompletionChunk
+except ImportError:
+    raise DidNotEnable("OpenAI not installed")
+
+RESPONSES_API_ENABLED = True
+try:
+    # responses API support was introduced in v1.66.0
+    from openai.resources.responses import Responses, AsyncResponses
+    from openai.types.responses.response_completed_event import ResponseCompletedEvent
+except ImportError:
+    RESPONSES_API_ENABLED = False
+
+
+class OpenAIIntegration(Integration):
+    identifier = "openai"
+    origin = f"auto.ai.{identifier}"
+
+    def __init__(self, include_prompts=True, tiktoken_encoding_name=None):
+        # type: (OpenAIIntegration, bool, Optional[str]) -> None
+        self.include_prompts = include_prompts
+
+        self.tiktoken_encoding = None
+        if tiktoken_encoding_name is not None:
+            import tiktoken  # type: ignore
+
+            self.tiktoken_encoding = tiktoken.get_encoding(tiktoken_encoding_name)
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        Completions.create = _wrap_chat_completion_create(Completions.create)
+        AsyncCompletions.create = _wrap_async_chat_completion_create(
+            AsyncCompletions.create
+        )
+
+        Embeddings.create = _wrap_embeddings_create(Embeddings.create)
+        AsyncEmbeddings.create = _wrap_async_embeddings_create(AsyncEmbeddings.create)
+
+        if RESPONSES_API_ENABLED:
+            Responses.create = _wrap_responses_create(Responses.create)
+            AsyncResponses.create = _wrap_async_responses_create(AsyncResponses.create)
+
+    def count_tokens(self, s):
+        # type: (OpenAIIntegration, str) -> int
+        if self.tiktoken_encoding is not None:
+            return len(self.tiktoken_encoding.encode_ordinary(s))
+        return 0
+
+
+def _capture_exception(exc):
+    # type: (Any) -> None
+    # Close an eventually open span
+    # We need to do this by hand because we are not using the start_span context manager
+    current_span = sentry_sdk.get_current_span()
+    if current_span is not None:
+        current_span.__exit__(None, None, None)
+
+    event, hint = event_from_exception(
+        exc,
+        client_options=sentry_sdk.get_client().options,
+        mechanism={"type": "openai", "handled": False},
+    )
+    sentry_sdk.capture_event(event, hint=hint)
+
+
+def _get_usage(usage, names):
+    # type: (Any, List[str]) -> int
+    for name in names:
+        if hasattr(usage, name) and isinstance(getattr(usage, name), int):
+            return getattr(usage, name)
+    return 0
+
+
+def _calculate_token_usage(
+    messages, response, span, streaming_message_responses, count_tokens
+):
+    # type: (Optional[Iterable[ChatCompletionMessageParam]], Any, Span, Optional[List[str]], Callable[..., Any]) -> None
+    input_tokens = 0  # type: Optional[int]
+    input_tokens_cached = 0  # type: Optional[int]
+    output_tokens = 0  # type: Optional[int]
+    output_tokens_reasoning = 0  # type: Optional[int]
+    total_tokens = 0  # type: Optional[int]
+
+    if hasattr(response, "usage"):
+        input_tokens = _get_usage(response.usage, ["input_tokens", "prompt_tokens"])
+        if hasattr(response.usage, "input_tokens_details"):
+            input_tokens_cached = _get_usage(
+                response.usage.input_tokens_details, ["cached_tokens"]
+            )
+
+        output_tokens = _get_usage(
+            response.usage, ["output_tokens", "completion_tokens"]
+        )
+        if hasattr(response.usage, "output_tokens_details"):
+            output_tokens_reasoning = _get_usage(
+                response.usage.output_tokens_details, ["reasoning_tokens"]
+            )
+
+        total_tokens = _get_usage(response.usage, ["total_tokens"])
+
+    # Manually count tokens
+    if input_tokens == 0:
+        for message in messages or []:
+            if isinstance(message, dict) and "content" in message:
+                input_tokens += count_tokens(message["content"])
+            elif isinstance(message, str):
+                input_tokens += count_tokens(message)
+
+    if output_tokens == 0:
+        if streaming_message_responses is not None:
+            for message in streaming_message_responses:
+                output_tokens += count_tokens(message)
+        elif hasattr(response, "choices"):
+            for choice in response.choices:
+                if hasattr(choice, "message"):
+                    output_tokens += count_tokens(choice.message)
+
+    # Do not set token data if it is 0
+    input_tokens = input_tokens or None
+    input_tokens_cached = input_tokens_cached or None
+    output_tokens = output_tokens or None
+    output_tokens_reasoning = output_tokens_reasoning or None
+    total_tokens = total_tokens or None
+
+    record_token_usage(
+        span,
+        input_tokens=input_tokens,
+        input_tokens_cached=input_tokens_cached,
+        output_tokens=output_tokens,
+        output_tokens_reasoning=output_tokens_reasoning,
+        total_tokens=total_tokens,
+    )
+
+
+def _set_input_data(span, kwargs, operation, integration):
+    # type: (Span, dict[str, Any], str, OpenAIIntegration) -> None
+    # Input messages (the prompt or data sent to the model)
+    messages = kwargs.get("messages")
+    if messages is None:
+        messages = kwargs.get("input")
+
+    if isinstance(messages, str):
+        messages = [messages]
+
+    if (
+        messages is not None
+        and len(messages) > 0
+        and should_send_default_pii()
+        and integration.include_prompts
+    ):
+        set_data_normalized(span, SPANDATA.GEN_AI_REQUEST_MESSAGES, messages)
+
+    # Input attributes: Common
+    set_data_normalized(span, SPANDATA.GEN_AI_SYSTEM, "openai")
+    set_data_normalized(span, SPANDATA.GEN_AI_OPERATION_NAME, operation)
+
+    # Input attributes: Optional
+    kwargs_keys_to_attributes = {
+        "model": SPANDATA.GEN_AI_REQUEST_MODEL,
+        "stream": SPANDATA.GEN_AI_RESPONSE_STREAMING,
+        "max_tokens": SPANDATA.GEN_AI_REQUEST_MAX_TOKENS,
+        "presence_penalty": SPANDATA.GEN_AI_REQUEST_PRESENCE_PENALTY,
+        "frequency_penalty": SPANDATA.GEN_AI_REQUEST_FREQUENCY_PENALTY,
+        "temperature": SPANDATA.GEN_AI_REQUEST_TEMPERATURE,
+        "top_p": SPANDATA.GEN_AI_REQUEST_TOP_P,
+    }
+    for key, attribute in kwargs_keys_to_attributes.items():
+        value = kwargs.get(key)
+
+        if value is not NOT_GIVEN and value is not None:
+            set_data_normalized(span, attribute, value)
+
+    # Input attributes: Tools
+    tools = kwargs.get("tools")
+    if tools is not NOT_GIVEN and tools is not None and len(tools) > 0:
+        set_data_normalized(
+            span, SPANDATA.GEN_AI_REQUEST_AVAILABLE_TOOLS, safe_serialize(tools)
+        )
+
+
+def _set_output_data(span, response, kwargs, integration, finish_span=True):
+    # type: (Span, Any, dict[str, Any], OpenAIIntegration, bool) -> None
+    if hasattr(response, "model"):
+        set_data_normalized(span, SPANDATA.GEN_AI_RESPONSE_MODEL, response.model)
+
+    # Input messages (the prompt or data sent to the model)
+    # used for the token usage calculation
+    messages = kwargs.get("messages")
+    if messages is None:
+        messages = kwargs.get("input")
+
+    if messages is not None and isinstance(messages, str):
+        messages = [messages]
+
+    if hasattr(response, "choices"):
+        if should_send_default_pii() and integration.include_prompts:
+            response_text = [choice.message.dict() for choice in response.choices]
+            if len(response_text) > 0:
+                set_data_normalized(
+                    span,
+                    SPANDATA.GEN_AI_RESPONSE_TEXT,
+                    safe_serialize(response_text),
+                )
+        _calculate_token_usage(messages, response, span, None, integration.count_tokens)
+        if finish_span:
+            span.__exit__(None, None, None)
+
+    elif hasattr(response, "output"):
+        if should_send_default_pii() and integration.include_prompts:
+            response_text = [item.to_dict() for item in response.output]
+            if len(response_text) > 0:
+                set_data_normalized(
+                    span,
+                    SPANDATA.GEN_AI_RESPONSE_TEXT,
+                    safe_serialize(response_text),
+                )
+        _calculate_token_usage(messages, response, span, None, integration.count_tokens)
+        if finish_span:
+            span.__exit__(None, None, None)
+
+    elif hasattr(response, "_iterator"):
+        data_buf: list[list[str]] = []  # one for each choice
+
+        old_iterator = response._iterator
+
+        def new_iterator():
+            # type: () -> Iterator[ChatCompletionChunk]
+            with capture_internal_exceptions():
+                count_tokens_manually = True
+                for x in old_iterator:
+                    # OpenAI chat completion API
+                    if hasattr(x, "choices"):
+                        choice_index = 0
+                        for choice in x.choices:
+                            if hasattr(choice, "delta") and hasattr(
+                                choice.delta, "content"
+                            ):
+                                content = choice.delta.content
+                                if len(data_buf) <= choice_index:
+                                    data_buf.append([])
+                                data_buf[choice_index].append(content or "")
+                            choice_index += 1
+
+                    # OpenAI responses API
+                    elif hasattr(x, "delta"):
+                        if len(data_buf) == 0:
+                            data_buf.append([])
+                        data_buf[0].append(x.delta or "")
+
+                    # OpenAI responses API end of streaming response
+                    if RESPONSES_API_ENABLED and isinstance(x, ResponseCompletedEvent):
+                        _calculate_token_usage(
+                            messages,
+                            x.response,
+                            span,
+                            None,
+                            integration.count_tokens,
+                        )
+                        count_tokens_manually = False
+
+                    yield x
+
+                if len(data_buf) > 0:
+                    all_responses = ["".join(chunk) for chunk in data_buf]
+                    if should_send_default_pii() and integration.include_prompts:
+                        set_data_normalized(
+                            span, SPANDATA.GEN_AI_RESPONSE_TEXT, all_responses
+                        )
+                    if count_tokens_manually:
+                        _calculate_token_usage(
+                            messages,
+                            response,
+                            span,
+                            all_responses,
+                            integration.count_tokens,
+                        )
+
+            if finish_span:
+                span.__exit__(None, None, None)
+
+        async def new_iterator_async():
+            # type: () -> AsyncIterator[ChatCompletionChunk]
+            with capture_internal_exceptions():
+                count_tokens_manually = True
+                async for x in old_iterator:
+                    # OpenAI chat completion API
+                    if hasattr(x, "choices"):
+                        choice_index = 0
+                        for choice in x.choices:
+                            if hasattr(choice, "delta") and hasattr(
+                                choice.delta, "content"
+                            ):
+                                content = choice.delta.content
+                                if len(data_buf) <= choice_index:
+                                    data_buf.append([])
+                                data_buf[choice_index].append(content or "")
+                            choice_index += 1
+
+                    # OpenAI responses API
+                    elif hasattr(x, "delta"):
+                        if len(data_buf) == 0:
+                            data_buf.append([])
+                        data_buf[0].append(x.delta or "")
+
+                    # OpenAI responses API end of streaming response
+                    if RESPONSES_API_ENABLED and isinstance(x, ResponseCompletedEvent):
+                        _calculate_token_usage(
+                            messages,
+                            x.response,
+                            span,
+                            None,
+                            integration.count_tokens,
+                        )
+                        count_tokens_manually = False
+
+                    yield x
+
+                if len(data_buf) > 0:
+                    all_responses = ["".join(chunk) for chunk in data_buf]
+                    if should_send_default_pii() and integration.include_prompts:
+                        set_data_normalized(
+                            span, SPANDATA.GEN_AI_RESPONSE_TEXT, all_responses
+                        )
+                    if count_tokens_manually:
+                        _calculate_token_usage(
+                            messages,
+                            response,
+                            span,
+                            all_responses,
+                            integration.count_tokens,
+                        )
+            if finish_span:
+                span.__exit__(None, None, None)
+
+        if str(type(response._iterator)) == "":
+            response._iterator = new_iterator_async()
+        else:
+            response._iterator = new_iterator()
+    else:
+        _calculate_token_usage(messages, response, span, None, integration.count_tokens)
+        if finish_span:
+            span.__exit__(None, None, None)
+
+
+def _new_chat_completion_common(f, *args, **kwargs):
+    # type: (Any, Any, Any) -> Any
+    integration = sentry_sdk.get_client().get_integration(OpenAIIntegration)
+    if integration is None:
+        return f(*args, **kwargs)
+
+    if "messages" not in kwargs:
+        # invalid call (in all versions of openai), let it return error
+        return f(*args, **kwargs)
+
+    try:
+        iter(kwargs["messages"])
+    except TypeError:
+        # invalid call (in all versions), messages must be iterable
+        return f(*args, **kwargs)
+
+    model = kwargs.get("model")
+    operation = "chat"
+
+    span = sentry_sdk.start_span(
+        op=consts.OP.GEN_AI_CHAT,
+        name=f"{operation} {model}",
+        origin=OpenAIIntegration.origin,
+    )
+    span.__enter__()
+
+    _set_input_data(span, kwargs, operation, integration)
+
+    response = yield f, args, kwargs
+
+    _set_output_data(span, response, kwargs, integration, finish_span=True)
+
+    return response
+
+
+def _wrap_chat_completion_create(f):
+    # type: (Callable[..., Any]) -> Callable[..., Any]
+    def _execute_sync(f, *args, **kwargs):
+        # type: (Any, Any, Any) -> Any
+        gen = _new_chat_completion_common(f, *args, **kwargs)
+
+        try:
+            f, args, kwargs = next(gen)
+        except StopIteration as e:
+            return e.value
+
+        try:
+            try:
+                result = f(*args, **kwargs)
+            except Exception as e:
+                _capture_exception(e)
+                raise e from None
+
+            return gen.send(result)
+        except StopIteration as e:
+            return e.value
+
+    @wraps(f)
+    def _sentry_patched_create_sync(*args, **kwargs):
+        # type: (Any, Any) -> Any
+        integration = sentry_sdk.get_client().get_integration(OpenAIIntegration)
+        if integration is None or "messages" not in kwargs:
+            # no "messages" means invalid call (in all versions of openai), let it return error
+            return f(*args, **kwargs)
+
+        return _execute_sync(f, *args, **kwargs)
+
+    return _sentry_patched_create_sync
+
+
+def _wrap_async_chat_completion_create(f):
+    # type: (Callable[..., Any]) -> Callable[..., Any]
+    async def _execute_async(f, *args, **kwargs):
+        # type: (Any, Any, Any) -> Any
+        gen = _new_chat_completion_common(f, *args, **kwargs)
+
+        try:
+            f, args, kwargs = next(gen)
+        except StopIteration as e:
+            return await e.value
+
+        try:
+            try:
+                result = await f(*args, **kwargs)
+            except Exception as e:
+                _capture_exception(e)
+                raise e from None
+
+            return gen.send(result)
+        except StopIteration as e:
+            return e.value
+
+    @wraps(f)
+    async def _sentry_patched_create_async(*args, **kwargs):
+        # type: (Any, Any) -> Any
+        integration = sentry_sdk.get_client().get_integration(OpenAIIntegration)
+        if integration is None or "messages" not in kwargs:
+            # no "messages" means invalid call (in all versions of openai), let it return error
+            return await f(*args, **kwargs)
+
+        return await _execute_async(f, *args, **kwargs)
+
+    return _sentry_patched_create_async
+
+
+def _new_embeddings_create_common(f, *args, **kwargs):
+    # type: (Any, Any, Any) -> Any
+    integration = sentry_sdk.get_client().get_integration(OpenAIIntegration)
+    if integration is None:
+        return f(*args, **kwargs)
+
+    model = kwargs.get("model")
+    operation = "embeddings"
+
+    with sentry_sdk.start_span(
+        op=consts.OP.GEN_AI_EMBEDDINGS,
+        name=f"{operation} {model}",
+        origin=OpenAIIntegration.origin,
+    ) as span:
+        _set_input_data(span, kwargs, operation, integration)
+
+        response = yield f, args, kwargs
+
+        _set_output_data(span, response, kwargs, integration, finish_span=False)
+
+        return response
+
+
+def _wrap_embeddings_create(f):
+    # type: (Any) -> Any
+    def _execute_sync(f, *args, **kwargs):
+        # type: (Any, Any, Any) -> Any
+        gen = _new_embeddings_create_common(f, *args, **kwargs)
+
+        try:
+            f, args, kwargs = next(gen)
+        except StopIteration as e:
+            return e.value
+
+        try:
+            try:
+                result = f(*args, **kwargs)
+            except Exception as e:
+                _capture_exception(e)
+                raise e from None
+
+            return gen.send(result)
+        except StopIteration as e:
+            return e.value
+
+    @wraps(f)
+    def _sentry_patched_create_sync(*args, **kwargs):
+        # type: (Any, Any) -> Any
+        integration = sentry_sdk.get_client().get_integration(OpenAIIntegration)
+        if integration is None:
+            return f(*args, **kwargs)
+
+        return _execute_sync(f, *args, **kwargs)
+
+    return _sentry_patched_create_sync
+
+
+def _wrap_async_embeddings_create(f):
+    # type: (Any) -> Any
+    async def _execute_async(f, *args, **kwargs):
+        # type: (Any, Any, Any) -> Any
+        gen = _new_embeddings_create_common(f, *args, **kwargs)
+
+        try:
+            f, args, kwargs = next(gen)
+        except StopIteration as e:
+            return await e.value
+
+        try:
+            try:
+                result = await f(*args, **kwargs)
+            except Exception as e:
+                _capture_exception(e)
+                raise e from None
+
+            return gen.send(result)
+        except StopIteration as e:
+            return e.value
+
+    @wraps(f)
+    async def _sentry_patched_create_async(*args, **kwargs):
+        # type: (Any, Any) -> Any
+        integration = sentry_sdk.get_client().get_integration(OpenAIIntegration)
+        if integration is None:
+            return await f(*args, **kwargs)
+
+        return await _execute_async(f, *args, **kwargs)
+
+    return _sentry_patched_create_async
+
+
+def _new_responses_create_common(f, *args, **kwargs):
+    # type: (Any, Any, Any) -> Any
+    integration = sentry_sdk.get_client().get_integration(OpenAIIntegration)
+    if integration is None:
+        return f(*args, **kwargs)
+
+    model = kwargs.get("model")
+    operation = "responses"
+
+    span = sentry_sdk.start_span(
+        op=consts.OP.GEN_AI_RESPONSES,
+        name=f"{operation} {model}",
+        origin=OpenAIIntegration.origin,
+    )
+    span.__enter__()
+
+    _set_input_data(span, kwargs, operation, integration)
+
+    response = yield f, args, kwargs
+
+    _set_output_data(span, response, kwargs, integration, finish_span=True)
+
+    return response
+
+
+def _wrap_responses_create(f):
+    # type: (Any) -> Any
+    def _execute_sync(f, *args, **kwargs):
+        # type: (Any, Any, Any) -> Any
+        gen = _new_responses_create_common(f, *args, **kwargs)
+
+        try:
+            f, args, kwargs = next(gen)
+        except StopIteration as e:
+            return e.value
+
+        try:
+            try:
+                result = f(*args, **kwargs)
+            except Exception as e:
+                _capture_exception(e)
+                raise e from None
+
+            return gen.send(result)
+        except StopIteration as e:
+            return e.value
+
+    @wraps(f)
+    def _sentry_patched_create_sync(*args, **kwargs):
+        # type: (Any, Any) -> Any
+        integration = sentry_sdk.get_client().get_integration(OpenAIIntegration)
+        if integration is None:
+            return f(*args, **kwargs)
+
+        return _execute_sync(f, *args, **kwargs)
+
+    return _sentry_patched_create_sync
+
+
+def _wrap_async_responses_create(f):
+    # type: (Any) -> Any
+    async def _execute_async(f, *args, **kwargs):
+        # type: (Any, Any, Any) -> Any
+        gen = _new_responses_create_common(f, *args, **kwargs)
+
+        try:
+            f, args, kwargs = next(gen)
+        except StopIteration as e:
+            return await e.value
+
+        try:
+            try:
+                result = await f(*args, **kwargs)
+            except Exception as e:
+                _capture_exception(e)
+                raise e from None
+
+            return gen.send(result)
+        except StopIteration as e:
+            return e.value
+
+    @wraps(f)
+    async def _sentry_patched_responses_async(*args, **kwargs):
+        # type: (Any, Any) -> Any
+        integration = sentry_sdk.get_client().get_integration(OpenAIIntegration)
+        if integration is None:
+            return await f(*args, **kwargs)
+
+        return await _execute_async(f, *args, **kwargs)
+
+    return _sentry_patched_responses_async
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..06b6459441d7bdde4bd3f9861555b4bf3a00e533
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/__init__.py
@@ -0,0 +1,53 @@
+from sentry_sdk.integrations import DidNotEnable, Integration
+
+from .patches import (
+    _create_get_model_wrapper,
+    _create_get_all_tools_wrapper,
+    _create_run_wrapper,
+    _patch_agent_run,
+)
+
+try:
+    import agents
+
+except ImportError:
+    raise DidNotEnable("OpenAI Agents not installed")
+
+
+def _patch_runner():
+    # type: () -> None
+    # Create the root span for one full agent run (including eventual handoffs)
+    # Note agents.run.DEFAULT_AGENT_RUNNER.run_sync is a wrapper around
+    # agents.run.DEFAULT_AGENT_RUNNER.run. It does not need to be wrapped separately.
+    # TODO-anton: Also patch streaming runner: agents.Runner.run_streamed
+    agents.run.DEFAULT_AGENT_RUNNER.run = _create_run_wrapper(
+        agents.run.DEFAULT_AGENT_RUNNER.run
+    )
+
+    # Creating the actual spans for each agent run.
+    _patch_agent_run()
+
+
+def _patch_model():
+    # type: () -> None
+    agents.run.AgentRunner._get_model = classmethod(
+        _create_get_model_wrapper(agents.run.AgentRunner._get_model),
+    )
+
+
+def _patch_tools():
+    # type: () -> None
+    agents.run.AgentRunner._get_all_tools = classmethod(
+        _create_get_all_tools_wrapper(agents.run.AgentRunner._get_all_tools),
+    )
+
+
+class OpenAIAgentsIntegration(Integration):
+    identifier = "openai_agents"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        _patch_tools()
+        _patch_model()
+        _patch_runner()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..45e525eb6a41a500db42ad066c54886a211faf24
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/__pycache__/consts.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/__pycache__/consts.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2082df26c04ec05fae7d2c9fc6b7ec8bfc4231bd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/__pycache__/consts.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/__pycache__/utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e14f86b7093d3b3d2354ef6237eec15a5bb65c93
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/__pycache__/utils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/consts.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/consts.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5de978be0d4ea3ded5c0421f193edfcb341e512
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/consts.py
@@ -0,0 +1 @@
+SPAN_ORIGIN = "auto.ai.openai_agents"
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..06bb1711f88c7fe0f7e72a1a3c56167518a22ef0
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/__init__.py
@@ -0,0 +1,4 @@
+from .models import _create_get_model_wrapper  # noqa: F401
+from .tools import _create_get_all_tools_wrapper  # noqa: F401
+from .runner import _create_run_wrapper  # noqa: F401
+from .agent_run import _patch_agent_run  # noqa: F401
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..752931970d9623f31d31618f5fdba06c325b98e8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/__pycache__/agent_run.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/__pycache__/agent_run.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ccffa476356740e7ec150d0fffa78126d88fc36
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/__pycache__/agent_run.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/__pycache__/models.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/__pycache__/models.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6c9e6785a2ffe0f8819f2e545718d1d0f2670c99
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/__pycache__/models.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/__pycache__/runner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/__pycache__/runner.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..548abb331c9e2eb0e4f14820144c6d6c7a0722e7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/__pycache__/runner.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/__pycache__/tools.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/__pycache__/tools.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ebfef1fe8f69a7665524efe53de8302078f89c9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/__pycache__/tools.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/agent_run.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/agent_run.py
new file mode 100644
index 0000000000000000000000000000000000000000..29002f66190cd34cd8a4b193ac1ac8730e0c266a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/agent_run.py
@@ -0,0 +1,140 @@
+from functools import wraps
+
+from sentry_sdk.integrations import DidNotEnable
+from ..spans import invoke_agent_span, update_invoke_agent_span, handoff_span
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Optional
+
+try:
+    import agents
+except ImportError:
+    raise DidNotEnable("OpenAI Agents not installed")
+
+
+def _patch_agent_run():
+    # type: () -> None
+    """
+    Patches AgentRunner methods to create agent invocation spans.
+    This directly patches the execution flow to track when agents start and stop.
+    """
+
+    # Store original methods
+    original_run_single_turn = agents.run.AgentRunner._run_single_turn
+    original_execute_handoffs = agents._run_impl.RunImpl.execute_handoffs
+    original_execute_final_output = agents._run_impl.RunImpl.execute_final_output
+
+    def _start_invoke_agent_span(context_wrapper, agent):
+        # type: (agents.RunContextWrapper, agents.Agent) -> None
+        """Start an agent invocation span"""
+        # Store the agent on the context wrapper so we can access it later
+        context_wrapper._sentry_current_agent = agent
+        invoke_agent_span(context_wrapper, agent)
+
+    def _end_invoke_agent_span(context_wrapper, agent, output=None):
+        # type: (agents.RunContextWrapper, agents.Agent, Optional[Any]) -> None
+        """End the agent invocation span"""
+        # Clear the stored agent
+        if hasattr(context_wrapper, "_sentry_current_agent"):
+            delattr(context_wrapper, "_sentry_current_agent")
+
+        update_invoke_agent_span(context_wrapper, agent, output)
+
+    def _has_active_agent_span(context_wrapper):
+        # type: (agents.RunContextWrapper) -> bool
+        """Check if there's an active agent span for this context"""
+        return getattr(context_wrapper, "_sentry_current_agent", None) is not None
+
+    def _get_current_agent(context_wrapper):
+        # type: (agents.RunContextWrapper) -> Optional[agents.Agent]
+        """Get the current agent from context wrapper"""
+        return getattr(context_wrapper, "_sentry_current_agent", None)
+
+    @wraps(
+        original_run_single_turn.__func__
+        if hasattr(original_run_single_turn, "__func__")
+        else original_run_single_turn
+    )
+    async def patched_run_single_turn(cls, *args, **kwargs):
+        # type: (agents.Runner, *Any, **Any) -> Any
+        """Patched _run_single_turn that creates agent invocation spans"""
+        agent = kwargs.get("agent")
+        context_wrapper = kwargs.get("context_wrapper")
+        should_run_agent_start_hooks = kwargs.get("should_run_agent_start_hooks")
+
+        # Start agent span when agent starts (but only once per agent)
+        if should_run_agent_start_hooks and agent and context_wrapper:
+            # End any existing span for a different agent
+            if _has_active_agent_span(context_wrapper):
+                current_agent = _get_current_agent(context_wrapper)
+                if current_agent and current_agent != agent:
+                    _end_invoke_agent_span(context_wrapper, current_agent)
+
+            _start_invoke_agent_span(context_wrapper, agent)
+
+        # Call original method with all the correct parameters
+        result = await original_run_single_turn(*args, **kwargs)
+
+        return result
+
+    @wraps(
+        original_execute_handoffs.__func__
+        if hasattr(original_execute_handoffs, "__func__")
+        else original_execute_handoffs
+    )
+    async def patched_execute_handoffs(cls, *args, **kwargs):
+        # type: (agents.Runner, *Any, **Any) -> Any
+        """Patched execute_handoffs that creates handoff spans and ends agent span for handoffs"""
+
+        context_wrapper = kwargs.get("context_wrapper")
+        run_handoffs = kwargs.get("run_handoffs")
+        agent = kwargs.get("agent")
+
+        # Create Sentry handoff span for the first handoff (agents library only processes the first one)
+        if run_handoffs:
+            first_handoff = run_handoffs[0]
+            handoff_agent_name = first_handoff.handoff.agent_name
+            handoff_span(context_wrapper, agent, handoff_agent_name)
+
+        # Call original method with all parameters
+        try:
+            result = await original_execute_handoffs(*args, **kwargs)
+
+        finally:
+            # End span for current agent after handoff processing is complete
+            if agent and context_wrapper and _has_active_agent_span(context_wrapper):
+                _end_invoke_agent_span(context_wrapper, agent)
+
+        return result
+
+    @wraps(
+        original_execute_final_output.__func__
+        if hasattr(original_execute_final_output, "__func__")
+        else original_execute_final_output
+    )
+    async def patched_execute_final_output(cls, *args, **kwargs):
+        # type: (agents.Runner, *Any, **Any) -> Any
+        """Patched execute_final_output that ends agent span for final outputs"""
+
+        agent = kwargs.get("agent")
+        context_wrapper = kwargs.get("context_wrapper")
+        final_output = kwargs.get("final_output")
+
+        # Call original method with all parameters
+        try:
+            result = await original_execute_final_output(*args, **kwargs)
+        finally:
+            # End span for current agent after final output processing is complete
+            if agent and context_wrapper and _has_active_agent_span(context_wrapper):
+                _end_invoke_agent_span(context_wrapper, agent, final_output)
+
+        return result
+
+    # Apply patches
+    agents.run.AgentRunner._run_single_turn = classmethod(patched_run_single_turn)
+    agents._run_impl.RunImpl.execute_handoffs = classmethod(patched_execute_handoffs)
+    agents._run_impl.RunImpl.execute_final_output = classmethod(
+        patched_execute_final_output
+    )
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/models.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/models.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6f24da6a11960cfafca5bfe7a4c822f8bd0ee3c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/models.py
@@ -0,0 +1,50 @@
+from functools import wraps
+
+from sentry_sdk.integrations import DidNotEnable
+
+from ..spans import ai_client_span, update_ai_client_span
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Callable
+
+
+try:
+    import agents
+except ImportError:
+    raise DidNotEnable("OpenAI Agents not installed")
+
+
+def _create_get_model_wrapper(original_get_model):
+    # type: (Callable[..., Any]) -> Callable[..., Any]
+    """
+    Wraps the agents.Runner._get_model method to wrap the get_response method of the model to create a AI client span.
+    """
+
+    @wraps(
+        original_get_model.__func__
+        if hasattr(original_get_model, "__func__")
+        else original_get_model
+    )
+    def wrapped_get_model(cls, agent, run_config):
+        # type: (agents.Runner, agents.Agent, agents.RunConfig) -> agents.Model
+
+        model = original_get_model(agent, run_config)
+        original_get_response = model.get_response
+
+        @wraps(original_get_response)
+        async def wrapped_get_response(*args, **kwargs):
+            # type: (*Any, **Any) -> Any
+            with ai_client_span(agent, kwargs) as span:
+                result = await original_get_response(*args, **kwargs)
+
+                update_ai_client_span(span, agent, kwargs, result)
+
+            return result
+
+        model.get_response = wrapped_get_response
+
+        return model
+
+    return wrapped_get_model
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/runner.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/runner.py
new file mode 100644
index 0000000000000000000000000000000000000000..745f30a38e8a810edab8b45f56b6a008edb3aff9
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/runner.py
@@ -0,0 +1,45 @@
+from functools import wraps
+
+import sentry_sdk
+
+from ..spans import agent_workflow_span
+from ..utils import _capture_exception
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Callable
+
+
+def _create_run_wrapper(original_func):
+    # type: (Callable[..., Any]) -> Callable[..., Any]
+    """
+    Wraps the agents.Runner.run methods to create a root span for the agent workflow runs.
+
+    Note agents.Runner.run_sync() is a wrapper around agents.Runner.run(),
+    so it does not need to be wrapped separately.
+    """
+
+    @wraps(original_func)
+    async def wrapper(*args, **kwargs):
+        # type: (*Any, **Any) -> Any
+        # Isolate each workflow so that when agents are run in asyncio tasks they
+        # don't touch each other's scopes
+        with sentry_sdk.isolation_scope():
+            agent = args[0]
+            with agent_workflow_span(agent):
+                result = None
+                try:
+                    result = await original_func(*args, **kwargs)
+                    return result
+                except Exception as exc:
+                    _capture_exception(exc)
+
+                    # It could be that there is a "invoke agent" span still open
+                    current_span = sentry_sdk.get_current_span()
+                    if current_span is not None and current_span.timestamp is None:
+                        current_span.__exit__(None, None, None)
+
+                    raise exc from None
+
+    return wrapper
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/tools.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..b359d3267844fc6c713a7d07b6140cc83266e08e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/patches/tools.py
@@ -0,0 +1,77 @@
+from functools import wraps
+
+from sentry_sdk.integrations import DidNotEnable
+
+from ..spans import execute_tool_span, update_execute_tool_span
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Callable
+
+try:
+    import agents
+except ImportError:
+    raise DidNotEnable("OpenAI Agents not installed")
+
+
+def _create_get_all_tools_wrapper(original_get_all_tools):
+    # type: (Callable[..., Any]) -> Callable[..., Any]
+    """
+    Wraps the agents.Runner._get_all_tools method of the Runner class to wrap all function tools with Sentry instrumentation.
+    """
+
+    @wraps(
+        original_get_all_tools.__func__
+        if hasattr(original_get_all_tools, "__func__")
+        else original_get_all_tools
+    )
+    async def wrapped_get_all_tools(cls, agent, context_wrapper):
+        # type: (agents.Runner, agents.Agent, agents.RunContextWrapper) -> list[agents.Tool]
+
+        # Get the original tools
+        tools = await original_get_all_tools(agent, context_wrapper)
+
+        wrapped_tools = []
+        for tool in tools:
+            # Wrap only the function tools (for now)
+            if tool.__class__.__name__ != "FunctionTool":
+                wrapped_tools.append(tool)
+                continue
+
+            # Create a new FunctionTool with our wrapped invoke method
+            original_on_invoke = tool.on_invoke_tool
+
+            def create_wrapped_invoke(current_tool, current_on_invoke):
+                # type: (agents.Tool, Callable[..., Any]) -> Callable[..., Any]
+                @wraps(current_on_invoke)
+                async def sentry_wrapped_on_invoke_tool(*args, **kwargs):
+                    # type: (*Any, **Any) -> Any
+                    with execute_tool_span(current_tool, *args, **kwargs) as span:
+                        # We can not capture exceptions in tool execution here because
+                        # `_on_invoke_tool` is swallowing the exception here:
+                        # https://github.com/openai/openai-agents-python/blob/main/src/agents/tool.py#L409-L422
+                        # And because function_tool is a decorator with `default_tool_error_function` set as a default parameter
+                        # I was unable to monkey patch it because those are evaluated at module import time
+                        # and the SDK is too late to patch it. I was also unable to patch `_on_invoke_tool_impl`
+                        # because it is nested inside this import time code. As if they made it hard to patch on purpose...
+                        result = await current_on_invoke(*args, **kwargs)
+                        update_execute_tool_span(span, agent, current_tool, result)
+
+                    return result
+
+                return sentry_wrapped_on_invoke_tool
+
+            wrapped_tool = agents.FunctionTool(
+                name=tool.name,
+                description=tool.description,
+                params_json_schema=tool.params_json_schema,
+                on_invoke_tool=create_wrapped_invoke(tool, original_on_invoke),
+                strict_json_schema=tool.strict_json_schema,
+                is_enabled=tool.is_enabled,
+            )
+            wrapped_tools.append(wrapped_tool)
+
+        return wrapped_tools
+
+    return wrapped_get_all_tools
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3bc453cafaf24d8d12c4767b038240d6705a51ce
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/__init__.py
@@ -0,0 +1,5 @@
+from .agent_workflow import agent_workflow_span  # noqa: F401
+from .ai_client import ai_client_span, update_ai_client_span  # noqa: F401
+from .execute_tool import execute_tool_span, update_execute_tool_span  # noqa: F401
+from .handoff import handoff_span  # noqa: F401
+from .invoke_agent import invoke_agent_span, update_invoke_agent_span  # noqa: F401
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fa4fc9b780371c69cbc128d9bb10a2d5a55fe910
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/__pycache__/agent_workflow.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/__pycache__/agent_workflow.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b8745e08d7258b50bf56ccd328e0805bac91dca6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/__pycache__/agent_workflow.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/__pycache__/ai_client.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/__pycache__/ai_client.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..796fe28d3e43f812a1a84a44bec0778a394c9395
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/__pycache__/ai_client.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/__pycache__/execute_tool.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/__pycache__/execute_tool.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d92fd51d58db1620b18c324473553b798a8feba2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/__pycache__/execute_tool.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/__pycache__/handoff.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/__pycache__/handoff.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5d695d1e658cb2f1cab13bd13a0abda6eb8512f4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/__pycache__/handoff.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/__pycache__/invoke_agent.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/__pycache__/invoke_agent.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2e04f9bc9595d578d4990d5a0f8303f00293f3de
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/__pycache__/invoke_agent.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/agent_workflow.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/agent_workflow.py
new file mode 100644
index 0000000000000000000000000000000000000000..de2f28d41e75a45e25677fd1177dd646837087ab
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/agent_workflow.py
@@ -0,0 +1,21 @@
+import sentry_sdk
+
+from ..consts import SPAN_ORIGIN
+from ..utils import _get_start_span_function
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    import agents
+
+
+def agent_workflow_span(agent):
+    # type: (agents.Agent) -> sentry_sdk.tracing.Span
+
+    # Create a transaction or a span if an transaction is already active
+    span = _get_start_span_function()(
+        name=f"{agent.name} workflow",
+        origin=SPAN_ORIGIN,
+    )
+
+    return span
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/ai_client.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/ai_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..d325ae86e3f5be5cdfecfab87c8a9c18c7bc703f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/ai_client.py
@@ -0,0 +1,39 @@
+import sentry_sdk
+from sentry_sdk.consts import OP, SPANDATA
+
+from ..consts import SPAN_ORIGIN
+from ..utils import (
+    _set_agent_data,
+    _set_input_data,
+    _set_output_data,
+    _set_usage_data,
+)
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from agents import Agent
+    from typing import Any
+
+
+def ai_client_span(agent, get_response_kwargs):
+    # type: (Agent, dict[str, Any]) -> sentry_sdk.tracing.Span
+    # TODO-anton: implement other types of operations. Now "chat" is hardcoded.
+    model_name = agent.model.model if hasattr(agent.model, "model") else agent.model
+    span = sentry_sdk.start_span(
+        op=OP.GEN_AI_CHAT,
+        description=f"chat {model_name}",
+        origin=SPAN_ORIGIN,
+    )
+    # TODO-anton: remove hardcoded stuff and replace something that also works for embedding and so on
+    span.set_data(SPANDATA.GEN_AI_OPERATION_NAME, "chat")
+
+    return span
+
+
+def update_ai_client_span(span, agent, get_response_kwargs, result):
+    # type: (sentry_sdk.tracing.Span, Agent, dict[str, Any], Any) -> None
+    _set_agent_data(span, agent)
+    _set_usage_data(span, result.usage)
+    _set_input_data(span, get_response_kwargs)
+    _set_output_data(span, result)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/execute_tool.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/execute_tool.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f9e4cb340c6bd4b68ba72df49f56ffa608c3e6b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/execute_tool.py
@@ -0,0 +1,48 @@
+import sentry_sdk
+from sentry_sdk.consts import OP, SPANDATA, SPANSTATUS
+from sentry_sdk.scope import should_send_default_pii
+
+from ..consts import SPAN_ORIGIN
+from ..utils import _set_agent_data
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    import agents
+    from typing import Any
+
+
+def execute_tool_span(tool, *args, **kwargs):
+    # type: (agents.Tool, *Any, **Any) -> sentry_sdk.tracing.Span
+    span = sentry_sdk.start_span(
+        op=OP.GEN_AI_EXECUTE_TOOL,
+        name=f"execute_tool {tool.name}",
+        origin=SPAN_ORIGIN,
+    )
+
+    span.set_data(SPANDATA.GEN_AI_OPERATION_NAME, "execute_tool")
+
+    if tool.__class__.__name__ == "FunctionTool":
+        span.set_data(SPANDATA.GEN_AI_TOOL_TYPE, "function")
+
+    span.set_data(SPANDATA.GEN_AI_TOOL_NAME, tool.name)
+    span.set_data(SPANDATA.GEN_AI_TOOL_DESCRIPTION, tool.description)
+
+    if should_send_default_pii():
+        input = args[1]
+        span.set_data(SPANDATA.GEN_AI_TOOL_INPUT, input)
+
+    return span
+
+
+def update_execute_tool_span(span, agent, tool, result):
+    # type: (sentry_sdk.tracing.Span, agents.Agent, agents.Tool, Any) -> None
+    _set_agent_data(span, agent)
+
+    if isinstance(result, str) and result.startswith(
+        "An error occurred while running the tool"
+    ):
+        span.set_status(SPANSTATUS.INTERNAL_ERROR)
+
+    if should_send_default_pii():
+        span.set_data(SPANDATA.GEN_AI_TOOL_OUTPUT, result)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/handoff.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/handoff.py
new file mode 100644
index 0000000000000000000000000000000000000000..78e6788c7d03cbf242030d5ce66298e79330188e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/handoff.py
@@ -0,0 +1,19 @@
+import sentry_sdk
+from sentry_sdk.consts import OP, SPANDATA
+
+from ..consts import SPAN_ORIGIN
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    import agents
+
+
+def handoff_span(context, from_agent, to_agent_name):
+    # type: (agents.RunContextWrapper, agents.Agent, str) -> None
+    with sentry_sdk.start_span(
+        op=OP.GEN_AI_HANDOFF,
+        name=f"handoff from {from_agent.name} to {to_agent_name}",
+        origin=SPAN_ORIGIN,
+    ) as span:
+        span.set_data(SPANDATA.GEN_AI_OPERATION_NAME, "handoff")
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/invoke_agent.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/invoke_agent.py
new file mode 100644
index 0000000000000000000000000000000000000000..549ade1246828ff69395c3a39f7eac17667d75b2
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/spans/invoke_agent.py
@@ -0,0 +1,34 @@
+import sentry_sdk
+from sentry_sdk.consts import OP, SPANDATA
+
+from ..consts import SPAN_ORIGIN
+from ..utils import _set_agent_data
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    import agents
+    from typing import Any
+
+
+def invoke_agent_span(context, agent):
+    # type: (agents.RunContextWrapper, agents.Agent) -> sentry_sdk.tracing.Span
+    span = sentry_sdk.start_span(
+        op=OP.GEN_AI_INVOKE_AGENT,
+        name=f"invoke_agent {agent.name}",
+        origin=SPAN_ORIGIN,
+    )
+    span.__enter__()
+
+    span.set_data(SPANDATA.GEN_AI_OPERATION_NAME, "invoke_agent")
+
+    _set_agent_data(span, agent)
+
+    return span
+
+
+def update_invoke_agent_span(context, agent, output):
+    # type: (agents.RunContextWrapper, agents.Agent, Any) -> None
+    current_span = sentry_sdk.get_current_span()
+    if current_span:
+        current_span.__exit__(None, None, None)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/utils.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..1525346726c6947508f636be8ee18a71373af98d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openai_agents/utils.py
@@ -0,0 +1,162 @@
+import sentry_sdk
+from sentry_sdk.consts import SPANDATA
+from sentry_sdk.integrations import DidNotEnable
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.utils import event_from_exception, safe_serialize
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Callable
+    from agents import Usage
+
+try:
+    import agents
+
+except ImportError:
+    raise DidNotEnable("OpenAI Agents not installed")
+
+
+def _capture_exception(exc):
+    # type: (Any) -> None
+    event, hint = event_from_exception(
+        exc,
+        client_options=sentry_sdk.get_client().options,
+        mechanism={"type": "openai_agents", "handled": False},
+    )
+    sentry_sdk.capture_event(event, hint=hint)
+
+
+def _get_start_span_function():
+    # type: () -> Callable[..., Any]
+    current_span = sentry_sdk.get_current_span()
+    transaction_exists = (
+        current_span is not None and current_span.containing_transaction == current_span
+    )
+    return sentry_sdk.start_span if transaction_exists else sentry_sdk.start_transaction
+
+
+def _set_agent_data(span, agent):
+    # type: (sentry_sdk.tracing.Span, agents.Agent) -> None
+    span.set_data(
+        SPANDATA.GEN_AI_SYSTEM, "openai"
+    )  # See footnote for  https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-system for explanation why.
+
+    span.set_data(SPANDATA.GEN_AI_AGENT_NAME, agent.name)
+
+    if agent.model_settings.max_tokens:
+        span.set_data(
+            SPANDATA.GEN_AI_REQUEST_MAX_TOKENS, agent.model_settings.max_tokens
+        )
+
+    if agent.model:
+        model_name = agent.model.model if hasattr(agent.model, "model") else agent.model
+        span.set_data(SPANDATA.GEN_AI_REQUEST_MODEL, model_name)
+
+    if agent.model_settings.presence_penalty:
+        span.set_data(
+            SPANDATA.GEN_AI_REQUEST_PRESENCE_PENALTY,
+            agent.model_settings.presence_penalty,
+        )
+
+    if agent.model_settings.temperature:
+        span.set_data(
+            SPANDATA.GEN_AI_REQUEST_TEMPERATURE, agent.model_settings.temperature
+        )
+
+    if agent.model_settings.top_p:
+        span.set_data(SPANDATA.GEN_AI_REQUEST_TOP_P, agent.model_settings.top_p)
+
+    if agent.model_settings.frequency_penalty:
+        span.set_data(
+            SPANDATA.GEN_AI_REQUEST_FREQUENCY_PENALTY,
+            agent.model_settings.frequency_penalty,
+        )
+
+    if len(agent.tools) > 0:
+        span.set_data(
+            SPANDATA.GEN_AI_REQUEST_AVAILABLE_TOOLS,
+            safe_serialize([vars(tool) for tool in agent.tools]),
+        )
+
+
+def _set_usage_data(span, usage):
+    # type: (sentry_sdk.tracing.Span, Usage) -> None
+    span.set_data(SPANDATA.GEN_AI_USAGE_INPUT_TOKENS, usage.input_tokens)
+    span.set_data(
+        SPANDATA.GEN_AI_USAGE_INPUT_TOKENS_CACHED,
+        usage.input_tokens_details.cached_tokens,
+    )
+    span.set_data(SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS, usage.output_tokens)
+    span.set_data(
+        SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS_REASONING,
+        usage.output_tokens_details.reasoning_tokens,
+    )
+    span.set_data(SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS, usage.total_tokens)
+
+
+def _set_input_data(span, get_response_kwargs):
+    # type: (sentry_sdk.tracing.Span, dict[str, Any]) -> None
+    if not should_send_default_pii():
+        return
+
+    messages_by_role = {
+        "system": [],
+        "user": [],
+        "assistant": [],
+        "tool": [],
+    }  # type: (dict[str, list[Any]])
+    system_instructions = get_response_kwargs.get("system_instructions")
+    if system_instructions:
+        messages_by_role["system"].append({"type": "text", "text": system_instructions})
+
+    for message in get_response_kwargs.get("input", []):
+        if "role" in message:
+            messages_by_role[message.get("role")].append(
+                {"type": "text", "text": message.get("content")}
+            )
+        else:
+            if message.get("type") == "function_call":
+                messages_by_role["assistant"].append(message)
+            elif message.get("type") == "function_call_output":
+                messages_by_role["tool"].append(message)
+
+    request_messages = []
+    for role, messages in messages_by_role.items():
+        if len(messages) > 0:
+            request_messages.append({"role": role, "content": messages})
+
+    span.set_data(SPANDATA.GEN_AI_REQUEST_MESSAGES, safe_serialize(request_messages))
+
+
+def _set_output_data(span, result):
+    # type: (sentry_sdk.tracing.Span, Any) -> None
+    if not should_send_default_pii():
+        return
+
+    output_messages = {
+        "response": [],
+        "tool": [],
+    }  # type: (dict[str, list[Any]])
+
+    for output in result.output:
+        if output.type == "function_call":
+            output_messages["tool"].append(output.dict())
+        elif output.type == "message":
+            for output_message in output.content:
+                try:
+                    output_messages["response"].append(output_message.text)
+                except AttributeError:
+                    # Unknown output message type, just return the json
+                    output_messages["response"].append(output_message.dict())
+
+    if len(output_messages["tool"]) > 0:
+        span.set_data(
+            SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS, safe_serialize(output_messages["tool"])
+        )
+
+    if len(output_messages["response"]) > 0:
+        span.set_data(
+            SPANDATA.GEN_AI_RESPONSE_TEXT, safe_serialize(output_messages["response"])
+        )
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openfeature.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openfeature.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ac73edd93f8aba5028cd24b7fd407e68ba54396
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/openfeature.py
@@ -0,0 +1,35 @@
+from typing import TYPE_CHECKING, Any
+
+from sentry_sdk.feature_flags import add_feature_flag
+from sentry_sdk.integrations import DidNotEnable, Integration
+
+try:
+    from openfeature import api
+    from openfeature.hook import Hook
+
+    if TYPE_CHECKING:
+        from openfeature.hook import HookContext, HookHints
+except ImportError:
+    raise DidNotEnable("OpenFeature is not installed")
+
+
+class OpenFeatureIntegration(Integration):
+    identifier = "openfeature"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        # Register the hook within the global openfeature hooks list.
+        api.add_hooks(hooks=[OpenFeatureHook()])
+
+
+class OpenFeatureHook(Hook):
+    def after(self, hook_context, details, hints):
+        # type: (Any, Any, Any) -> None
+        if isinstance(details.value, bool):
+            add_feature_flag(details.flag_key, details.value)
+
+    def error(self, hook_context, exception, hints):
+        # type: (HookContext, Exception, HookHints) -> None
+        if isinstance(hook_context.default_value, bool):
+            add_feature_flag(hook_context.flag_key, hook_context.default_value)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c4c1a683d27192a5e91a1f2ed8ef097ebfcb0bb
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/__init__.py
@@ -0,0 +1,7 @@
+from sentry_sdk.integrations.opentelemetry.span_processor import SentrySpanProcessor
+from sentry_sdk.integrations.opentelemetry.propagator import SentryPropagator
+
+__all__ = [
+    "SentryPropagator",
+    "SentrySpanProcessor",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ae3dfa3303bfc4a05dc191888089f08c8ef2e46
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/__pycache__/consts.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/__pycache__/consts.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..02f738b300a63bcd13cc2ac1902d53c8c170c18a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/__pycache__/consts.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/__pycache__/integration.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/__pycache__/integration.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4348e9f8f48062ceeb5bb74abbdf89aa46ea1ba1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/__pycache__/integration.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/__pycache__/propagator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/__pycache__/propagator.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fa948457f238c78ce4df650d7150b79a840d334d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/__pycache__/propagator.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/__pycache__/span_processor.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/__pycache__/span_processor.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4284aad5c108baa357ff34a32fcfecb298945de0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/__pycache__/span_processor.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/consts.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/consts.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec493449d3b2d4cd249463d21af086e8d0e30fbf
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/consts.py
@@ -0,0 +1,5 @@
+from opentelemetry.context import create_key
+
+
+SENTRY_TRACE_KEY = create_key("sentry-trace")
+SENTRY_BAGGAGE_KEY = create_key("sentry-baggage")
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/integration.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/integration.py
new file mode 100644
index 0000000000000000000000000000000000000000..43e0396c1698c9d59820db33d51de6881bedc080
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/integration.py
@@ -0,0 +1,58 @@
+"""
+IMPORTANT: The contents of this file are part of a proof of concept and as such
+are experimental and not suitable for production use. They may be changed or
+removed at any time without prior notice.
+"""
+
+from sentry_sdk.integrations import DidNotEnable, Integration
+from sentry_sdk.integrations.opentelemetry.propagator import SentryPropagator
+from sentry_sdk.integrations.opentelemetry.span_processor import SentrySpanProcessor
+from sentry_sdk.utils import logger
+
+try:
+    from opentelemetry import trace
+    from opentelemetry.propagate import set_global_textmap
+    from opentelemetry.sdk.trace import TracerProvider
+except ImportError:
+    raise DidNotEnable("opentelemetry not installed")
+
+try:
+    from opentelemetry.instrumentation.django import DjangoInstrumentor  # type: ignore[import-not-found]
+except ImportError:
+    DjangoInstrumentor = None
+
+
+CONFIGURABLE_INSTRUMENTATIONS = {
+    DjangoInstrumentor: {"is_sql_commentor_enabled": True},
+}
+
+
+class OpenTelemetryIntegration(Integration):
+    identifier = "opentelemetry"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        logger.warning(
+            "[OTel] Initializing highly experimental OpenTelemetry support. "
+            "Use at your own risk."
+        )
+
+        _setup_sentry_tracing()
+        # _setup_instrumentors()
+
+        logger.debug("[OTel] Finished setting up OpenTelemetry integration")
+
+
+def _setup_sentry_tracing():
+    # type: () -> None
+    provider = TracerProvider()
+    provider.add_span_processor(SentrySpanProcessor())
+    trace.set_tracer_provider(provider)
+    set_global_textmap(SentryPropagator())
+
+
+def _setup_instrumentors():
+    # type: () -> None
+    for instrumentor, kwargs in CONFIGURABLE_INSTRUMENTATIONS.items():
+        instrumentor().instrument(**kwargs)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/propagator.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/propagator.py
new file mode 100644
index 0000000000000000000000000000000000000000..b84d582d6e94bbff1aeb8ecd016b4e9c89c84b1b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/propagator.py
@@ -0,0 +1,117 @@
+from opentelemetry import trace
+from opentelemetry.context import (
+    Context,
+    get_current,
+    set_value,
+)
+from opentelemetry.propagators.textmap import (
+    CarrierT,
+    Getter,
+    Setter,
+    TextMapPropagator,
+    default_getter,
+    default_setter,
+)
+from opentelemetry.trace import (
+    NonRecordingSpan,
+    SpanContext,
+    TraceFlags,
+)
+
+from sentry_sdk.integrations.opentelemetry.consts import (
+    SENTRY_BAGGAGE_KEY,
+    SENTRY_TRACE_KEY,
+)
+from sentry_sdk.integrations.opentelemetry.span_processor import (
+    SentrySpanProcessor,
+)
+from sentry_sdk.tracing import (
+    BAGGAGE_HEADER_NAME,
+    SENTRY_TRACE_HEADER_NAME,
+)
+from sentry_sdk.tracing_utils import Baggage, extract_sentrytrace_data
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Optional, Set
+
+
+class SentryPropagator(TextMapPropagator):
+    """
+    Propagates tracing headers for Sentry's tracing system in a way OTel understands.
+    """
+
+    def extract(self, carrier, context=None, getter=default_getter):
+        # type: (CarrierT, Optional[Context], Getter[CarrierT]) -> Context
+        if context is None:
+            context = get_current()
+
+        sentry_trace = getter.get(carrier, SENTRY_TRACE_HEADER_NAME)
+        if not sentry_trace:
+            return context
+
+        sentrytrace = extract_sentrytrace_data(sentry_trace[0])
+        if not sentrytrace:
+            return context
+
+        context = set_value(SENTRY_TRACE_KEY, sentrytrace, context)
+
+        trace_id, span_id = sentrytrace["trace_id"], sentrytrace["parent_span_id"]
+
+        span_context = SpanContext(
+            trace_id=int(trace_id, 16),  # type: ignore
+            span_id=int(span_id, 16),  # type: ignore
+            # we simulate a sampled trace on the otel side and leave the sampling to sentry
+            trace_flags=TraceFlags(TraceFlags.SAMPLED),
+            is_remote=True,
+        )
+
+        baggage_header = getter.get(carrier, BAGGAGE_HEADER_NAME)
+
+        if baggage_header:
+            baggage = Baggage.from_incoming_header(baggage_header[0])
+        else:
+            # If there's an incoming sentry-trace but no incoming baggage header,
+            # for instance in traces coming from older SDKs,
+            # baggage will be empty and frozen and won't be populated as head SDK.
+            baggage = Baggage(sentry_items={})
+
+        baggage.freeze()
+        context = set_value(SENTRY_BAGGAGE_KEY, baggage, context)
+
+        span = NonRecordingSpan(span_context)
+        modified_context = trace.set_span_in_context(span, context)
+        return modified_context
+
+    def inject(self, carrier, context=None, setter=default_setter):
+        # type: (CarrierT, Optional[Context], Setter[CarrierT]) -> None
+        if context is None:
+            context = get_current()
+
+        current_span = trace.get_current_span(context)
+        current_span_context = current_span.get_span_context()
+
+        if not current_span_context.is_valid:
+            return
+
+        span_id = trace.format_span_id(current_span_context.span_id)
+
+        span_map = SentrySpanProcessor().otel_span_map
+        sentry_span = span_map.get(span_id, None)
+        if not sentry_span:
+            return
+
+        setter.set(carrier, SENTRY_TRACE_HEADER_NAME, sentry_span.to_traceparent())
+
+        if sentry_span.containing_transaction:
+            baggage = sentry_span.containing_transaction.get_baggage()
+            if baggage:
+                baggage_data = baggage.serialize()
+                if baggage_data:
+                    setter.set(carrier, BAGGAGE_HEADER_NAME, baggage_data)
+
+    @property
+    def fields(self):
+        # type: () -> Set[str]
+        return {SENTRY_TRACE_HEADER_NAME, BAGGAGE_HEADER_NAME}
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/span_processor.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/span_processor.py
new file mode 100644
index 0000000000000000000000000000000000000000..e00562a50990ae713ede67268439c2ccf1ea812b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/opentelemetry/span_processor.py
@@ -0,0 +1,391 @@
+from datetime import datetime, timezone
+from time import time
+from typing import TYPE_CHECKING, cast
+
+from opentelemetry.context import get_value
+from opentelemetry.sdk.trace import SpanProcessor, ReadableSpan as OTelSpan
+from opentelemetry.semconv.trace import SpanAttributes
+from opentelemetry.trace import (
+    format_span_id,
+    format_trace_id,
+    get_current_span,
+    SpanKind,
+)
+from opentelemetry.trace.span import (
+    INVALID_SPAN_ID,
+    INVALID_TRACE_ID,
+)
+from sentry_sdk import get_client, start_transaction
+from sentry_sdk.consts import INSTRUMENTER, SPANSTATUS
+from sentry_sdk.integrations.opentelemetry.consts import (
+    SENTRY_BAGGAGE_KEY,
+    SENTRY_TRACE_KEY,
+)
+from sentry_sdk.scope import add_global_event_processor
+from sentry_sdk.tracing import Transaction, Span as SentrySpan
+from sentry_sdk.utils import Dsn
+
+from urllib3.util import parse_url as urlparse
+
+if TYPE_CHECKING:
+    from typing import Any, Optional, Union
+    from opentelemetry import context as context_api
+    from sentry_sdk._types import Event, Hint
+
+OPEN_TELEMETRY_CONTEXT = "otel"
+SPAN_MAX_TIME_OPEN_MINUTES = 10
+SPAN_ORIGIN = "auto.otel"
+
+
+def link_trace_context_to_error_event(event, otel_span_map):
+    # type: (Event, dict[str, Union[Transaction, SentrySpan]]) -> Event
+    client = get_client()
+
+    if client.options["instrumenter"] != INSTRUMENTER.OTEL:
+        return event
+
+    if hasattr(event, "type") and event["type"] == "transaction":
+        return event
+
+    otel_span = get_current_span()
+    if not otel_span:
+        return event
+
+    ctx = otel_span.get_span_context()
+
+    if ctx.trace_id == INVALID_TRACE_ID or ctx.span_id == INVALID_SPAN_ID:
+        return event
+
+    sentry_span = otel_span_map.get(format_span_id(ctx.span_id), None)
+    if not sentry_span:
+        return event
+
+    contexts = event.setdefault("contexts", {})
+    contexts.setdefault("trace", {}).update(sentry_span.get_trace_context())
+
+    return event
+
+
+class SentrySpanProcessor(SpanProcessor):
+    """
+    Converts OTel spans into Sentry spans so they can be sent to the Sentry backend.
+    """
+
+    # The mapping from otel span ids to sentry spans
+    otel_span_map = {}  # type: dict[str, Union[Transaction, SentrySpan]]
+
+    # The currently open spans. Elements will be discarded after SPAN_MAX_TIME_OPEN_MINUTES
+    open_spans = {}  # type: dict[int, set[str]]
+
+    def __new__(cls):
+        # type: () -> SentrySpanProcessor
+        if not hasattr(cls, "instance"):
+            cls.instance = super().__new__(cls)
+
+        return cls.instance
+
+    def __init__(self):
+        # type: () -> None
+        @add_global_event_processor
+        def global_event_processor(event, hint):
+            # type: (Event, Hint) -> Event
+            return link_trace_context_to_error_event(event, self.otel_span_map)
+
+    def _prune_old_spans(self):
+        # type: (SentrySpanProcessor) -> None
+        """
+        Prune spans that have been open for too long.
+        """
+        current_time_minutes = int(time() / 60)
+        for span_start_minutes in list(
+            self.open_spans.keys()
+        ):  # making a list because we change the dict
+            # prune empty open spans buckets
+            if self.open_spans[span_start_minutes] == set():
+                self.open_spans.pop(span_start_minutes)
+
+            # prune old buckets
+            elif current_time_minutes - span_start_minutes > SPAN_MAX_TIME_OPEN_MINUTES:
+                for span_id in self.open_spans.pop(span_start_minutes):
+                    self.otel_span_map.pop(span_id, None)
+
+    def on_start(self, otel_span, parent_context=None):
+        # type: (OTelSpan, Optional[context_api.Context]) -> None
+        client = get_client()
+
+        if not client.dsn:
+            return
+
+        try:
+            _ = Dsn(client.dsn)
+        except Exception:
+            return
+
+        if client.options["instrumenter"] != INSTRUMENTER.OTEL:
+            return
+
+        if not otel_span.get_span_context().is_valid:
+            return
+
+        if self._is_sentry_span(otel_span):
+            return
+
+        trace_data = self._get_trace_data(otel_span, parent_context)
+
+        parent_span_id = trace_data["parent_span_id"]
+        sentry_parent_span = (
+            self.otel_span_map.get(parent_span_id) if parent_span_id else None
+        )
+
+        start_timestamp = None
+        if otel_span.start_time is not None:
+            start_timestamp = datetime.fromtimestamp(
+                otel_span.start_time / 1e9, timezone.utc
+            )  # OTel spans have nanosecond precision
+
+        sentry_span = None
+        if sentry_parent_span:
+            sentry_span = sentry_parent_span.start_child(
+                span_id=trace_data["span_id"],
+                name=otel_span.name,
+                start_timestamp=start_timestamp,
+                instrumenter=INSTRUMENTER.OTEL,
+                origin=SPAN_ORIGIN,
+            )
+        else:
+            sentry_span = start_transaction(
+                name=otel_span.name,
+                span_id=trace_data["span_id"],
+                parent_span_id=parent_span_id,
+                trace_id=trace_data["trace_id"],
+                baggage=trace_data["baggage"],
+                start_timestamp=start_timestamp,
+                instrumenter=INSTRUMENTER.OTEL,
+                origin=SPAN_ORIGIN,
+            )
+
+        self.otel_span_map[trace_data["span_id"]] = sentry_span
+
+        if otel_span.start_time is not None:
+            span_start_in_minutes = int(
+                otel_span.start_time / 1e9 / 60
+            )  # OTel spans have nanosecond precision
+            self.open_spans.setdefault(span_start_in_minutes, set()).add(
+                trace_data["span_id"]
+            )
+
+        self._prune_old_spans()
+
+    def on_end(self, otel_span):
+        # type: (OTelSpan) -> None
+        client = get_client()
+
+        if client.options["instrumenter"] != INSTRUMENTER.OTEL:
+            return
+
+        span_context = otel_span.get_span_context()
+        if not span_context.is_valid:
+            return
+
+        span_id = format_span_id(span_context.span_id)
+        sentry_span = self.otel_span_map.pop(span_id, None)
+        if not sentry_span:
+            return
+
+        sentry_span.op = otel_span.name
+
+        self._update_span_with_otel_status(sentry_span, otel_span)
+
+        if isinstance(sentry_span, Transaction):
+            sentry_span.name = otel_span.name
+            sentry_span.set_context(
+                OPEN_TELEMETRY_CONTEXT, self._get_otel_context(otel_span)
+            )
+            self._update_transaction_with_otel_data(sentry_span, otel_span)
+
+        else:
+            self._update_span_with_otel_data(sentry_span, otel_span)
+
+        end_timestamp = None
+        if otel_span.end_time is not None:
+            end_timestamp = datetime.fromtimestamp(
+                otel_span.end_time / 1e9, timezone.utc
+            )  # OTel spans have nanosecond precision
+
+        sentry_span.finish(end_timestamp=end_timestamp)
+
+        if otel_span.start_time is not None:
+            span_start_in_minutes = int(
+                otel_span.start_time / 1e9 / 60
+            )  # OTel spans have nanosecond precision
+            self.open_spans.setdefault(span_start_in_minutes, set()).discard(span_id)
+
+        self._prune_old_spans()
+
+    def _is_sentry_span(self, otel_span):
+        # type: (OTelSpan) -> bool
+        """
+        Break infinite loop:
+        HTTP requests to Sentry are caught by OTel and send again to Sentry.
+        """
+        otel_span_url = None
+        if otel_span.attributes is not None:
+            otel_span_url = otel_span.attributes.get(SpanAttributes.HTTP_URL)
+        otel_span_url = cast("Optional[str]", otel_span_url)
+
+        dsn_url = None
+        client = get_client()
+        if client.dsn:
+            dsn_url = Dsn(client.dsn).netloc
+
+        if otel_span_url and dsn_url and dsn_url in otel_span_url:
+            return True
+
+        return False
+
+    def _get_otel_context(self, otel_span):
+        # type: (OTelSpan) -> dict[str, Any]
+        """
+        Returns the OTel context for Sentry.
+        See: https://develop.sentry.dev/sdk/performance/opentelemetry/#step-5-add-opentelemetry-context
+        """
+        ctx = {}
+
+        if otel_span.attributes:
+            ctx["attributes"] = dict(otel_span.attributes)
+
+        if otel_span.resource.attributes:
+            ctx["resource"] = dict(otel_span.resource.attributes)
+
+        return ctx
+
+    def _get_trace_data(self, otel_span, parent_context):
+        # type: (OTelSpan, Optional[context_api.Context]) -> dict[str, Any]
+        """
+        Extracts tracing information from one OTel span and its parent OTel context.
+        """
+        trace_data = {}  # type: dict[str, Any]
+        span_context = otel_span.get_span_context()
+
+        span_id = format_span_id(span_context.span_id)
+        trace_data["span_id"] = span_id
+
+        trace_id = format_trace_id(span_context.trace_id)
+        trace_data["trace_id"] = trace_id
+
+        parent_span_id = (
+            format_span_id(otel_span.parent.span_id) if otel_span.parent else None
+        )
+        trace_data["parent_span_id"] = parent_span_id
+
+        sentry_trace_data = get_value(SENTRY_TRACE_KEY, parent_context)
+        sentry_trace_data = cast("dict[str, Union[str, bool, None]]", sentry_trace_data)
+        trace_data["parent_sampled"] = (
+            sentry_trace_data["parent_sampled"] if sentry_trace_data else None
+        )
+
+        baggage = get_value(SENTRY_BAGGAGE_KEY, parent_context)
+        trace_data["baggage"] = baggage
+
+        return trace_data
+
+    def _update_span_with_otel_status(self, sentry_span, otel_span):
+        # type: (SentrySpan, OTelSpan) -> None
+        """
+        Set the Sentry span status from the OTel span
+        """
+        if otel_span.status.is_unset:
+            return
+
+        if otel_span.status.is_ok:
+            sentry_span.set_status(SPANSTATUS.OK)
+            return
+
+        sentry_span.set_status(SPANSTATUS.INTERNAL_ERROR)
+
+    def _update_span_with_otel_data(self, sentry_span, otel_span):
+        # type: (SentrySpan, OTelSpan) -> None
+        """
+        Convert OTel span data and update the Sentry span with it.
+        This should eventually happen on the server when ingesting the spans.
+        """
+        sentry_span.set_data("otel.kind", otel_span.kind)
+
+        op = otel_span.name
+        description = otel_span.name
+
+        if otel_span.attributes is not None:
+            for key, val in otel_span.attributes.items():
+                sentry_span.set_data(key, val)
+
+            http_method = otel_span.attributes.get(SpanAttributes.HTTP_METHOD)
+            http_method = cast("Optional[str]", http_method)
+
+            db_query = otel_span.attributes.get(SpanAttributes.DB_SYSTEM)
+
+            if http_method:
+                op = "http"
+
+                if otel_span.kind == SpanKind.SERVER:
+                    op += ".server"
+                elif otel_span.kind == SpanKind.CLIENT:
+                    op += ".client"
+
+                description = http_method
+
+                peer_name = otel_span.attributes.get(SpanAttributes.NET_PEER_NAME, None)
+                if peer_name:
+                    description += " {}".format(peer_name)
+
+                target = otel_span.attributes.get(SpanAttributes.HTTP_TARGET, None)
+                if target:
+                    description += " {}".format(target)
+
+                if not peer_name and not target:
+                    url = otel_span.attributes.get(SpanAttributes.HTTP_URL, None)
+                    url = cast("Optional[str]", url)
+                    if url:
+                        parsed_url = urlparse(url)
+                        url = "{}://{}{}".format(
+                            parsed_url.scheme, parsed_url.netloc, parsed_url.path
+                        )
+                        description += " {}".format(url)
+
+                status_code = otel_span.attributes.get(
+                    SpanAttributes.HTTP_STATUS_CODE, None
+                )
+                status_code = cast("Optional[int]", status_code)
+                if status_code:
+                    sentry_span.set_http_status(status_code)
+
+            elif db_query:
+                op = "db"
+                statement = otel_span.attributes.get(SpanAttributes.DB_STATEMENT, None)
+                statement = cast("Optional[str]", statement)
+                if statement:
+                    description = statement
+
+        sentry_span.op = op
+        sentry_span.description = description
+
+    def _update_transaction_with_otel_data(self, sentry_span, otel_span):
+        # type: (SentrySpan, OTelSpan) -> None
+        if otel_span.attributes is None:
+            return
+
+        http_method = otel_span.attributes.get(SpanAttributes.HTTP_METHOD)
+
+        if http_method:
+            status_code = otel_span.attributes.get(SpanAttributes.HTTP_STATUS_CODE)
+            status_code = cast("Optional[int]", status_code)
+            if status_code:
+                sentry_span.set_http_status(status_code)
+
+            op = "http"
+
+            if otel_span.kind == SpanKind.SERVER:
+                op += ".server"
+            elif otel_span.kind == SpanKind.CLIENT:
+                op += ".client"
+
+            sentry_span.op = op
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/pure_eval.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/pure_eval.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1c3d63871014af917e12a46638f106bafce0a95
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/pure_eval.py
@@ -0,0 +1,139 @@
+import ast
+
+import sentry_sdk
+from sentry_sdk import serializer
+from sentry_sdk.integrations import Integration, DidNotEnable
+from sentry_sdk.scope import add_global_event_processor
+from sentry_sdk.utils import walk_exception_chain, iter_stacks
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Optional, Dict, Any, Tuple, List
+    from types import FrameType
+
+    from sentry_sdk._types import Event, Hint
+
+try:
+    import executing
+except ImportError:
+    raise DidNotEnable("executing is not installed")
+
+try:
+    import pure_eval
+except ImportError:
+    raise DidNotEnable("pure_eval is not installed")
+
+try:
+    # Used implicitly, just testing it's available
+    import asttokens  # noqa
+except ImportError:
+    raise DidNotEnable("asttokens is not installed")
+
+
+class PureEvalIntegration(Integration):
+    identifier = "pure_eval"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+
+        @add_global_event_processor
+        def add_executing_info(event, hint):
+            # type: (Event, Optional[Hint]) -> Optional[Event]
+            if sentry_sdk.get_client().get_integration(PureEvalIntegration) is None:
+                return event
+
+            if hint is None:
+                return event
+
+            exc_info = hint.get("exc_info", None)
+
+            if exc_info is None:
+                return event
+
+            exception = event.get("exception", None)
+
+            if exception is None:
+                return event
+
+            values = exception.get("values", None)
+
+            if values is None:
+                return event
+
+            for exception, (_exc_type, _exc_value, exc_tb) in zip(
+                reversed(values), walk_exception_chain(exc_info)
+            ):
+                sentry_frames = [
+                    frame
+                    for frame in exception.get("stacktrace", {}).get("frames", [])
+                    if frame.get("function")
+                ]
+                tbs = list(iter_stacks(exc_tb))
+                if len(sentry_frames) != len(tbs):
+                    continue
+
+                for sentry_frame, tb in zip(sentry_frames, tbs):
+                    sentry_frame["vars"] = (
+                        pure_eval_frame(tb.tb_frame) or sentry_frame["vars"]
+                    )
+            return event
+
+
+def pure_eval_frame(frame):
+    # type: (FrameType) -> Dict[str, Any]
+    source = executing.Source.for_frame(frame)
+    if not source.tree:
+        return {}
+
+    statements = source.statements_at_line(frame.f_lineno)
+    if not statements:
+        return {}
+
+    scope = stmt = list(statements)[0]
+    while True:
+        # Get the parent first in case the original statement is already
+        # a function definition, e.g. if we're calling a decorator
+        # In that case we still want the surrounding scope, not that function
+        scope = scope.parent
+        if isinstance(scope, (ast.FunctionDef, ast.ClassDef, ast.Module)):
+            break
+
+    evaluator = pure_eval.Evaluator.from_frame(frame)
+    expressions = evaluator.interesting_expressions_grouped(scope)
+
+    def closeness(expression):
+        # type: (Tuple[List[Any], Any]) -> Tuple[int, int]
+        # Prioritise expressions with a node closer to the statement executed
+        # without being after that statement
+        # A higher return value is better - the expression will appear
+        # earlier in the list of values and is less likely to be trimmed
+        nodes, _value = expression
+
+        def start(n):
+            # type: (ast.expr) -> Tuple[int, int]
+            return (n.lineno, n.col_offset)
+
+        nodes_before_stmt = [
+            node for node in nodes if start(node) < stmt.last_token.end  # type: ignore
+        ]
+        if nodes_before_stmt:
+            # The position of the last node before or in the statement
+            return max(start(node) for node in nodes_before_stmt)
+        else:
+            # The position of the first node after the statement
+            # Negative means it's always lower priority than nodes that come before
+            # Less negative means closer to the statement and higher priority
+            lineno, col_offset = min(start(node) for node in nodes)
+            return (-lineno, -col_offset)
+
+    # This adds the first_token and last_token attributes to nodes
+    atok = source.asttokens()
+
+    expressions.sort(key=closeness, reverse=True)
+    vars = {
+        atok.get_text(nodes[0]): value
+        for nodes, value in expressions[: serializer.MAX_DATABAG_BREADTH]
+    }
+    return serializer.serialize(vars, is_vars=True)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/pymongo.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/pymongo.py
new file mode 100644
index 0000000000000000000000000000000000000000..f65ad7368778d4f0dc2af63522bbfede807f2f97
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/pymongo.py
@@ -0,0 +1,214 @@
+import copy
+import json
+
+import sentry_sdk
+from sentry_sdk.consts import SPANSTATUS, SPANDATA, OP
+from sentry_sdk.integrations import DidNotEnable, Integration
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.tracing import Span
+from sentry_sdk.utils import capture_internal_exceptions
+
+try:
+    from pymongo import monitoring
+except ImportError:
+    raise DidNotEnable("Pymongo not installed")
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Dict, Union
+
+    from pymongo.monitoring import (
+        CommandFailedEvent,
+        CommandStartedEvent,
+        CommandSucceededEvent,
+    )
+
+
+SAFE_COMMAND_ATTRIBUTES = [
+    "insert",
+    "ordered",
+    "find",
+    "limit",
+    "singleBatch",
+    "aggregate",
+    "createIndexes",
+    "indexes",
+    "delete",
+    "findAndModify",
+    "renameCollection",
+    "to",
+    "drop",
+]
+
+
+def _strip_pii(command):
+    # type: (Dict[str, Any]) -> Dict[str, Any]
+    for key in command:
+        is_safe_field = key in SAFE_COMMAND_ATTRIBUTES
+        if is_safe_field:
+            # Skip if safe key
+            continue
+
+        update_db_command = key == "update" and "findAndModify" not in command
+        if update_db_command:
+            # Also skip "update" db command because it is save.
+            # There is also an "update" key in the "findAndModify" command, which is NOT safe!
+            continue
+
+        # Special stripping for documents
+        is_document = key == "documents"
+        if is_document:
+            for doc in command[key]:
+                for doc_key in doc:
+                    doc[doc_key] = "%s"
+            continue
+
+        # Special stripping for dict style fields
+        is_dict_field = key in ["filter", "query", "update"]
+        if is_dict_field:
+            for item_key in command[key]:
+                command[key][item_key] = "%s"
+            continue
+
+        # For pipeline fields strip the `$match` dict
+        is_pipeline_field = key == "pipeline"
+        if is_pipeline_field:
+            for pipeline in command[key]:
+                for match_key in pipeline["$match"] if "$match" in pipeline else []:
+                    pipeline["$match"][match_key] = "%s"
+            continue
+
+        # Default stripping
+        command[key] = "%s"
+
+    return command
+
+
+def _get_db_data(event):
+    # type: (Any) -> Dict[str, Any]
+    data = {}
+
+    data[SPANDATA.DB_SYSTEM] = "mongodb"
+
+    db_name = event.database_name
+    if db_name is not None:
+        data[SPANDATA.DB_NAME] = db_name
+
+    server_address = event.connection_id[0]
+    if server_address is not None:
+        data[SPANDATA.SERVER_ADDRESS] = server_address
+
+    server_port = event.connection_id[1]
+    if server_port is not None:
+        data[SPANDATA.SERVER_PORT] = server_port
+
+    return data
+
+
+class CommandTracer(monitoring.CommandListener):
+    def __init__(self):
+        # type: () -> None
+        self._ongoing_operations = {}  # type: Dict[int, Span]
+
+    def _operation_key(self, event):
+        # type: (Union[CommandFailedEvent, CommandStartedEvent, CommandSucceededEvent]) -> int
+        return event.request_id
+
+    def started(self, event):
+        # type: (CommandStartedEvent) -> None
+        if sentry_sdk.get_client().get_integration(PyMongoIntegration) is None:
+            return
+
+        with capture_internal_exceptions():
+            command = dict(copy.deepcopy(event.command))
+
+            command.pop("$db", None)
+            command.pop("$clusterTime", None)
+            command.pop("$signature", None)
+
+            tags = {
+                "db.name": event.database_name,
+                SPANDATA.DB_SYSTEM: "mongodb",
+                SPANDATA.DB_OPERATION: event.command_name,
+                SPANDATA.DB_MONGODB_COLLECTION: command.get(event.command_name),
+            }
+
+            try:
+                tags["net.peer.name"] = event.connection_id[0]
+                tags["net.peer.port"] = str(event.connection_id[1])
+            except TypeError:
+                pass
+
+            data = {"operation_ids": {}}  # type: Dict[str, Any]
+            data["operation_ids"]["operation"] = event.operation_id
+            data["operation_ids"]["request"] = event.request_id
+
+            data.update(_get_db_data(event))
+
+            try:
+                lsid = command.pop("lsid")["id"]
+                data["operation_ids"]["session"] = str(lsid)
+            except KeyError:
+                pass
+
+            if not should_send_default_pii():
+                command = _strip_pii(command)
+
+            query = json.dumps(command, default=str)
+            span = sentry_sdk.start_span(
+                op=OP.DB,
+                name=query,
+                origin=PyMongoIntegration.origin,
+            )
+
+            for tag, value in tags.items():
+                # set the tag for backwards-compatibility.
+                # TODO: remove the set_tag call in the next major release!
+                span.set_tag(tag, value)
+
+                span.set_data(tag, value)
+
+            for key, value in data.items():
+                span.set_data(key, value)
+
+            with capture_internal_exceptions():
+                sentry_sdk.add_breadcrumb(
+                    message=query, category="query", type=OP.DB, data=tags
+                )
+
+            self._ongoing_operations[self._operation_key(event)] = span.__enter__()
+
+    def failed(self, event):
+        # type: (CommandFailedEvent) -> None
+        if sentry_sdk.get_client().get_integration(PyMongoIntegration) is None:
+            return
+
+        try:
+            span = self._ongoing_operations.pop(self._operation_key(event))
+            span.set_status(SPANSTATUS.INTERNAL_ERROR)
+            span.__exit__(None, None, None)
+        except KeyError:
+            return
+
+    def succeeded(self, event):
+        # type: (CommandSucceededEvent) -> None
+        if sentry_sdk.get_client().get_integration(PyMongoIntegration) is None:
+            return
+
+        try:
+            span = self._ongoing_operations.pop(self._operation_key(event))
+            span.set_status(SPANSTATUS.OK)
+            span.__exit__(None, None, None)
+        except KeyError:
+            pass
+
+
+class PyMongoIntegration(Integration):
+    identifier = "pymongo"
+    origin = f"auto.db.{identifier}"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        monitoring.register(CommandTracer())
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/pyramid.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/pyramid.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1475ada65ce0c374315dc9f87f55e3434baee22
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/pyramid.py
@@ -0,0 +1,229 @@
+import functools
+import os
+import sys
+import weakref
+
+import sentry_sdk
+from sentry_sdk.integrations import Integration, DidNotEnable
+from sentry_sdk.integrations._wsgi_common import RequestExtractor
+from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.tracing import SOURCE_FOR_STYLE
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    event_from_exception,
+    reraise,
+)
+
+try:
+    from pyramid.httpexceptions import HTTPException
+    from pyramid.request import Request
+except ImportError:
+    raise DidNotEnable("Pyramid not installed")
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from pyramid.response import Response
+    from typing import Any
+    from sentry_sdk.integrations.wsgi import _ScopedResponse
+    from typing import Callable
+    from typing import Dict
+    from typing import Optional
+    from webob.cookies import RequestCookies
+    from webob.request import _FieldStorageWithFile
+
+    from sentry_sdk.utils import ExcInfo
+    from sentry_sdk._types import Event, EventProcessor
+
+
+if getattr(Request, "authenticated_userid", None):
+
+    def authenticated_userid(request):
+        # type: (Request) -> Optional[Any]
+        return request.authenticated_userid
+
+else:
+    # bw-compat for pyramid < 1.5
+    from pyramid.security import authenticated_userid  # type: ignore
+
+
+TRANSACTION_STYLE_VALUES = ("route_name", "route_pattern")
+
+
+class PyramidIntegration(Integration):
+    identifier = "pyramid"
+    origin = f"auto.http.{identifier}"
+
+    transaction_style = ""
+
+    def __init__(self, transaction_style="route_name"):
+        # type: (str) -> None
+        if transaction_style not in TRANSACTION_STYLE_VALUES:
+            raise ValueError(
+                "Invalid value for transaction_style: %s (must be in %s)"
+                % (transaction_style, TRANSACTION_STYLE_VALUES)
+            )
+        self.transaction_style = transaction_style
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        from pyramid import router
+
+        old_call_view = router._call_view
+
+        @functools.wraps(old_call_view)
+        def sentry_patched_call_view(registry, request, *args, **kwargs):
+            # type: (Any, Request, *Any, **Any) -> Response
+            integration = sentry_sdk.get_client().get_integration(PyramidIntegration)
+            if integration is None:
+                return old_call_view(registry, request, *args, **kwargs)
+
+            _set_transaction_name_and_source(
+                sentry_sdk.get_current_scope(), integration.transaction_style, request
+            )
+            scope = sentry_sdk.get_isolation_scope()
+            scope.add_event_processor(
+                _make_event_processor(weakref.ref(request), integration)
+            )
+
+            return old_call_view(registry, request, *args, **kwargs)
+
+        router._call_view = sentry_patched_call_view
+
+        if hasattr(Request, "invoke_exception_view"):
+            old_invoke_exception_view = Request.invoke_exception_view
+
+            def sentry_patched_invoke_exception_view(self, *args, **kwargs):
+                # type: (Request, *Any, **Any) -> Any
+                rv = old_invoke_exception_view(self, *args, **kwargs)
+
+                if (
+                    self.exc_info
+                    and all(self.exc_info)
+                    and rv.status_int == 500
+                    and sentry_sdk.get_client().get_integration(PyramidIntegration)
+                    is not None
+                ):
+                    _capture_exception(self.exc_info)
+
+                return rv
+
+            Request.invoke_exception_view = sentry_patched_invoke_exception_view
+
+        old_wsgi_call = router.Router.__call__
+
+        @ensure_integration_enabled(PyramidIntegration, old_wsgi_call)
+        def sentry_patched_wsgi_call(self, environ, start_response):
+            # type: (Any, Dict[str, str], Callable[..., Any]) -> _ScopedResponse
+            def sentry_patched_inner_wsgi_call(environ, start_response):
+                # type: (Dict[str, Any], Callable[..., Any]) -> Any
+                try:
+                    return old_wsgi_call(self, environ, start_response)
+                except Exception:
+                    einfo = sys.exc_info()
+                    _capture_exception(einfo)
+                    reraise(*einfo)
+
+            middleware = SentryWsgiMiddleware(
+                sentry_patched_inner_wsgi_call,
+                span_origin=PyramidIntegration.origin,
+            )
+            return middleware(environ, start_response)
+
+        router.Router.__call__ = sentry_patched_wsgi_call
+
+
+@ensure_integration_enabled(PyramidIntegration)
+def _capture_exception(exc_info):
+    # type: (ExcInfo) -> None
+    if exc_info[0] is None or issubclass(exc_info[0], HTTPException):
+        return
+
+    event, hint = event_from_exception(
+        exc_info,
+        client_options=sentry_sdk.get_client().options,
+        mechanism={"type": "pyramid", "handled": False},
+    )
+
+    sentry_sdk.capture_event(event, hint=hint)
+
+
+def _set_transaction_name_and_source(scope, transaction_style, request):
+    # type: (sentry_sdk.Scope, str, Request) -> None
+    try:
+        name_for_style = {
+            "route_name": request.matched_route.name,
+            "route_pattern": request.matched_route.pattern,
+        }
+        scope.set_transaction_name(
+            name_for_style[transaction_style],
+            source=SOURCE_FOR_STYLE[transaction_style],
+        )
+    except Exception:
+        pass
+
+
+class PyramidRequestExtractor(RequestExtractor):
+    def url(self):
+        # type: () -> str
+        return self.request.path_url
+
+    def env(self):
+        # type: () -> Dict[str, str]
+        return self.request.environ
+
+    def cookies(self):
+        # type: () -> RequestCookies
+        return self.request.cookies
+
+    def raw_data(self):
+        # type: () -> str
+        return self.request.text
+
+    def form(self):
+        # type: () -> Dict[str, str]
+        return {
+            key: value
+            for key, value in self.request.POST.items()
+            if not getattr(value, "filename", None)
+        }
+
+    def files(self):
+        # type: () -> Dict[str, _FieldStorageWithFile]
+        return {
+            key: value
+            for key, value in self.request.POST.items()
+            if getattr(value, "filename", None)
+        }
+
+    def size_of_file(self, postdata):
+        # type: (_FieldStorageWithFile) -> int
+        file = postdata.file
+        try:
+            return os.fstat(file.fileno()).st_size
+        except Exception:
+            return 0
+
+
+def _make_event_processor(weak_request, integration):
+    # type: (Callable[[], Request], PyramidIntegration) -> EventProcessor
+    def pyramid_event_processor(event, hint):
+        # type: (Event, Dict[str, Any]) -> Event
+        request = weak_request()
+        if request is None:
+            return event
+
+        with capture_internal_exceptions():
+            PyramidRequestExtractor(request).extract_into_event(event)
+
+        if should_send_default_pii():
+            with capture_internal_exceptions():
+                user_info = event.setdefault("user", {})
+                user_info.setdefault("id", authenticated_userid(request))
+
+        return event
+
+    return pyramid_event_processor
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/quart.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/quart.py
new file mode 100644
index 0000000000000000000000000000000000000000..64f7e0bcd26a7f7c6ce42313352c03a75feecaed
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/quart.py
@@ -0,0 +1,237 @@
+import asyncio
+import inspect
+from functools import wraps
+
+import sentry_sdk
+from sentry_sdk.integrations import DidNotEnable, Integration
+from sentry_sdk.integrations._wsgi_common import _filter_headers
+from sentry_sdk.integrations.asgi import SentryAsgiMiddleware
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.tracing import SOURCE_FOR_STYLE
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    event_from_exception,
+)
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Union
+
+    from sentry_sdk._types import Event, EventProcessor
+
+try:
+    import quart_auth  # type: ignore
+except ImportError:
+    quart_auth = None
+
+try:
+    from quart import (  # type: ignore
+        has_request_context,
+        has_websocket_context,
+        Request,
+        Quart,
+        request,
+        websocket,
+    )
+    from quart.signals import (  # type: ignore
+        got_background_exception,
+        got_request_exception,
+        got_websocket_exception,
+        request_started,
+        websocket_started,
+    )
+except ImportError:
+    raise DidNotEnable("Quart is not installed")
+else:
+    # Quart 0.19 is based on Flask and hence no longer has a Scaffold
+    try:
+        from quart.scaffold import Scaffold  # type: ignore
+    except ImportError:
+        from flask.sansio.scaffold import Scaffold  # type: ignore
+
+TRANSACTION_STYLE_VALUES = ("endpoint", "url")
+
+
+class QuartIntegration(Integration):
+    identifier = "quart"
+    origin = f"auto.http.{identifier}"
+
+    transaction_style = ""
+
+    def __init__(self, transaction_style="endpoint"):
+        # type: (str) -> None
+        if transaction_style not in TRANSACTION_STYLE_VALUES:
+            raise ValueError(
+                "Invalid value for transaction_style: %s (must be in %s)"
+                % (transaction_style, TRANSACTION_STYLE_VALUES)
+            )
+        self.transaction_style = transaction_style
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+
+        request_started.connect(_request_websocket_started)
+        websocket_started.connect(_request_websocket_started)
+        got_background_exception.connect(_capture_exception)
+        got_request_exception.connect(_capture_exception)
+        got_websocket_exception.connect(_capture_exception)
+
+        patch_asgi_app()
+        patch_scaffold_route()
+
+
+def patch_asgi_app():
+    # type: () -> None
+    old_app = Quart.__call__
+
+    async def sentry_patched_asgi_app(self, scope, receive, send):
+        # type: (Any, Any, Any, Any) -> Any
+        if sentry_sdk.get_client().get_integration(QuartIntegration) is None:
+            return await old_app(self, scope, receive, send)
+
+        middleware = SentryAsgiMiddleware(
+            lambda *a, **kw: old_app(self, *a, **kw),
+            span_origin=QuartIntegration.origin,
+            asgi_version=3,
+        )
+        return await middleware(scope, receive, send)
+
+    Quart.__call__ = sentry_patched_asgi_app
+
+
+def patch_scaffold_route():
+    # type: () -> None
+    old_route = Scaffold.route
+
+    def _sentry_route(*args, **kwargs):
+        # type: (*Any, **Any) -> Any
+        old_decorator = old_route(*args, **kwargs)
+
+        def decorator(old_func):
+            # type: (Any) -> Any
+
+            if inspect.isfunction(old_func) and not asyncio.iscoroutinefunction(
+                old_func
+            ):
+
+                @wraps(old_func)
+                @ensure_integration_enabled(QuartIntegration, old_func)
+                def _sentry_func(*args, **kwargs):
+                    # type: (*Any, **Any) -> Any
+                    current_scope = sentry_sdk.get_current_scope()
+                    if current_scope.transaction is not None:
+                        current_scope.transaction.update_active_thread()
+
+                    sentry_scope = sentry_sdk.get_isolation_scope()
+                    if sentry_scope.profile is not None:
+                        sentry_scope.profile.update_active_thread_id()
+
+                    return old_func(*args, **kwargs)
+
+                return old_decorator(_sentry_func)
+
+            return old_decorator(old_func)
+
+        return decorator
+
+    Scaffold.route = _sentry_route
+
+
+def _set_transaction_name_and_source(scope, transaction_style, request):
+    # type: (sentry_sdk.Scope, str, Request) -> None
+
+    try:
+        name_for_style = {
+            "url": request.url_rule.rule,
+            "endpoint": request.url_rule.endpoint,
+        }
+        scope.set_transaction_name(
+            name_for_style[transaction_style],
+            source=SOURCE_FOR_STYLE[transaction_style],
+        )
+    except Exception:
+        pass
+
+
+async def _request_websocket_started(app, **kwargs):
+    # type: (Quart, **Any) -> None
+    integration = sentry_sdk.get_client().get_integration(QuartIntegration)
+    if integration is None:
+        return
+
+    if has_request_context():
+        request_websocket = request._get_current_object()
+    if has_websocket_context():
+        request_websocket = websocket._get_current_object()
+
+    # Set the transaction name here, but rely on ASGI middleware
+    # to actually start the transaction
+    _set_transaction_name_and_source(
+        sentry_sdk.get_current_scope(), integration.transaction_style, request_websocket
+    )
+
+    scope = sentry_sdk.get_isolation_scope()
+    evt_processor = _make_request_event_processor(app, request_websocket, integration)
+    scope.add_event_processor(evt_processor)
+
+
+def _make_request_event_processor(app, request, integration):
+    # type: (Quart, Request, QuartIntegration) -> EventProcessor
+    def inner(event, hint):
+        # type: (Event, dict[str, Any]) -> Event
+        # if the request is gone we are fine not logging the data from
+        # it.  This might happen if the processor is pushed away to
+        # another thread.
+        if request is None:
+            return event
+
+        with capture_internal_exceptions():
+            # TODO: Figure out what to do with request body. Methods on request
+            # are async, but event processors are not.
+
+            request_info = event.setdefault("request", {})
+            request_info["url"] = request.url
+            request_info["query_string"] = request.query_string
+            request_info["method"] = request.method
+            request_info["headers"] = _filter_headers(dict(request.headers))
+
+            if should_send_default_pii():
+                request_info["env"] = {"REMOTE_ADDR": request.access_route[0]}
+                _add_user_to_event(event)
+
+        return event
+
+    return inner
+
+
+async def _capture_exception(sender, exception, **kwargs):
+    # type: (Quart, Union[ValueError, BaseException], **Any) -> None
+    integration = sentry_sdk.get_client().get_integration(QuartIntegration)
+    if integration is None:
+        return
+
+    event, hint = event_from_exception(
+        exception,
+        client_options=sentry_sdk.get_client().options,
+        mechanism={"type": "quart", "handled": False},
+    )
+
+    sentry_sdk.capture_event(event, hint=hint)
+
+
+def _add_user_to_event(event):
+    # type: (Event) -> None
+    if quart_auth is None:
+        return
+
+    user = quart_auth.current_user
+    if user is None:
+        return
+
+    with capture_internal_exceptions():
+        user_info = event.setdefault("user", {})
+
+        user_info["id"] = quart_auth.current_user._auth_id
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/ray.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/ray.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d6cdc1201e0042695d7847202a80c77cb05012e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/ray.py
@@ -0,0 +1,149 @@
+import inspect
+import sys
+
+import sentry_sdk
+from sentry_sdk.consts import OP, SPANSTATUS
+from sentry_sdk.integrations import _check_minimum_version, DidNotEnable, Integration
+from sentry_sdk.tracing import TransactionSource
+from sentry_sdk.utils import (
+    event_from_exception,
+    logger,
+    package_version,
+    qualname_from_function,
+    reraise,
+)
+
+try:
+    import ray  # type: ignore[import-not-found]
+except ImportError:
+    raise DidNotEnable("Ray not installed.")
+import functools
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from collections.abc import Callable
+    from typing import Any, Optional
+    from sentry_sdk.utils import ExcInfo
+
+
+def _check_sentry_initialized():
+    # type: () -> None
+    if sentry_sdk.get_client().is_active():
+        return
+
+    logger.debug(
+        "[Tracing] Sentry not initialized in ray cluster worker, performance data will be discarded."
+    )
+
+
+def _patch_ray_remote():
+    # type: () -> None
+    old_remote = ray.remote
+
+    @functools.wraps(old_remote)
+    def new_remote(f=None, *args, **kwargs):
+        # type: (Optional[Callable[..., Any]], *Any, **Any) -> Callable[..., Any]
+
+        if inspect.isclass(f):
+            # Ray Actors
+            # (https://docs.ray.io/en/latest/ray-core/actors.html)
+            # are not supported
+            # (Only Ray Tasks are supported)
+            return old_remote(f, *args, **kwargs)
+
+        def wrapper(user_f):
+            # type: (Callable[..., Any]) -> Any
+            def new_func(*f_args, _tracing=None, **f_kwargs):
+                # type: (Any, Optional[dict[str, Any]], Any) -> Any
+                _check_sentry_initialized()
+
+                transaction = sentry_sdk.continue_trace(
+                    _tracing or {},
+                    op=OP.QUEUE_TASK_RAY,
+                    name=qualname_from_function(user_f),
+                    origin=RayIntegration.origin,
+                    source=TransactionSource.TASK,
+                )
+
+                with sentry_sdk.start_transaction(transaction) as transaction:
+                    try:
+                        result = user_f(*f_args, **f_kwargs)
+                        transaction.set_status(SPANSTATUS.OK)
+                    except Exception:
+                        transaction.set_status(SPANSTATUS.INTERNAL_ERROR)
+                        exc_info = sys.exc_info()
+                        _capture_exception(exc_info)
+                        reraise(*exc_info)
+
+                    return result
+
+            if f:
+                rv = old_remote(new_func)
+            else:
+                rv = old_remote(*args, **kwargs)(new_func)
+            old_remote_method = rv.remote
+
+            def _remote_method_with_header_propagation(*args, **kwargs):
+                # type: (*Any, **Any) -> Any
+                """
+                Ray Client
+                """
+                with sentry_sdk.start_span(
+                    op=OP.QUEUE_SUBMIT_RAY,
+                    name=qualname_from_function(user_f),
+                    origin=RayIntegration.origin,
+                ) as span:
+                    tracing = {
+                        k: v
+                        for k, v in sentry_sdk.get_current_scope().iter_trace_propagation_headers()
+                    }
+                    try:
+                        result = old_remote_method(*args, **kwargs, _tracing=tracing)
+                        span.set_status(SPANSTATUS.OK)
+                    except Exception:
+                        span.set_status(SPANSTATUS.INTERNAL_ERROR)
+                        exc_info = sys.exc_info()
+                        _capture_exception(exc_info)
+                        reraise(*exc_info)
+
+                    return result
+
+            rv.remote = _remote_method_with_header_propagation
+
+            return rv
+
+        if f is not None:
+            return wrapper(f)
+        else:
+            return wrapper
+
+    ray.remote = new_remote
+
+
+def _capture_exception(exc_info, **kwargs):
+    # type: (ExcInfo, **Any) -> None
+    client = sentry_sdk.get_client()
+
+    event, hint = event_from_exception(
+        exc_info,
+        client_options=client.options,
+        mechanism={
+            "handled": False,
+            "type": RayIntegration.identifier,
+        },
+    )
+    sentry_sdk.capture_event(event, hint=hint)
+
+
+class RayIntegration(Integration):
+    identifier = "ray"
+    origin = f"auto.queue.{identifier}"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        version = package_version("ray")
+        _check_minimum_version(RayIntegration, version)
+
+        _patch_ray_remote()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4431382953bbf617aca1fec9e8ac43141fc8335
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__init__.py
@@ -0,0 +1,38 @@
+from sentry_sdk.integrations import Integration, DidNotEnable
+from sentry_sdk.integrations.redis.consts import _DEFAULT_MAX_DATA_SIZE
+from sentry_sdk.integrations.redis.rb import _patch_rb
+from sentry_sdk.integrations.redis.redis import _patch_redis
+from sentry_sdk.integrations.redis.redis_cluster import _patch_redis_cluster
+from sentry_sdk.integrations.redis.redis_py_cluster_legacy import _patch_rediscluster
+from sentry_sdk.utils import logger
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Optional
+
+
+class RedisIntegration(Integration):
+    identifier = "redis"
+
+    def __init__(self, max_data_size=_DEFAULT_MAX_DATA_SIZE, cache_prefixes=None):
+        # type: (int, Optional[list[str]]) -> None
+        self.max_data_size = max_data_size
+        self.cache_prefixes = cache_prefixes if cache_prefixes is not None else []
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        try:
+            from redis import StrictRedis, client
+        except ImportError:
+            raise DidNotEnable("Redis client not installed")
+
+        _patch_redis(StrictRedis, client)
+        _patch_redis_cluster()
+        _patch_rb()
+
+        try:
+            _patch_rediscluster()
+        except Exception:
+            logger.exception("Error occurred while patching `rediscluster` library")
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b20a080be86e69338635e2f0a0d2e6404f1b1d26
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/_async_common.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/_async_common.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9de7d545e20e0e535fe92412e23eed711bcffcc6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/_async_common.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/_sync_common.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/_sync_common.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..436762d83f6edbb68071234077eded8126c49ebe
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/_sync_common.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/consts.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/consts.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a968f5d83b194333c0ee8830a91809e0c5374e16
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/consts.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/rb.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/rb.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9f0297405fa66c3cada2f253e9c4776337518aea
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/rb.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/redis.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/redis.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9b228b98160bf6acda9577add697a8773c3c8e2c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/redis.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/redis_cluster.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/redis_cluster.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6704b75b82d4f481441ffc03c029a99e1df1d03b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/redis_cluster.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/redis_py_cluster_legacy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/redis_py_cluster_legacy.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..275417a43c6aa6401a57383d151dcff9394b64a9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/redis_py_cluster_legacy.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..972322c2731a387f9393118016f6634dfdeefcbd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/__pycache__/utils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/_async_common.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/_async_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..b96986fba3b8eca37daba340fdad8ec1b4466f86
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/_async_common.py
@@ -0,0 +1,116 @@
+import sentry_sdk
+from sentry_sdk.consts import OP
+from sentry_sdk.integrations.redis.consts import SPAN_ORIGIN
+from sentry_sdk.integrations.redis.modules.caches import (
+    _compile_cache_span_properties,
+    _set_cache_data,
+)
+from sentry_sdk.integrations.redis.modules.queries import _compile_db_span_properties
+from sentry_sdk.integrations.redis.utils import (
+    _set_client_data,
+    _set_pipeline_data,
+)
+from sentry_sdk.tracing import Span
+from sentry_sdk.utils import capture_internal_exceptions
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from collections.abc import Callable
+    from typing import Any, Union
+    from redis.asyncio.client import Pipeline, StrictRedis
+    from redis.asyncio.cluster import ClusterPipeline, RedisCluster
+
+
+def patch_redis_async_pipeline(
+    pipeline_cls, is_cluster, get_command_args_fn, set_db_data_fn
+):
+    # type: (Union[type[Pipeline[Any]], type[ClusterPipeline[Any]]], bool, Any, Callable[[Span, Any], None]) -> None
+    old_execute = pipeline_cls.execute
+
+    from sentry_sdk.integrations.redis import RedisIntegration
+
+    async def _sentry_execute(self, *args, **kwargs):
+        # type: (Any, *Any, **Any) -> Any
+        if sentry_sdk.get_client().get_integration(RedisIntegration) is None:
+            return await old_execute(self, *args, **kwargs)
+
+        with sentry_sdk.start_span(
+            op=OP.DB_REDIS,
+            name="redis.pipeline.execute",
+            origin=SPAN_ORIGIN,
+        ) as span:
+            with capture_internal_exceptions():
+                try:
+                    command_seq = self._execution_strategy._command_queue
+                except AttributeError:
+                    if is_cluster:
+                        command_seq = self._command_stack
+                    else:
+                        command_seq = self.command_stack
+
+                set_db_data_fn(span, self)
+                _set_pipeline_data(
+                    span,
+                    is_cluster,
+                    get_command_args_fn,
+                    False if is_cluster else self.is_transaction,
+                    command_seq,
+                )
+
+            return await old_execute(self, *args, **kwargs)
+
+    pipeline_cls.execute = _sentry_execute  # type: ignore
+
+
+def patch_redis_async_client(cls, is_cluster, set_db_data_fn):
+    # type: (Union[type[StrictRedis[Any]], type[RedisCluster[Any]]], bool, Callable[[Span, Any], None]) -> None
+    old_execute_command = cls.execute_command
+
+    from sentry_sdk.integrations.redis import RedisIntegration
+
+    async def _sentry_execute_command(self, name, *args, **kwargs):
+        # type: (Any, str, *Any, **Any) -> Any
+        integration = sentry_sdk.get_client().get_integration(RedisIntegration)
+        if integration is None:
+            return await old_execute_command(self, name, *args, **kwargs)
+
+        cache_properties = _compile_cache_span_properties(
+            name,
+            args,
+            kwargs,
+            integration,
+        )
+
+        cache_span = None
+        if cache_properties["is_cache_key"] and cache_properties["op"] is not None:
+            cache_span = sentry_sdk.start_span(
+                op=cache_properties["op"],
+                name=cache_properties["description"],
+                origin=SPAN_ORIGIN,
+            )
+            cache_span.__enter__()
+
+        db_properties = _compile_db_span_properties(integration, name, args)
+
+        db_span = sentry_sdk.start_span(
+            op=db_properties["op"],
+            name=db_properties["description"],
+            origin=SPAN_ORIGIN,
+        )
+        db_span.__enter__()
+
+        set_db_data_fn(db_span, self)
+        _set_client_data(db_span, is_cluster, name, *args)
+
+        value = await old_execute_command(self, name, *args, **kwargs)
+
+        db_span.__exit__(None, None, None)
+
+        if cache_span:
+            _set_cache_data(cache_span, self, cache_properties, value)
+            cache_span.__exit__(None, None, None)
+
+        return value
+
+    cls.execute_command = _sentry_execute_command  # type: ignore
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/_sync_common.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/_sync_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..72f3eb7778a90dbcddf69dc21dddfcfac7db65b2
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/_sync_common.py
@@ -0,0 +1,119 @@
+import sentry_sdk
+from sentry_sdk.consts import OP
+from sentry_sdk.integrations.redis.consts import SPAN_ORIGIN
+from sentry_sdk.integrations.redis.modules.caches import (
+    _compile_cache_span_properties,
+    _set_cache_data,
+)
+from sentry_sdk.integrations.redis.modules.queries import _compile_db_span_properties
+from sentry_sdk.integrations.redis.utils import (
+    _set_client_data,
+    _set_pipeline_data,
+)
+from sentry_sdk.tracing import Span
+from sentry_sdk.utils import capture_internal_exceptions
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from collections.abc import Callable
+    from typing import Any
+
+
+def patch_redis_pipeline(
+    pipeline_cls,
+    is_cluster,
+    get_command_args_fn,
+    set_db_data_fn,
+):
+    # type: (Any, bool, Any, Callable[[Span, Any], None]) -> None
+    old_execute = pipeline_cls.execute
+
+    from sentry_sdk.integrations.redis import RedisIntegration
+
+    def sentry_patched_execute(self, *args, **kwargs):
+        # type: (Any, *Any, **Any) -> Any
+        if sentry_sdk.get_client().get_integration(RedisIntegration) is None:
+            return old_execute(self, *args, **kwargs)
+
+        with sentry_sdk.start_span(
+            op=OP.DB_REDIS,
+            name="redis.pipeline.execute",
+            origin=SPAN_ORIGIN,
+        ) as span:
+            with capture_internal_exceptions():
+                command_seq = None
+                try:
+                    command_seq = self._execution_strategy.command_queue
+                except AttributeError:
+                    command_seq = self.command_stack
+
+                set_db_data_fn(span, self)
+                _set_pipeline_data(
+                    span,
+                    is_cluster,
+                    get_command_args_fn,
+                    False if is_cluster else self.transaction,
+                    command_seq,
+                )
+
+            return old_execute(self, *args, **kwargs)
+
+    pipeline_cls.execute = sentry_patched_execute
+
+
+def patch_redis_client(cls, is_cluster, set_db_data_fn):
+    # type: (Any, bool, Callable[[Span, Any], None]) -> None
+    """
+    This function can be used to instrument custom redis client classes or
+    subclasses.
+    """
+    old_execute_command = cls.execute_command
+
+    from sentry_sdk.integrations.redis import RedisIntegration
+
+    def sentry_patched_execute_command(self, name, *args, **kwargs):
+        # type: (Any, str, *Any, **Any) -> Any
+        integration = sentry_sdk.get_client().get_integration(RedisIntegration)
+        if integration is None:
+            return old_execute_command(self, name, *args, **kwargs)
+
+        cache_properties = _compile_cache_span_properties(
+            name,
+            args,
+            kwargs,
+            integration,
+        )
+
+        cache_span = None
+        if cache_properties["is_cache_key"] and cache_properties["op"] is not None:
+            cache_span = sentry_sdk.start_span(
+                op=cache_properties["op"],
+                name=cache_properties["description"],
+                origin=SPAN_ORIGIN,
+            )
+            cache_span.__enter__()
+
+        db_properties = _compile_db_span_properties(integration, name, args)
+
+        db_span = sentry_sdk.start_span(
+            op=db_properties["op"],
+            name=db_properties["description"],
+            origin=SPAN_ORIGIN,
+        )
+        db_span.__enter__()
+
+        set_db_data_fn(db_span, self)
+        _set_client_data(db_span, is_cluster, name, *args)
+
+        value = old_execute_command(self, name, *args, **kwargs)
+
+        db_span.__exit__(None, None, None)
+
+        if cache_span:
+            _set_cache_data(cache_span, self, cache_properties, value)
+            cache_span.__exit__(None, None, None)
+
+        return value
+
+    cls.execute_command = sentry_patched_execute_command
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/consts.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/consts.py
new file mode 100644
index 0000000000000000000000000000000000000000..737e8297352158d1a8d674d0b66068e9376805ad
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/consts.py
@@ -0,0 +1,19 @@
+SPAN_ORIGIN = "auto.db.redis"
+
+_SINGLE_KEY_COMMANDS = frozenset(
+    ["decr", "decrby", "get", "incr", "incrby", "pttl", "set", "setex", "setnx", "ttl"],
+)
+_MULTI_KEY_COMMANDS = frozenset(
+    [
+        "del",
+        "touch",
+        "unlink",
+        "mget",
+    ],
+)
+_COMMANDS_INCLUDING_SENSITIVE_DATA = [
+    "auth",
+]
+_MAX_NUM_ARGS = 10  # Trim argument lists to this many values
+_MAX_NUM_COMMANDS = 10  # Trim command lists to this many values
+_DEFAULT_MAX_DATA_SIZE = 1024
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/modules/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/modules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/modules/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/modules/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..056e1536aea0879e38587382da4eb0c61d199b55
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/modules/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/modules/__pycache__/caches.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/modules/__pycache__/caches.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1575f63d21cd33d99c67600e2825df89ec1a07eb
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/modules/__pycache__/caches.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/modules/__pycache__/queries.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/modules/__pycache__/queries.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0a6345a8f9e2ac9b52b6556e2b9b5e1ddd9e77d0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/modules/__pycache__/queries.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/modules/caches.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/modules/caches.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6fc19f5b241329328b2415f22feca8f7281bad9
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/modules/caches.py
@@ -0,0 +1,121 @@
+"""
+Code used for the Caches module in Sentry
+"""
+
+from sentry_sdk.consts import OP, SPANDATA
+from sentry_sdk.integrations.redis.utils import _get_safe_key, _key_as_string
+from sentry_sdk.utils import capture_internal_exceptions
+
+GET_COMMANDS = ("get", "mget")
+SET_COMMANDS = ("set", "setex")
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from sentry_sdk.integrations.redis import RedisIntegration
+    from sentry_sdk.tracing import Span
+    from typing import Any, Optional
+
+
+def _get_op(name):
+    # type: (str) -> Optional[str]
+    op = None
+    if name.lower() in GET_COMMANDS:
+        op = OP.CACHE_GET
+    elif name.lower() in SET_COMMANDS:
+        op = OP.CACHE_PUT
+
+    return op
+
+
+def _compile_cache_span_properties(redis_command, args, kwargs, integration):
+    # type: (str, tuple[Any, ...], dict[str, Any], RedisIntegration) -> dict[str, Any]
+    key = _get_safe_key(redis_command, args, kwargs)
+    key_as_string = _key_as_string(key)
+    keys_as_string = key_as_string.split(", ")
+
+    is_cache_key = False
+    for prefix in integration.cache_prefixes:
+        for kee in keys_as_string:
+            if kee.startswith(prefix):
+                is_cache_key = True
+                break
+        if is_cache_key:
+            break
+
+    value = None
+    if redis_command.lower() in SET_COMMANDS:
+        value = args[-1]
+
+    properties = {
+        "op": _get_op(redis_command),
+        "description": _get_cache_span_description(
+            redis_command, args, kwargs, integration
+        ),
+        "key": key,
+        "key_as_string": key_as_string,
+        "redis_command": redis_command.lower(),
+        "is_cache_key": is_cache_key,
+        "value": value,
+    }
+
+    return properties
+
+
+def _get_cache_span_description(redis_command, args, kwargs, integration):
+    # type: (str, tuple[Any, ...], dict[str, Any], RedisIntegration) -> str
+    description = _key_as_string(_get_safe_key(redis_command, args, kwargs))
+
+    data_should_be_truncated = (
+        integration.max_data_size and len(description) > integration.max_data_size
+    )
+    if data_should_be_truncated:
+        description = description[: integration.max_data_size - len("...")] + "..."
+
+    return description
+
+
+def _set_cache_data(span, redis_client, properties, return_value):
+    # type: (Span, Any, dict[str, Any], Optional[Any]) -> None
+    with capture_internal_exceptions():
+        span.set_data(SPANDATA.CACHE_KEY, properties["key"])
+
+        if properties["redis_command"] in GET_COMMANDS:
+            if return_value is not None:
+                span.set_data(SPANDATA.CACHE_HIT, True)
+                size = (
+                    len(str(return_value).encode("utf-8"))
+                    if not isinstance(return_value, bytes)
+                    else len(return_value)
+                )
+                span.set_data(SPANDATA.CACHE_ITEM_SIZE, size)
+            else:
+                span.set_data(SPANDATA.CACHE_HIT, False)
+
+        elif properties["redis_command"] in SET_COMMANDS:
+            if properties["value"] is not None:
+                size = (
+                    len(properties["value"].encode("utf-8"))
+                    if not isinstance(properties["value"], bytes)
+                    else len(properties["value"])
+                )
+                span.set_data(SPANDATA.CACHE_ITEM_SIZE, size)
+
+        try:
+            connection_params = redis_client.connection_pool.connection_kwargs
+        except AttributeError:
+            # If it is a cluster, there is no connection_pool attribute so we
+            # need to get the default node from the cluster instance
+            default_node = redis_client.get_default_node()
+            connection_params = {
+                "host": default_node.host,
+                "port": default_node.port,
+            }
+
+        host = connection_params.get("host")
+        if host is not None:
+            span.set_data(SPANDATA.NETWORK_PEER_ADDRESS, host)
+
+        port = connection_params.get("port")
+        if port is not None:
+            span.set_data(SPANDATA.NETWORK_PEER_PORT, port)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/modules/queries.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/modules/queries.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0d85a4ef742394cb7e44b7a84a3e124cafd1920
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/modules/queries.py
@@ -0,0 +1,68 @@
+"""
+Code used for the Queries module in Sentry
+"""
+
+from sentry_sdk.consts import OP, SPANDATA
+from sentry_sdk.integrations.redis.utils import _get_safe_command
+from sentry_sdk.utils import capture_internal_exceptions
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from redis import Redis
+    from sentry_sdk.integrations.redis import RedisIntegration
+    from sentry_sdk.tracing import Span
+    from typing import Any
+
+
+def _compile_db_span_properties(integration, redis_command, args):
+    # type: (RedisIntegration, str, tuple[Any, ...]) -> dict[str, Any]
+    description = _get_db_span_description(integration, redis_command, args)
+
+    properties = {
+        "op": OP.DB_REDIS,
+        "description": description,
+    }
+
+    return properties
+
+
+def _get_db_span_description(integration, command_name, args):
+    # type: (RedisIntegration, str, tuple[Any, ...]) -> str
+    description = command_name
+
+    with capture_internal_exceptions():
+        description = _get_safe_command(command_name, args)
+
+    data_should_be_truncated = (
+        integration.max_data_size and len(description) > integration.max_data_size
+    )
+    if data_should_be_truncated:
+        description = description[: integration.max_data_size - len("...")] + "..."
+
+    return description
+
+
+def _set_db_data_on_span(span, connection_params):
+    # type: (Span, dict[str, Any]) -> None
+    span.set_data(SPANDATA.DB_SYSTEM, "redis")
+
+    db = connection_params.get("db")
+    if db is not None:
+        span.set_data(SPANDATA.DB_NAME, str(db))
+
+    host = connection_params.get("host")
+    if host is not None:
+        span.set_data(SPANDATA.SERVER_ADDRESS, host)
+
+    port = connection_params.get("port")
+    if port is not None:
+        span.set_data(SPANDATA.SERVER_PORT, port)
+
+
+def _set_db_data(span, redis_instance):
+    # type: (Span, Redis[Any]) -> None
+    try:
+        _set_db_data_on_span(span, redis_instance.connection_pool.connection_kwargs)
+    except AttributeError:
+        pass  # connections_kwargs may be missing in some cases
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/rb.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/rb.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b3e2e530cc40ac7980d65b2e2eb0427e7baf8be
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/rb.py
@@ -0,0 +1,32 @@
+"""
+Instrumentation for Redis Blaster (rb)
+
+https://github.com/getsentry/rb
+"""
+
+from sentry_sdk.integrations.redis._sync_common import patch_redis_client
+from sentry_sdk.integrations.redis.modules.queries import _set_db_data
+
+
+def _patch_rb():
+    # type: () -> None
+    try:
+        import rb.clients  # type: ignore
+    except ImportError:
+        pass
+    else:
+        patch_redis_client(
+            rb.clients.FanoutClient,
+            is_cluster=False,
+            set_db_data_fn=_set_db_data,
+        )
+        patch_redis_client(
+            rb.clients.MappingClient,
+            is_cluster=False,
+            set_db_data_fn=_set_db_data,
+        )
+        patch_redis_client(
+            rb.clients.RoutingClient,
+            is_cluster=False,
+            set_db_data_fn=_set_db_data,
+        )
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/redis.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/redis.py
new file mode 100644
index 0000000000000000000000000000000000000000..c92958a32d830e43ba887e71051b823d575fbabe
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/redis.py
@@ -0,0 +1,69 @@
+"""
+Instrumentation for Redis
+
+https://github.com/redis/redis-py
+"""
+
+from sentry_sdk.integrations.redis._sync_common import (
+    patch_redis_client,
+    patch_redis_pipeline,
+)
+from sentry_sdk.integrations.redis.modules.queries import _set_db_data
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Sequence
+
+
+def _get_redis_command_args(command):
+    # type: (Any) -> Sequence[Any]
+    return command[0]
+
+
+def _patch_redis(StrictRedis, client):  # noqa: N803
+    # type: (Any, Any) -> None
+    patch_redis_client(
+        StrictRedis,
+        is_cluster=False,
+        set_db_data_fn=_set_db_data,
+    )
+    patch_redis_pipeline(
+        client.Pipeline,
+        is_cluster=False,
+        get_command_args_fn=_get_redis_command_args,
+        set_db_data_fn=_set_db_data,
+    )
+    try:
+        strict_pipeline = client.StrictPipeline
+    except AttributeError:
+        pass
+    else:
+        patch_redis_pipeline(
+            strict_pipeline,
+            is_cluster=False,
+            get_command_args_fn=_get_redis_command_args,
+            set_db_data_fn=_set_db_data,
+        )
+
+    try:
+        import redis.asyncio
+    except ImportError:
+        pass
+    else:
+        from sentry_sdk.integrations.redis._async_common import (
+            patch_redis_async_client,
+            patch_redis_async_pipeline,
+        )
+
+        patch_redis_async_client(
+            redis.asyncio.client.StrictRedis,
+            is_cluster=False,
+            set_db_data_fn=_set_db_data,
+        )
+        patch_redis_async_pipeline(
+            redis.asyncio.client.Pipeline,
+            False,
+            _get_redis_command_args,
+            set_db_data_fn=_set_db_data,
+        )
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/redis_cluster.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/redis_cluster.py
new file mode 100644
index 0000000000000000000000000000000000000000..52936d1512f191a62746dc30f65b1ca075bb274a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/redis_cluster.py
@@ -0,0 +1,107 @@
+"""
+Instrumentation for RedisCluster
+This is part of the main redis-py client.
+
+https://github.com/redis/redis-py/blob/master/redis/cluster.py
+"""
+
+from sentry_sdk.integrations.redis._sync_common import (
+    patch_redis_client,
+    patch_redis_pipeline,
+)
+from sentry_sdk.integrations.redis.modules.queries import _set_db_data_on_span
+from sentry_sdk.integrations.redis.utils import _parse_rediscluster_command
+
+from sentry_sdk.utils import capture_internal_exceptions
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from redis import RedisCluster
+    from redis.asyncio.cluster import (
+        RedisCluster as AsyncRedisCluster,
+        ClusterPipeline as AsyncClusterPipeline,
+    )
+    from sentry_sdk.tracing import Span
+
+
+def _set_async_cluster_db_data(span, async_redis_cluster_instance):
+    # type: (Span, AsyncRedisCluster[Any]) -> None
+    default_node = async_redis_cluster_instance.get_default_node()
+    if default_node is not None and default_node.connection_kwargs is not None:
+        _set_db_data_on_span(span, default_node.connection_kwargs)
+
+
+def _set_async_cluster_pipeline_db_data(span, async_redis_cluster_pipeline_instance):
+    # type: (Span, AsyncClusterPipeline[Any]) -> None
+    with capture_internal_exceptions():
+        client = getattr(async_redis_cluster_pipeline_instance, "cluster_client", None)
+        if client is None:
+            # In older redis-py versions, the AsyncClusterPipeline had a `_client`
+            # attr but it is private so potentially problematic and mypy does not
+            # recognize it - see
+            # https://github.com/redis/redis-py/blame/v5.0.0/redis/asyncio/cluster.py#L1386
+            client = (
+                async_redis_cluster_pipeline_instance._client  # type: ignore[attr-defined]
+            )
+
+        _set_async_cluster_db_data(
+            span,
+            client,
+        )
+
+
+def _set_cluster_db_data(span, redis_cluster_instance):
+    # type: (Span, RedisCluster[Any]) -> None
+    default_node = redis_cluster_instance.get_default_node()
+
+    if default_node is not None:
+        connection_params = {
+            "host": default_node.host,
+            "port": default_node.port,
+        }
+        _set_db_data_on_span(span, connection_params)
+
+
+def _patch_redis_cluster():
+    # type: () -> None
+    """Patches the cluster module on redis SDK (as opposed to rediscluster library)"""
+    try:
+        from redis import RedisCluster, cluster
+    except ImportError:
+        pass
+    else:
+        patch_redis_client(
+            RedisCluster,
+            is_cluster=True,
+            set_db_data_fn=_set_cluster_db_data,
+        )
+        patch_redis_pipeline(
+            cluster.ClusterPipeline,
+            is_cluster=True,
+            get_command_args_fn=_parse_rediscluster_command,
+            set_db_data_fn=_set_cluster_db_data,
+        )
+
+    try:
+        from redis.asyncio import cluster as async_cluster
+    except ImportError:
+        pass
+    else:
+        from sentry_sdk.integrations.redis._async_common import (
+            patch_redis_async_client,
+            patch_redis_async_pipeline,
+        )
+
+        patch_redis_async_client(
+            async_cluster.RedisCluster,
+            is_cluster=True,
+            set_db_data_fn=_set_async_cluster_db_data,
+        )
+        patch_redis_async_pipeline(
+            async_cluster.ClusterPipeline,
+            is_cluster=True,
+            get_command_args_fn=_parse_rediscluster_command,
+            set_db_data_fn=_set_async_cluster_pipeline_db_data,
+        )
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/redis_py_cluster_legacy.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/redis_py_cluster_legacy.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad1c23633f70d7662f57ae94b9a9107495307121
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/redis_py_cluster_legacy.py
@@ -0,0 +1,50 @@
+"""
+Instrumentation for redis-py-cluster
+The project redis-py-cluster is EOL and was integrated into redis-py starting from version 4.1.0 (Dec 26, 2021).
+
+https://github.com/grokzen/redis-py-cluster
+"""
+
+from sentry_sdk.integrations.redis._sync_common import (
+    patch_redis_client,
+    patch_redis_pipeline,
+)
+from sentry_sdk.integrations.redis.modules.queries import _set_db_data
+from sentry_sdk.integrations.redis.utils import _parse_rediscluster_command
+
+
+def _patch_rediscluster():
+    # type: () -> None
+    try:
+        import rediscluster  # type: ignore
+    except ImportError:
+        return
+
+    patch_redis_client(
+        rediscluster.RedisCluster,
+        is_cluster=True,
+        set_db_data_fn=_set_db_data,
+    )
+
+    # up to v1.3.6, __version__ attribute is a tuple
+    # from v2.0.0, __version__ is a string and VERSION a tuple
+    version = getattr(rediscluster, "VERSION", rediscluster.__version__)
+
+    # StrictRedisCluster was introduced in v0.2.0 and removed in v2.0.0
+    # https://github.com/Grokzen/redis-py-cluster/blob/master/docs/release-notes.rst
+    if (0, 2, 0) < version < (2, 0, 0):
+        pipeline_cls = rediscluster.pipeline.StrictClusterPipeline
+        patch_redis_client(
+            rediscluster.StrictRedisCluster,
+            is_cluster=True,
+            set_db_data_fn=_set_db_data,
+        )
+    else:
+        pipeline_cls = rediscluster.pipeline.ClusterPipeline
+
+    patch_redis_pipeline(
+        pipeline_cls,
+        is_cluster=True,
+        get_command_args_fn=_parse_rediscluster_command,
+        set_db_data_fn=_set_db_data,
+    )
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/utils.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf230f664835f8292f3e7ade1616adf6c2aadaa9
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/redis/utils.py
@@ -0,0 +1,148 @@
+from sentry_sdk.consts import SPANDATA
+from sentry_sdk.integrations.redis.consts import (
+    _COMMANDS_INCLUDING_SENSITIVE_DATA,
+    _MAX_NUM_ARGS,
+    _MAX_NUM_COMMANDS,
+    _MULTI_KEY_COMMANDS,
+    _SINGLE_KEY_COMMANDS,
+)
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.utils import SENSITIVE_DATA_SUBSTITUTE
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Optional, Sequence
+    from sentry_sdk.tracing import Span
+
+
+def _get_safe_command(name, args):
+    # type: (str, Sequence[Any]) -> str
+    command_parts = [name]
+
+    for i, arg in enumerate(args):
+        if i > _MAX_NUM_ARGS:
+            break
+
+        name_low = name.lower()
+
+        if name_low in _COMMANDS_INCLUDING_SENSITIVE_DATA:
+            command_parts.append(SENSITIVE_DATA_SUBSTITUTE)
+            continue
+
+        arg_is_the_key = i == 0
+        if arg_is_the_key:
+            command_parts.append(repr(arg))
+
+        else:
+            if should_send_default_pii():
+                command_parts.append(repr(arg))
+            else:
+                command_parts.append(SENSITIVE_DATA_SUBSTITUTE)
+
+    command = " ".join(command_parts)
+    return command
+
+
+def _safe_decode(key):
+    # type: (Any) -> str
+    if isinstance(key, bytes):
+        try:
+            return key.decode()
+        except UnicodeDecodeError:
+            return ""
+
+    return str(key)
+
+
+def _key_as_string(key):
+    # type: (Any) -> str
+    if isinstance(key, (dict, list, tuple)):
+        key = ", ".join(_safe_decode(x) for x in key)
+    elif isinstance(key, bytes):
+        key = _safe_decode(key)
+    elif key is None:
+        key = ""
+    else:
+        key = str(key)
+
+    return key
+
+
+def _get_safe_key(method_name, args, kwargs):
+    # type: (str, Optional[tuple[Any, ...]], Optional[dict[str, Any]]) -> Optional[tuple[str, ...]]
+    """
+    Gets the key (or keys) from the given method_name.
+    The method_name could be a redis command or a django caching command
+    """
+    key = None
+
+    if args is not None and method_name.lower() in _MULTI_KEY_COMMANDS:
+        # for example redis "mget"
+        key = tuple(args)
+
+    elif args is not None and len(args) >= 1:
+        # for example django "set_many/get_many" or redis "get"
+        if isinstance(args[0], (dict, list, tuple)):
+            key = tuple(args[0])
+        else:
+            key = (args[0],)
+
+    elif kwargs is not None and "key" in kwargs:
+        # this is a legacy case for older versions of Django
+        if isinstance(kwargs["key"], (list, tuple)):
+            if len(kwargs["key"]) > 0:
+                key = tuple(kwargs["key"])
+        else:
+            if kwargs["key"] is not None:
+                key = (kwargs["key"],)
+
+    return key
+
+
+def _parse_rediscluster_command(command):
+    # type: (Any) -> Sequence[Any]
+    return command.args
+
+
+def _set_pipeline_data(
+    span,
+    is_cluster,
+    get_command_args_fn,
+    is_transaction,
+    commands_seq,
+):
+    # type: (Span, bool, Any, bool, Sequence[Any]) -> None
+    span.set_tag("redis.is_cluster", is_cluster)
+    span.set_tag("redis.transaction", is_transaction)
+
+    commands = []
+    for i, arg in enumerate(commands_seq):
+        if i >= _MAX_NUM_COMMANDS:
+            break
+
+        command = get_command_args_fn(arg)
+        commands.append(_get_safe_command(command[0], command[1:]))
+
+    span.set_data(
+        "redis.commands",
+        {
+            "count": len(commands_seq),
+            "first_ten": commands,
+        },
+    )
+
+
+def _set_client_data(span, is_cluster, name, *args):
+    # type: (Span, bool, str, *Any) -> None
+    span.set_tag("redis.is_cluster", is_cluster)
+    if name:
+        span.set_tag("redis.command", name)
+        span.set_tag(SPANDATA.DB_OPERATION, name)
+
+    if name and args:
+        name_low = name.lower()
+        if (name_low in _SINGLE_KEY_COMMANDS) or (
+            name_low in _MULTI_KEY_COMMANDS and len(args) == 1
+        ):
+            span.set_tag("redis.key", args[0])
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/rq.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/rq.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d7fcf723bb7d2a89661a63ad62a71d18efd0405
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/rq.py
@@ -0,0 +1,161 @@
+import weakref
+
+import sentry_sdk
+from sentry_sdk.consts import OP
+from sentry_sdk.api import continue_trace
+from sentry_sdk.integrations import _check_minimum_version, DidNotEnable, Integration
+from sentry_sdk.integrations.logging import ignore_logger
+from sentry_sdk.tracing import TransactionSource
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    event_from_exception,
+    format_timestamp,
+    parse_version,
+)
+
+try:
+    from rq.queue import Queue
+    from rq.timeouts import JobTimeoutException
+    from rq.version import VERSION as RQ_VERSION
+    from rq.worker import Worker
+    from rq.job import JobStatus
+except ImportError:
+    raise DidNotEnable("RQ not installed")
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Callable
+
+    from sentry_sdk._types import Event, EventProcessor
+    from sentry_sdk.utils import ExcInfo
+
+    from rq.job import Job
+
+
+class RqIntegration(Integration):
+    identifier = "rq"
+    origin = f"auto.queue.{identifier}"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        version = parse_version(RQ_VERSION)
+        _check_minimum_version(RqIntegration, version)
+
+        old_perform_job = Worker.perform_job
+
+        @ensure_integration_enabled(RqIntegration, old_perform_job)
+        def sentry_patched_perform_job(self, job, *args, **kwargs):
+            # type: (Any, Job, *Queue, **Any) -> bool
+            with sentry_sdk.new_scope() as scope:
+                scope.clear_breadcrumbs()
+                scope.add_event_processor(_make_event_processor(weakref.ref(job)))
+
+                transaction = continue_trace(
+                    job.meta.get("_sentry_trace_headers") or {},
+                    op=OP.QUEUE_TASK_RQ,
+                    name="unknown RQ task",
+                    source=TransactionSource.TASK,
+                    origin=RqIntegration.origin,
+                )
+
+                with capture_internal_exceptions():
+                    transaction.name = job.func_name
+
+                with sentry_sdk.start_transaction(
+                    transaction,
+                    custom_sampling_context={"rq_job": job},
+                ):
+                    rv = old_perform_job(self, job, *args, **kwargs)
+
+            if self.is_horse:
+                # We're inside of a forked process and RQ is
+                # about to call `os._exit`. Make sure that our
+                # events get sent out.
+                sentry_sdk.get_client().flush()
+
+            return rv
+
+        Worker.perform_job = sentry_patched_perform_job
+
+        old_handle_exception = Worker.handle_exception
+
+        def sentry_patched_handle_exception(self, job, *exc_info, **kwargs):
+            # type: (Worker, Any, *Any, **Any) -> Any
+            retry = (
+                hasattr(job, "retries_left")
+                and job.retries_left
+                and job.retries_left > 0
+            )
+            failed = job._status == JobStatus.FAILED or job.is_failed
+            if failed and not retry:
+                _capture_exception(exc_info)
+
+            return old_handle_exception(self, job, *exc_info, **kwargs)
+
+        Worker.handle_exception = sentry_patched_handle_exception
+
+        old_enqueue_job = Queue.enqueue_job
+
+        @ensure_integration_enabled(RqIntegration, old_enqueue_job)
+        def sentry_patched_enqueue_job(self, job, **kwargs):
+            # type: (Queue, Any, **Any) -> Any
+            scope = sentry_sdk.get_current_scope()
+            if scope.span is not None:
+                job.meta["_sentry_trace_headers"] = dict(
+                    scope.iter_trace_propagation_headers()
+                )
+
+            return old_enqueue_job(self, job, **kwargs)
+
+        Queue.enqueue_job = sentry_patched_enqueue_job
+
+        ignore_logger("rq.worker")
+
+
+def _make_event_processor(weak_job):
+    # type: (Callable[[], Job]) -> EventProcessor
+    def event_processor(event, hint):
+        # type: (Event, dict[str, Any]) -> Event
+        job = weak_job()
+        if job is not None:
+            with capture_internal_exceptions():
+                extra = event.setdefault("extra", {})
+                rq_job = {
+                    "job_id": job.id,
+                    "func": job.func_name,
+                    "args": job.args,
+                    "kwargs": job.kwargs,
+                    "description": job.description,
+                }
+
+                if job.enqueued_at:
+                    rq_job["enqueued_at"] = format_timestamp(job.enqueued_at)
+                if job.started_at:
+                    rq_job["started_at"] = format_timestamp(job.started_at)
+
+                extra["rq-job"] = rq_job
+
+        if "exc_info" in hint:
+            with capture_internal_exceptions():
+                if issubclass(hint["exc_info"][0], JobTimeoutException):
+                    event["fingerprint"] = ["rq", "JobTimeoutException", job.func_name]
+
+        return event
+
+    return event_processor
+
+
+def _capture_exception(exc_info, **kwargs):
+    # type: (ExcInfo, **Any) -> None
+    client = sentry_sdk.get_client()
+
+    event, hint = event_from_exception(
+        exc_info,
+        client_options=client.options,
+        mechanism={"type": "rq", "handled": False},
+    )
+
+    sentry_sdk.capture_event(event, hint=hint)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/rust_tracing.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/rust_tracing.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4c211814faa4d45c5368963b63c753ea186ea54
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/rust_tracing.py
@@ -0,0 +1,284 @@
+"""
+This integration ingests tracing data from native extensions written in Rust.
+
+Using it requires additional setup on the Rust side to accept a
+`RustTracingLayer` Python object and register it with the `tracing-subscriber`
+using an adapter from the `pyo3-python-tracing-subscriber` crate. For example:
+```rust
+#[pyfunction]
+pub fn initialize_tracing(py_impl: Bound<'_, PyAny>) {
+    tracing_subscriber::registry()
+        .with(pyo3_python_tracing_subscriber::PythonCallbackLayerBridge::new(py_impl))
+        .init();
+}
+```
+
+Usage in Python would then look like:
+```
+sentry_sdk.init(
+    dsn=sentry_dsn,
+    integrations=[
+        RustTracingIntegration(
+            "demo_rust_extension",
+            demo_rust_extension.initialize_tracing,
+            event_type_mapping=event_type_mapping,
+        )
+    ],
+)
+```
+
+Each native extension requires its own integration.
+"""
+
+import json
+from enum import Enum, auto
+from typing import Any, Callable, Dict, Tuple, Optional
+
+import sentry_sdk
+from sentry_sdk.integrations import Integration
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.tracing import Span as SentrySpan
+from sentry_sdk.utils import SENSITIVE_DATA_SUBSTITUTE
+
+TraceState = Optional[Tuple[Optional[SentrySpan], SentrySpan]]
+
+
+class RustTracingLevel(Enum):
+    Trace = "TRACE"
+    Debug = "DEBUG"
+    Info = "INFO"
+    Warn = "WARN"
+    Error = "ERROR"
+
+
+class EventTypeMapping(Enum):
+    Ignore = auto()
+    Exc = auto()
+    Breadcrumb = auto()
+    Event = auto()
+
+
+def tracing_level_to_sentry_level(level):
+    # type: (str) -> sentry_sdk._types.LogLevelStr
+    level = RustTracingLevel(level)
+    if level in (RustTracingLevel.Trace, RustTracingLevel.Debug):
+        return "debug"
+    elif level == RustTracingLevel.Info:
+        return "info"
+    elif level == RustTracingLevel.Warn:
+        return "warning"
+    elif level == RustTracingLevel.Error:
+        return "error"
+    else:
+        # Better this than crashing
+        return "info"
+
+
+def extract_contexts(event: Dict[str, Any]) -> Dict[str, Any]:
+    metadata = event.get("metadata", {})
+    contexts = {}
+
+    location = {}
+    for field in ["module_path", "file", "line"]:
+        if field in metadata:
+            location[field] = metadata[field]
+    if len(location) > 0:
+        contexts["rust_tracing_location"] = location
+
+    fields = {}
+    for field in metadata.get("fields", []):
+        fields[field] = event.get(field)
+    if len(fields) > 0:
+        contexts["rust_tracing_fields"] = fields
+
+    return contexts
+
+
+def process_event(event: Dict[str, Any]) -> None:
+    metadata = event.get("metadata", {})
+
+    logger = metadata.get("target")
+    level = tracing_level_to_sentry_level(metadata.get("level"))
+    message = event.get("message")  # type: sentry_sdk._types.Any
+    contexts = extract_contexts(event)
+
+    sentry_event = {
+        "logger": logger,
+        "level": level,
+        "message": message,
+        "contexts": contexts,
+    }  # type: sentry_sdk._types.Event
+
+    sentry_sdk.capture_event(sentry_event)
+
+
+def process_exception(event: Dict[str, Any]) -> None:
+    process_event(event)
+
+
+def process_breadcrumb(event: Dict[str, Any]) -> None:
+    level = tracing_level_to_sentry_level(event.get("metadata", {}).get("level"))
+    message = event.get("message")
+
+    sentry_sdk.add_breadcrumb(level=level, message=message)
+
+
+def default_span_filter(metadata: Dict[str, Any]) -> bool:
+    return RustTracingLevel(metadata.get("level")) in (
+        RustTracingLevel.Error,
+        RustTracingLevel.Warn,
+        RustTracingLevel.Info,
+    )
+
+
+def default_event_type_mapping(metadata: Dict[str, Any]) -> EventTypeMapping:
+    level = RustTracingLevel(metadata.get("level"))
+    if level == RustTracingLevel.Error:
+        return EventTypeMapping.Exc
+    elif level in (RustTracingLevel.Warn, RustTracingLevel.Info):
+        return EventTypeMapping.Breadcrumb
+    elif level in (RustTracingLevel.Debug, RustTracingLevel.Trace):
+        return EventTypeMapping.Ignore
+    else:
+        return EventTypeMapping.Ignore
+
+
+class RustTracingLayer:
+    def __init__(
+        self,
+        origin: str,
+        event_type_mapping: Callable[
+            [Dict[str, Any]], EventTypeMapping
+        ] = default_event_type_mapping,
+        span_filter: Callable[[Dict[str, Any]], bool] = default_span_filter,
+        include_tracing_fields: Optional[bool] = None,
+    ):
+        self.origin = origin
+        self.event_type_mapping = event_type_mapping
+        self.span_filter = span_filter
+        self.include_tracing_fields = include_tracing_fields
+
+    def _include_tracing_fields(self) -> bool:
+        """
+        By default, the values of tracing fields are not included in case they
+        contain PII. A user may override that by passing `True` for the
+        `include_tracing_fields` keyword argument of this integration or by
+        setting `send_default_pii` to `True` in their Sentry client options.
+        """
+        return (
+            should_send_default_pii()
+            if self.include_tracing_fields is None
+            else self.include_tracing_fields
+        )
+
+    def on_event(self, event: str, _span_state: TraceState) -> None:
+        deserialized_event = json.loads(event)
+        metadata = deserialized_event.get("metadata", {})
+
+        event_type = self.event_type_mapping(metadata)
+        if event_type == EventTypeMapping.Ignore:
+            return
+        elif event_type == EventTypeMapping.Exc:
+            process_exception(deserialized_event)
+        elif event_type == EventTypeMapping.Breadcrumb:
+            process_breadcrumb(deserialized_event)
+        elif event_type == EventTypeMapping.Event:
+            process_event(deserialized_event)
+
+    def on_new_span(self, attrs: str, span_id: str) -> TraceState:
+        attrs = json.loads(attrs)
+        metadata = attrs.get("metadata", {})
+
+        if not self.span_filter(metadata):
+            return None
+
+        module_path = metadata.get("module_path")
+        name = metadata.get("name")
+        message = attrs.get("message")
+
+        if message is not None:
+            sentry_span_name = message
+        elif module_path is not None and name is not None:
+            sentry_span_name = f"{module_path}::{name}"  # noqa: E231
+        elif name is not None:
+            sentry_span_name = name
+        else:
+            sentry_span_name = ""
+
+        kwargs = {
+            "op": "function",
+            "name": sentry_span_name,
+            "origin": self.origin,
+        }
+
+        scope = sentry_sdk.get_current_scope()
+        parent_sentry_span = scope.span
+        if parent_sentry_span:
+            sentry_span = parent_sentry_span.start_child(**kwargs)
+        else:
+            sentry_span = scope.start_span(**kwargs)
+
+        fields = metadata.get("fields", [])
+        for field in fields:
+            if self._include_tracing_fields():
+                sentry_span.set_data(field, attrs.get(field))
+            else:
+                sentry_span.set_data(field, SENSITIVE_DATA_SUBSTITUTE)
+
+        scope.span = sentry_span
+        return (parent_sentry_span, sentry_span)
+
+    def on_close(self, span_id: str, span_state: TraceState) -> None:
+        if span_state is None:
+            return
+
+        parent_sentry_span, sentry_span = span_state
+        sentry_span.finish()
+        sentry_sdk.get_current_scope().span = parent_sentry_span
+
+    def on_record(self, span_id: str, values: str, span_state: TraceState) -> None:
+        if span_state is None:
+            return
+        _parent_sentry_span, sentry_span = span_state
+
+        deserialized_values = json.loads(values)
+        for key, value in deserialized_values.items():
+            if self._include_tracing_fields():
+                sentry_span.set_data(key, value)
+            else:
+                sentry_span.set_data(key, SENSITIVE_DATA_SUBSTITUTE)
+
+
+class RustTracingIntegration(Integration):
+    """
+    Ingests tracing data from a Rust native extension's `tracing` instrumentation.
+
+    If a project uses more than one Rust native extension, each one will need
+    its own instance of `RustTracingIntegration` with an initializer function
+    specific to that extension.
+
+    Since all of the setup for this integration requires instance-specific state
+    which is not available in `setup_once()`, setup instead happens in `__init__()`.
+    """
+
+    def __init__(
+        self,
+        identifier: str,
+        initializer: Callable[[RustTracingLayer], None],
+        event_type_mapping: Callable[
+            [Dict[str, Any]], EventTypeMapping
+        ] = default_event_type_mapping,
+        span_filter: Callable[[Dict[str, Any]], bool] = default_span_filter,
+        include_tracing_fields: Optional[bool] = None,
+    ):
+        self.identifier = identifier
+        origin = f"auto.function.rust_tracing.{identifier}"
+        self.tracing_layer = RustTracingLayer(
+            origin, event_type_mapping, span_filter, include_tracing_fields
+        )
+
+        initializer(self.tracing_layer)
+
+    @staticmethod
+    def setup_once() -> None:
+        pass
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/sanic.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/sanic.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd8f1f329b437f3c20754eb111b38ceb95ce34f1
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/sanic.py
@@ -0,0 +1,368 @@
+import sys
+import weakref
+from inspect import isawaitable
+from urllib.parse import urlsplit
+
+import sentry_sdk
+from sentry_sdk import continue_trace
+from sentry_sdk.consts import OP
+from sentry_sdk.integrations import _check_minimum_version, Integration, DidNotEnable
+from sentry_sdk.integrations._wsgi_common import RequestExtractor, _filter_headers
+from sentry_sdk.integrations.logging import ignore_logger
+from sentry_sdk.tracing import TransactionSource
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    event_from_exception,
+    HAS_REAL_CONTEXTVARS,
+    CONTEXTVARS_ERROR_MESSAGE,
+    parse_version,
+    reraise,
+)
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from collections.abc import Container
+    from typing import Any
+    from typing import Callable
+    from typing import Optional
+    from typing import Union
+    from typing import Dict
+
+    from sanic.request import Request, RequestParameters
+    from sanic.response import BaseHTTPResponse
+
+    from sentry_sdk._types import Event, EventProcessor, ExcInfo, Hint
+    from sanic.router import Route
+
+try:
+    from sanic import Sanic, __version__ as SANIC_VERSION
+    from sanic.exceptions import SanicException
+    from sanic.router import Router
+    from sanic.handlers import ErrorHandler
+except ImportError:
+    raise DidNotEnable("Sanic not installed")
+
+old_error_handler_lookup = ErrorHandler.lookup
+old_handle_request = Sanic.handle_request
+old_router_get = Router.get
+
+try:
+    # This method was introduced in Sanic v21.9
+    old_startup = Sanic._startup
+except AttributeError:
+    pass
+
+
+class SanicIntegration(Integration):
+    identifier = "sanic"
+    origin = f"auto.http.{identifier}"
+    version = None
+
+    def __init__(self, unsampled_statuses=frozenset({404})):
+        # type: (Optional[Container[int]]) -> None
+        """
+        The unsampled_statuses parameter can be used to specify for which HTTP statuses the
+        transactions should not be sent to Sentry. By default, transactions are sent for all
+        HTTP statuses, except 404. Set unsampled_statuses to None to send transactions for all
+        HTTP statuses, including 404.
+        """
+        self._unsampled_statuses = unsampled_statuses or set()
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        SanicIntegration.version = parse_version(SANIC_VERSION)
+        _check_minimum_version(SanicIntegration, SanicIntegration.version)
+
+        if not HAS_REAL_CONTEXTVARS:
+            # We better have contextvars or we're going to leak state between
+            # requests.
+            raise DidNotEnable(
+                "The sanic integration for Sentry requires Python 3.7+ "
+                " or the aiocontextvars package." + CONTEXTVARS_ERROR_MESSAGE
+            )
+
+        if SANIC_VERSION.startswith("0.8."):
+            # Sanic 0.8 and older creates a logger named "root" and puts a
+            # stringified version of every exception in there (without exc_info),
+            # which our error deduplication can't detect.
+            #
+            # We explicitly check the version here because it is a very
+            # invasive step to ignore this logger and not necessary in newer
+            # versions at all.
+            #
+            # https://github.com/huge-success/sanic/issues/1332
+            ignore_logger("root")
+
+        if SanicIntegration.version is not None and SanicIntegration.version < (21, 9):
+            _setup_legacy_sanic()
+            return
+
+        _setup_sanic()
+
+
+class SanicRequestExtractor(RequestExtractor):
+    def content_length(self):
+        # type: () -> int
+        if self.request.body is None:
+            return 0
+        return len(self.request.body)
+
+    def cookies(self):
+        # type: () -> Dict[str, str]
+        return dict(self.request.cookies)
+
+    def raw_data(self):
+        # type: () -> bytes
+        return self.request.body
+
+    def form(self):
+        # type: () -> RequestParameters
+        return self.request.form
+
+    def is_json(self):
+        # type: () -> bool
+        raise NotImplementedError()
+
+    def json(self):
+        # type: () -> Optional[Any]
+        return self.request.json
+
+    def files(self):
+        # type: () -> RequestParameters
+        return self.request.files
+
+    def size_of_file(self, file):
+        # type: (Any) -> int
+        return len(file.body or ())
+
+
+def _setup_sanic():
+    # type: () -> None
+    Sanic._startup = _startup
+    ErrorHandler.lookup = _sentry_error_handler_lookup
+
+
+def _setup_legacy_sanic():
+    # type: () -> None
+    Sanic.handle_request = _legacy_handle_request
+    Router.get = _legacy_router_get
+    ErrorHandler.lookup = _sentry_error_handler_lookup
+
+
+async def _startup(self):
+    # type: (Sanic) -> None
+    # This happens about as early in the lifecycle as possible, just after the
+    # Request object is created. The body has not yet been consumed.
+    self.signal("http.lifecycle.request")(_context_enter)
+
+    # This happens after the handler is complete. In v21.9 this signal is not
+    # dispatched when there is an exception. Therefore we need to close out
+    # and call _context_exit from the custom exception handler as well.
+    # See https://github.com/sanic-org/sanic/issues/2297
+    self.signal("http.lifecycle.response")(_context_exit)
+
+    # This happens inside of request handling immediately after the route
+    # has been identified by the router.
+    self.signal("http.routing.after")(_set_transaction)
+
+    # The above signals need to be declared before this can be called.
+    await old_startup(self)
+
+
+async def _context_enter(request):
+    # type: (Request) -> None
+    request.ctx._sentry_do_integration = (
+        sentry_sdk.get_client().get_integration(SanicIntegration) is not None
+    )
+
+    if not request.ctx._sentry_do_integration:
+        return
+
+    weak_request = weakref.ref(request)
+    request.ctx._sentry_scope = sentry_sdk.isolation_scope()
+    scope = request.ctx._sentry_scope.__enter__()
+    scope.clear_breadcrumbs()
+    scope.add_event_processor(_make_request_processor(weak_request))
+
+    transaction = continue_trace(
+        dict(request.headers),
+        op=OP.HTTP_SERVER,
+        # Unless the request results in a 404 error, the name and source will get overwritten in _set_transaction
+        name=request.path,
+        source=TransactionSource.URL,
+        origin=SanicIntegration.origin,
+    )
+    request.ctx._sentry_transaction = sentry_sdk.start_transaction(
+        transaction
+    ).__enter__()
+
+
+async def _context_exit(request, response=None):
+    # type: (Request, Optional[BaseHTTPResponse]) -> None
+    with capture_internal_exceptions():
+        if not request.ctx._sentry_do_integration:
+            return
+
+        integration = sentry_sdk.get_client().get_integration(SanicIntegration)
+
+        response_status = None if response is None else response.status
+
+        # This capture_internal_exceptions block has been intentionally nested here, so that in case an exception
+        # happens while trying to end the transaction, we still attempt to exit the hub.
+        with capture_internal_exceptions():
+            request.ctx._sentry_transaction.set_http_status(response_status)
+            request.ctx._sentry_transaction.sampled &= (
+                isinstance(integration, SanicIntegration)
+                and response_status not in integration._unsampled_statuses
+            )
+            request.ctx._sentry_transaction.__exit__(None, None, None)
+
+        request.ctx._sentry_scope.__exit__(None, None, None)
+
+
+async def _set_transaction(request, route, **_):
+    # type: (Request, Route, **Any) -> None
+    if request.ctx._sentry_do_integration:
+        with capture_internal_exceptions():
+            scope = sentry_sdk.get_current_scope()
+            route_name = route.name.replace(request.app.name, "").strip(".")
+            scope.set_transaction_name(route_name, source=TransactionSource.COMPONENT)
+
+
+def _sentry_error_handler_lookup(self, exception, *args, **kwargs):
+    # type: (Any, Exception, *Any, **Any) -> Optional[object]
+    _capture_exception(exception)
+    old_error_handler = old_error_handler_lookup(self, exception, *args, **kwargs)
+
+    if old_error_handler is None:
+        return None
+
+    if sentry_sdk.get_client().get_integration(SanicIntegration) is None:
+        return old_error_handler
+
+    async def sentry_wrapped_error_handler(request, exception):
+        # type: (Request, Exception) -> Any
+        try:
+            response = old_error_handler(request, exception)
+            if isawaitable(response):
+                response = await response
+            return response
+        except Exception:
+            # Report errors that occur in Sanic error handler. These
+            # exceptions will not even show up in Sanic's
+            # `sanic.exceptions` logger.
+            exc_info = sys.exc_info()
+            _capture_exception(exc_info)
+            reraise(*exc_info)
+        finally:
+            # As mentioned in previous comment in _startup, this can be removed
+            # after https://github.com/sanic-org/sanic/issues/2297 is resolved
+            if SanicIntegration.version and SanicIntegration.version == (21, 9):
+                await _context_exit(request)
+
+    return sentry_wrapped_error_handler
+
+
+async def _legacy_handle_request(self, request, *args, **kwargs):
+    # type: (Any, Request, *Any, **Any) -> Any
+    if sentry_sdk.get_client().get_integration(SanicIntegration) is None:
+        return await old_handle_request(self, request, *args, **kwargs)
+
+    weak_request = weakref.ref(request)
+
+    with sentry_sdk.isolation_scope() as scope:
+        scope.clear_breadcrumbs()
+        scope.add_event_processor(_make_request_processor(weak_request))
+
+        response = old_handle_request(self, request, *args, **kwargs)
+        if isawaitable(response):
+            response = await response
+
+        return response
+
+
+def _legacy_router_get(self, *args):
+    # type: (Any, Union[Any, Request]) -> Any
+    rv = old_router_get(self, *args)
+    if sentry_sdk.get_client().get_integration(SanicIntegration) is not None:
+        with capture_internal_exceptions():
+            scope = sentry_sdk.get_isolation_scope()
+            if SanicIntegration.version and SanicIntegration.version >= (21, 3):
+                # Sanic versions above and including 21.3 append the app name to the
+                # route name, and so we need to remove it from Route name so the
+                # transaction name is consistent across all versions
+                sanic_app_name = self.ctx.app.name
+                sanic_route = rv[0].name
+
+                if sanic_route.startswith("%s." % sanic_app_name):
+                    # We add a 1 to the len of the sanic_app_name because there is a dot
+                    # that joins app name and the route name
+                    # Format: app_name.route_name
+                    sanic_route = sanic_route[len(sanic_app_name) + 1 :]
+
+                scope.set_transaction_name(
+                    sanic_route, source=TransactionSource.COMPONENT
+                )
+            else:
+                scope.set_transaction_name(
+                    rv[0].__name__, source=TransactionSource.COMPONENT
+                )
+
+    return rv
+
+
+@ensure_integration_enabled(SanicIntegration)
+def _capture_exception(exception):
+    # type: (Union[ExcInfo, BaseException]) -> None
+    with capture_internal_exceptions():
+        event, hint = event_from_exception(
+            exception,
+            client_options=sentry_sdk.get_client().options,
+            mechanism={"type": "sanic", "handled": False},
+        )
+
+        if hint and hasattr(hint["exc_info"][0], "quiet") and hint["exc_info"][0].quiet:
+            return
+
+        sentry_sdk.capture_event(event, hint=hint)
+
+
+def _make_request_processor(weak_request):
+    # type: (Callable[[], Request]) -> EventProcessor
+    def sanic_processor(event, hint):
+        # type: (Event, Optional[Hint]) -> Optional[Event]
+
+        try:
+            if hint and issubclass(hint["exc_info"][0], SanicException):
+                return None
+        except KeyError:
+            pass
+
+        request = weak_request()
+        if request is None:
+            return event
+
+        with capture_internal_exceptions():
+            extractor = SanicRequestExtractor(request)
+            extractor.extract_into_event(event)
+
+            request_info = event["request"]
+            urlparts = urlsplit(request.url)
+
+            request_info["url"] = "%s://%s%s" % (
+                urlparts.scheme,
+                urlparts.netloc,
+                urlparts.path,
+            )
+
+            request_info["query_string"] = urlparts.query
+            request_info["method"] = request.method
+            request_info["env"] = {"REMOTE_ADDR": request.remote_addr}
+            request_info["headers"] = _filter_headers(dict(request.headers))
+
+        return event
+
+    return sanic_processor
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/serverless.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/serverless.py
new file mode 100644
index 0000000000000000000000000000000000000000..760c07ffad83e2d313cc493679058e1b4447874a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/serverless.py
@@ -0,0 +1,76 @@
+import sys
+from functools import wraps
+
+import sentry_sdk
+from sentry_sdk.utils import event_from_exception, reraise
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Callable
+    from typing import TypeVar
+    from typing import Union
+    from typing import Optional
+    from typing import overload
+
+    F = TypeVar("F", bound=Callable[..., Any])
+
+else:
+
+    def overload(x):
+        # type: (F) -> F
+        return x
+
+
+@overload
+def serverless_function(f, flush=True):
+    # type: (F, bool) -> F
+    pass
+
+
+@overload
+def serverless_function(f=None, flush=True):  # noqa: F811
+    # type: (None, bool) -> Callable[[F], F]
+    pass
+
+
+def serverless_function(f=None, flush=True):  # noqa
+    # type: (Optional[F], bool) -> Union[F, Callable[[F], F]]
+    def wrapper(f):
+        # type: (F) -> F
+        @wraps(f)
+        def inner(*args, **kwargs):
+            # type: (*Any, **Any) -> Any
+            with sentry_sdk.isolation_scope() as scope:
+                scope.clear_breadcrumbs()
+
+                try:
+                    return f(*args, **kwargs)
+                except Exception:
+                    _capture_and_reraise()
+                finally:
+                    if flush:
+                        sentry_sdk.flush()
+
+        return inner  # type: ignore
+
+    if f is None:
+        return wrapper
+    else:
+        return wrapper(f)
+
+
+def _capture_and_reraise():
+    # type: () -> None
+    exc_info = sys.exc_info()
+    client = sentry_sdk.get_client()
+    if client.is_active():
+        event, hint = event_from_exception(
+            exc_info,
+            client_options=client.options,
+            mechanism={"type": "serverless", "handled": False},
+        )
+        sentry_sdk.capture_event(event, hint=hint)
+
+    reraise(*exc_info)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/socket.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/socket.py
new file mode 100644
index 0000000000000000000000000000000000000000..babf61aa7a81fabc4ea0f493298d6f513a496ba8
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/socket.py
@@ -0,0 +1,96 @@
+import socket
+
+import sentry_sdk
+from sentry_sdk._types import MYPY
+from sentry_sdk.consts import OP
+from sentry_sdk.integrations import Integration
+
+if MYPY:
+    from socket import AddressFamily, SocketKind
+    from typing import Tuple, Optional, Union, List
+
+__all__ = ["SocketIntegration"]
+
+
+class SocketIntegration(Integration):
+    identifier = "socket"
+    origin = f"auto.socket.{identifier}"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        """
+        patches two of the most used functions of socket: create_connection and getaddrinfo(dns resolver)
+        """
+        _patch_create_connection()
+        _patch_getaddrinfo()
+
+
+def _get_span_description(host, port):
+    # type: (Union[bytes, str, None], Union[bytes, str, int, None]) -> str
+
+    try:
+        host = host.decode()  # type: ignore
+    except (UnicodeDecodeError, AttributeError):
+        pass
+
+    try:
+        port = port.decode()  # type: ignore
+    except (UnicodeDecodeError, AttributeError):
+        pass
+
+    description = "%s:%s" % (host, port)  # type: ignore
+    return description
+
+
+def _patch_create_connection():
+    # type: () -> None
+    real_create_connection = socket.create_connection
+
+    def create_connection(
+        address,
+        timeout=socket._GLOBAL_DEFAULT_TIMEOUT,  # type: ignore
+        source_address=None,
+    ):
+        # type: (Tuple[Optional[str], int], Optional[float], Optional[Tuple[Union[bytearray, bytes, str], int]])-> socket.socket
+        integration = sentry_sdk.get_client().get_integration(SocketIntegration)
+        if integration is None:
+            return real_create_connection(address, timeout, source_address)
+
+        with sentry_sdk.start_span(
+            op=OP.SOCKET_CONNECTION,
+            name=_get_span_description(address[0], address[1]),
+            origin=SocketIntegration.origin,
+        ) as span:
+            span.set_data("address", address)
+            span.set_data("timeout", timeout)
+            span.set_data("source_address", source_address)
+
+            return real_create_connection(
+                address=address, timeout=timeout, source_address=source_address
+            )
+
+    socket.create_connection = create_connection  # type: ignore
+
+
+def _patch_getaddrinfo():
+    # type: () -> None
+    real_getaddrinfo = socket.getaddrinfo
+
+    def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
+        # type: (Union[bytes, str, None], Union[bytes, str, int, None], int, int, int, int) -> List[Tuple[AddressFamily, SocketKind, int, str, Union[Tuple[str, int], Tuple[str, int, int, int], Tuple[int, bytes]]]]
+        integration = sentry_sdk.get_client().get_integration(SocketIntegration)
+        if integration is None:
+            return real_getaddrinfo(host, port, family, type, proto, flags)
+
+        with sentry_sdk.start_span(
+            op=OP.SOCKET_DNS,
+            name=_get_span_description(host, port),
+            origin=SocketIntegration.origin,
+        ) as span:
+            span.set_data("host", host)
+            span.set_data("port", port)
+
+            return real_getaddrinfo(host, port, family, type, proto, flags)
+
+    socket.getaddrinfo = getaddrinfo
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/spark/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/spark/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..10d94163c52cb8b0b1424cdc3eac699ed49a072c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/spark/__init__.py
@@ -0,0 +1,4 @@
+from sentry_sdk.integrations.spark.spark_driver import SparkIntegration
+from sentry_sdk.integrations.spark.spark_worker import SparkWorkerIntegration
+
+__all__ = ["SparkIntegration", "SparkWorkerIntegration"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/spark/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/spark/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d20465e5dc29fa4352ac04215476d8f300dfe71e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/spark/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/spark/__pycache__/spark_driver.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/spark/__pycache__/spark_driver.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..86f6c87940e27ed01a097d759668e76bf05fa4ad
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/spark/__pycache__/spark_driver.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/spark/__pycache__/spark_worker.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/spark/__pycache__/spark_worker.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8c30af8d7adf4c8726ee8493b56586258a540b9a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/spark/__pycache__/spark_worker.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/spark/spark_driver.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/spark/spark_driver.py
new file mode 100644
index 0000000000000000000000000000000000000000..fac985357f976384b18feb6add7830c65b14096f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/spark/spark_driver.py
@@ -0,0 +1,315 @@
+import sentry_sdk
+from sentry_sdk.integrations import Integration
+from sentry_sdk.utils import capture_internal_exceptions, ensure_integration_enabled
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Optional
+
+    from sentry_sdk._types import Event, Hint
+    from pyspark import SparkContext
+
+
+class SparkIntegration(Integration):
+    identifier = "spark"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        _setup_sentry_tracing()
+
+
+def _set_app_properties():
+    # type: () -> None
+    """
+    Set properties in driver that propagate to worker processes, allowing for workers to have access to those properties.
+    This allows worker integration to have access to app_name and application_id.
+    """
+    from pyspark import SparkContext
+
+    spark_context = SparkContext._active_spark_context
+    if spark_context:
+        spark_context.setLocalProperty(
+            "sentry_app_name",
+            spark_context.appName,
+        )
+        spark_context.setLocalProperty(
+            "sentry_application_id",
+            spark_context.applicationId,
+        )
+
+
+def _start_sentry_listener(sc):
+    # type: (SparkContext) -> None
+    """
+    Start java gateway server to add custom `SparkListener`
+    """
+    from pyspark.java_gateway import ensure_callback_server_started
+
+    gw = sc._gateway
+    ensure_callback_server_started(gw)
+    listener = SentryListener()
+    sc._jsc.sc().addSparkListener(listener)
+
+
+def _add_event_processor(sc):
+    # type: (SparkContext) -> None
+    scope = sentry_sdk.get_isolation_scope()
+
+    @scope.add_event_processor
+    def process_event(event, hint):
+        # type: (Event, Hint) -> Optional[Event]
+        with capture_internal_exceptions():
+            if sentry_sdk.get_client().get_integration(SparkIntegration) is None:
+                return event
+
+            if sc._active_spark_context is None:
+                return event
+
+            event.setdefault("user", {}).setdefault("id", sc.sparkUser())
+
+            event.setdefault("tags", {}).setdefault(
+                "executor.id", sc._conf.get("spark.executor.id")
+            )
+            event["tags"].setdefault(
+                "spark-submit.deployMode",
+                sc._conf.get("spark.submit.deployMode"),
+            )
+            event["tags"].setdefault("driver.host", sc._conf.get("spark.driver.host"))
+            event["tags"].setdefault("driver.port", sc._conf.get("spark.driver.port"))
+            event["tags"].setdefault("spark_version", sc.version)
+            event["tags"].setdefault("app_name", sc.appName)
+            event["tags"].setdefault("application_id", sc.applicationId)
+            event["tags"].setdefault("master", sc.master)
+            event["tags"].setdefault("spark_home", sc.sparkHome)
+
+            event.setdefault("extra", {}).setdefault("web_url", sc.uiWebUrl)
+
+        return event
+
+
+def _activate_integration(sc):
+    # type: (SparkContext) -> None
+
+    _start_sentry_listener(sc)
+    _set_app_properties()
+    _add_event_processor(sc)
+
+
+def _patch_spark_context_init():
+    # type: () -> None
+    from pyspark import SparkContext
+
+    spark_context_init = SparkContext._do_init
+
+    @ensure_integration_enabled(SparkIntegration, spark_context_init)
+    def _sentry_patched_spark_context_init(self, *args, **kwargs):
+        # type: (SparkContext, *Any, **Any) -> Optional[Any]
+        rv = spark_context_init(self, *args, **kwargs)
+        _activate_integration(self)
+        return rv
+
+    SparkContext._do_init = _sentry_patched_spark_context_init
+
+
+def _setup_sentry_tracing():
+    # type: () -> None
+    from pyspark import SparkContext
+
+    if SparkContext._active_spark_context is not None:
+        _activate_integration(SparkContext._active_spark_context)
+        return
+    _patch_spark_context_init()
+
+
+class SparkListener:
+    def onApplicationEnd(self, applicationEnd):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onApplicationStart(self, applicationStart):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onBlockManagerAdded(self, blockManagerAdded):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onBlockManagerRemoved(self, blockManagerRemoved):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onBlockUpdated(self, blockUpdated):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onEnvironmentUpdate(self, environmentUpdate):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onExecutorAdded(self, executorAdded):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onExecutorBlacklisted(self, executorBlacklisted):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onExecutorBlacklistedForStage(  # noqa: N802
+        self, executorBlacklistedForStage  # noqa: N803
+    ):
+        # type: (Any) -> None
+        pass
+
+    def onExecutorMetricsUpdate(self, executorMetricsUpdate):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onExecutorRemoved(self, executorRemoved):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onJobEnd(self, jobEnd):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onJobStart(self, jobStart):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onNodeBlacklisted(self, nodeBlacklisted):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onNodeBlacklistedForStage(self, nodeBlacklistedForStage):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onNodeUnblacklisted(self, nodeUnblacklisted):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onOtherEvent(self, event):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onSpeculativeTaskSubmitted(self, speculativeTask):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onStageCompleted(self, stageCompleted):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onStageSubmitted(self, stageSubmitted):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onTaskEnd(self, taskEnd):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onTaskGettingResult(self, taskGettingResult):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onTaskStart(self, taskStart):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    def onUnpersistRDD(self, unpersistRDD):  # noqa: N802,N803
+        # type: (Any) -> None
+        pass
+
+    class Java:
+        implements = ["org.apache.spark.scheduler.SparkListenerInterface"]
+
+
+class SentryListener(SparkListener):
+    def _add_breadcrumb(
+        self,
+        level,  # type: str
+        message,  # type: str
+        data=None,  # type: Optional[dict[str, Any]]
+    ):
+        # type: (...) -> None
+        sentry_sdk.get_isolation_scope().add_breadcrumb(
+            level=level, message=message, data=data
+        )
+
+    def onJobStart(self, jobStart):  # noqa: N802,N803
+        # type: (Any) -> None
+        sentry_sdk.get_isolation_scope().clear_breadcrumbs()
+
+        message = "Job {} Started".format(jobStart.jobId())
+        self._add_breadcrumb(level="info", message=message)
+        _set_app_properties()
+
+    def onJobEnd(self, jobEnd):  # noqa: N802,N803
+        # type: (Any) -> None
+        level = ""
+        message = ""
+        data = {"result": jobEnd.jobResult().toString()}
+
+        if jobEnd.jobResult().toString() == "JobSucceeded":
+            level = "info"
+            message = "Job {} Ended".format(jobEnd.jobId())
+        else:
+            level = "warning"
+            message = "Job {} Failed".format(jobEnd.jobId())
+
+        self._add_breadcrumb(level=level, message=message, data=data)
+
+    def onStageSubmitted(self, stageSubmitted):  # noqa: N802,N803
+        # type: (Any) -> None
+        stage_info = stageSubmitted.stageInfo()
+        message = "Stage {} Submitted".format(stage_info.stageId())
+
+        data = {"name": stage_info.name()}
+        attempt_id = _get_attempt_id(stage_info)
+        if attempt_id is not None:
+            data["attemptId"] = attempt_id
+
+        self._add_breadcrumb(level="info", message=message, data=data)
+        _set_app_properties()
+
+    def onStageCompleted(self, stageCompleted):  # noqa: N802,N803
+        # type: (Any) -> None
+        from py4j.protocol import Py4JJavaError  # type: ignore
+
+        stage_info = stageCompleted.stageInfo()
+        message = ""
+        level = ""
+
+        data = {"name": stage_info.name()}
+        attempt_id = _get_attempt_id(stage_info)
+        if attempt_id is not None:
+            data["attemptId"] = attempt_id
+
+        # Have to Try Except because stageInfo.failureReason() is typed with Scala Option
+        try:
+            data["reason"] = stage_info.failureReason().get()
+            message = "Stage {} Failed".format(stage_info.stageId())
+            level = "warning"
+        except Py4JJavaError:
+            message = "Stage {} Completed".format(stage_info.stageId())
+            level = "info"
+
+        self._add_breadcrumb(level=level, message=message, data=data)
+
+
+def _get_attempt_id(stage_info):
+    # type: (Any) -> Optional[int]
+    try:
+        return stage_info.attemptId()
+    except Exception:
+        pass
+
+    try:
+        return stage_info.attemptNumber()
+    except Exception:
+        pass
+
+    return None
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/spark/spark_worker.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/spark/spark_worker.py
new file mode 100644
index 0000000000000000000000000000000000000000..5340a0b3509a1430f770d27960d03a0db7183e89
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/spark/spark_worker.py
@@ -0,0 +1,116 @@
+import sys
+
+import sentry_sdk
+from sentry_sdk.integrations import Integration
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    exc_info_from_error,
+    single_exception_from_error_tuple,
+    walk_exception_chain,
+    event_hint_with_exc_info,
+)
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Optional
+
+    from sentry_sdk._types import ExcInfo, Event, Hint
+
+
+class SparkWorkerIntegration(Integration):
+    identifier = "spark_worker"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        import pyspark.daemon as original_daemon
+
+        original_daemon.worker_main = _sentry_worker_main
+
+
+def _capture_exception(exc_info):
+    # type: (ExcInfo) -> None
+    client = sentry_sdk.get_client()
+
+    mechanism = {"type": "spark", "handled": False}
+
+    exc_info = exc_info_from_error(exc_info)
+
+    exc_type, exc_value, tb = exc_info
+    rv = []
+
+    # On Exception worker will call sys.exit(-1), so we can ignore SystemExit and similar errors
+    for exc_type, exc_value, tb in walk_exception_chain(exc_info):
+        if exc_type not in (SystemExit, EOFError, ConnectionResetError):
+            rv.append(
+                single_exception_from_error_tuple(
+                    exc_type, exc_value, tb, client.options, mechanism
+                )
+            )
+
+    if rv:
+        rv.reverse()
+        hint = event_hint_with_exc_info(exc_info)
+        event = {"level": "error", "exception": {"values": rv}}  # type: Event
+
+        _tag_task_context()
+
+        sentry_sdk.capture_event(event, hint=hint)
+
+
+def _tag_task_context():
+    # type: () -> None
+    from pyspark.taskcontext import TaskContext
+
+    scope = sentry_sdk.get_isolation_scope()
+
+    @scope.add_event_processor
+    def process_event(event, hint):
+        # type: (Event, Hint) -> Optional[Event]
+        with capture_internal_exceptions():
+            integration = sentry_sdk.get_client().get_integration(
+                SparkWorkerIntegration
+            )
+            task_context = TaskContext.get()
+
+            if integration is None or task_context is None:
+                return event
+
+            event.setdefault("tags", {}).setdefault(
+                "stageId", str(task_context.stageId())
+            )
+            event["tags"].setdefault("partitionId", str(task_context.partitionId()))
+            event["tags"].setdefault("attemptNumber", str(task_context.attemptNumber()))
+            event["tags"].setdefault("taskAttemptId", str(task_context.taskAttemptId()))
+
+            if task_context._localProperties:
+                if "sentry_app_name" in task_context._localProperties:
+                    event["tags"].setdefault(
+                        "app_name", task_context._localProperties["sentry_app_name"]
+                    )
+                    event["tags"].setdefault(
+                        "application_id",
+                        task_context._localProperties["sentry_application_id"],
+                    )
+
+                if "callSite.short" in task_context._localProperties:
+                    event.setdefault("extra", {}).setdefault(
+                        "callSite", task_context._localProperties["callSite.short"]
+                    )
+
+        return event
+
+
+def _sentry_worker_main(*args, **kwargs):
+    # type: (*Optional[Any], **Optional[Any]) -> None
+    import pyspark.worker as original_worker
+
+    try:
+        original_worker.main(*args, **kwargs)
+    except SystemExit:
+        if sentry_sdk.get_client().get_integration(SparkWorkerIntegration) is not None:
+            exc_info = sys.exc_info()
+            with capture_internal_exceptions():
+                _capture_exception(exc_info)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/sqlalchemy.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/sqlalchemy.py
new file mode 100644
index 0000000000000000000000000000000000000000..068d373053d5c063af9a7c5b96889a523747d478
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/sqlalchemy.py
@@ -0,0 +1,146 @@
+from sentry_sdk.consts import SPANSTATUS, SPANDATA
+from sentry_sdk.integrations import _check_minimum_version, Integration, DidNotEnable
+from sentry_sdk.tracing_utils import add_query_source, record_sql_queries
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    parse_version,
+)
+
+try:
+    from sqlalchemy.engine import Engine  # type: ignore
+    from sqlalchemy.event import listen  # type: ignore
+    from sqlalchemy import __version__ as SQLALCHEMY_VERSION  # type: ignore
+except ImportError:
+    raise DidNotEnable("SQLAlchemy not installed.")
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import ContextManager
+    from typing import Optional
+
+    from sentry_sdk.tracing import Span
+
+
+class SqlalchemyIntegration(Integration):
+    identifier = "sqlalchemy"
+    origin = f"auto.db.{identifier}"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        version = parse_version(SQLALCHEMY_VERSION)
+        _check_minimum_version(SqlalchemyIntegration, version)
+
+        listen(Engine, "before_cursor_execute", _before_cursor_execute)
+        listen(Engine, "after_cursor_execute", _after_cursor_execute)
+        listen(Engine, "handle_error", _handle_error)
+
+
+@ensure_integration_enabled(SqlalchemyIntegration)
+def _before_cursor_execute(
+    conn, cursor, statement, parameters, context, executemany, *args
+):
+    # type: (Any, Any, Any, Any, Any, bool, *Any) -> None
+    ctx_mgr = record_sql_queries(
+        cursor,
+        statement,
+        parameters,
+        paramstyle=context and context.dialect and context.dialect.paramstyle or None,
+        executemany=executemany,
+        span_origin=SqlalchemyIntegration.origin,
+    )
+    context._sentry_sql_span_manager = ctx_mgr
+
+    span = ctx_mgr.__enter__()
+
+    if span is not None:
+        _set_db_data(span, conn)
+        context._sentry_sql_span = span
+
+
+@ensure_integration_enabled(SqlalchemyIntegration)
+def _after_cursor_execute(conn, cursor, statement, parameters, context, *args):
+    # type: (Any, Any, Any, Any, Any, *Any) -> None
+    ctx_mgr = getattr(
+        context, "_sentry_sql_span_manager", None
+    )  # type: Optional[ContextManager[Any]]
+
+    if ctx_mgr is not None:
+        context._sentry_sql_span_manager = None
+        ctx_mgr.__exit__(None, None, None)
+
+    span = getattr(context, "_sentry_sql_span", None)  # type: Optional[Span]
+    if span is not None:
+        with capture_internal_exceptions():
+            add_query_source(span)
+
+
+def _handle_error(context, *args):
+    # type: (Any, *Any) -> None
+    execution_context = context.execution_context
+    if execution_context is None:
+        return
+
+    span = getattr(execution_context, "_sentry_sql_span", None)  # type: Optional[Span]
+
+    if span is not None:
+        span.set_status(SPANSTATUS.INTERNAL_ERROR)
+
+    # _after_cursor_execute does not get called for crashing SQL stmts. Judging
+    # from SQLAlchemy codebase it does seem like any error coming into this
+    # handler is going to be fatal.
+    ctx_mgr = getattr(
+        execution_context, "_sentry_sql_span_manager", None
+    )  # type: Optional[ContextManager[Any]]
+
+    if ctx_mgr is not None:
+        execution_context._sentry_sql_span_manager = None
+        ctx_mgr.__exit__(None, None, None)
+
+
+# See: https://docs.sqlalchemy.org/en/20/dialects/index.html
+def _get_db_system(name):
+    # type: (str) -> Optional[str]
+    name = str(name)
+
+    if "sqlite" in name:
+        return "sqlite"
+
+    if "postgres" in name:
+        return "postgresql"
+
+    if "mariadb" in name:
+        return "mariadb"
+
+    if "mysql" in name:
+        return "mysql"
+
+    if "oracle" in name:
+        return "oracle"
+
+    return None
+
+
+def _set_db_data(span, conn):
+    # type: (Span, Any) -> None
+    db_system = _get_db_system(conn.engine.name)
+    if db_system is not None:
+        span.set_data(SPANDATA.DB_SYSTEM, db_system)
+
+    if conn.engine.url is None:
+        return
+
+    db_name = conn.engine.url.database
+    if db_name is not None:
+        span.set_data(SPANDATA.DB_NAME, db_name)
+
+    server_address = conn.engine.url.host
+    if server_address is not None:
+        span.set_data(SPANDATA.SERVER_ADDRESS, server_address)
+
+    server_port = conn.engine.url.port
+    if server_port is not None:
+        span.set_data(SPANDATA.SERVER_PORT, server_port)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/starlette.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/starlette.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7ce40618b97a725497c1c9c8fefb0171d5b4a8b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/starlette.py
@@ -0,0 +1,739 @@
+import asyncio
+import functools
+import warnings
+from collections.abc import Set
+from copy import deepcopy
+from json import JSONDecodeError
+
+import sentry_sdk
+from sentry_sdk.consts import OP
+from sentry_sdk.integrations import (
+    DidNotEnable,
+    Integration,
+    _DEFAULT_FAILED_REQUEST_STATUS_CODES,
+)
+from sentry_sdk.integrations._wsgi_common import (
+    DEFAULT_HTTP_METHODS_TO_CAPTURE,
+    HttpCodeRangeContainer,
+    _is_json_content_type,
+    request_body_within_bounds,
+)
+from sentry_sdk.integrations.asgi import SentryAsgiMiddleware
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.tracing import (
+    SOURCE_FOR_STYLE,
+    TransactionSource,
+)
+from sentry_sdk.utils import (
+    AnnotatedValue,
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    event_from_exception,
+    parse_version,
+    transaction_from_function,
+)
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Awaitable, Callable, Container, Dict, Optional, Tuple, Union
+
+    from sentry_sdk._types import Event, HttpStatusCodeRange
+
+try:
+    import starlette  # type: ignore
+    from starlette import __version__ as STARLETTE_VERSION
+    from starlette.applications import Starlette  # type: ignore
+    from starlette.datastructures import UploadFile  # type: ignore
+    from starlette.middleware import Middleware  # type: ignore
+    from starlette.middleware.authentication import (  # type: ignore
+        AuthenticationMiddleware,
+    )
+    from starlette.requests import Request  # type: ignore
+    from starlette.routing import Match  # type: ignore
+    from starlette.types import ASGIApp, Receive, Scope as StarletteScope, Send  # type: ignore
+except ImportError:
+    raise DidNotEnable("Starlette is not installed")
+
+try:
+    # Starlette 0.20
+    from starlette.middleware.exceptions import ExceptionMiddleware  # type: ignore
+except ImportError:
+    # Startlette 0.19.1
+    from starlette.exceptions import ExceptionMiddleware  # type: ignore
+
+try:
+    # Optional dependency of Starlette to parse form data.
+    try:
+        # python-multipart 0.0.13 and later
+        import python_multipart as multipart  # type: ignore
+    except ImportError:
+        # python-multipart 0.0.12 and earlier
+        import multipart  # type: ignore
+except ImportError:
+    multipart = None
+
+
+_DEFAULT_TRANSACTION_NAME = "generic Starlette request"
+
+TRANSACTION_STYLE_VALUES = ("endpoint", "url")
+
+
+class StarletteIntegration(Integration):
+    identifier = "starlette"
+    origin = f"auto.http.{identifier}"
+
+    transaction_style = ""
+
+    def __init__(
+        self,
+        transaction_style="url",  # type: str
+        failed_request_status_codes=_DEFAULT_FAILED_REQUEST_STATUS_CODES,  # type: Union[Set[int], list[HttpStatusCodeRange], None]
+        middleware_spans=True,  # type: bool
+        http_methods_to_capture=DEFAULT_HTTP_METHODS_TO_CAPTURE,  # type: tuple[str, ...]
+    ):
+        # type: (...) -> None
+        if transaction_style not in TRANSACTION_STYLE_VALUES:
+            raise ValueError(
+                "Invalid value for transaction_style: %s (must be in %s)"
+                % (transaction_style, TRANSACTION_STYLE_VALUES)
+            )
+        self.transaction_style = transaction_style
+        self.middleware_spans = middleware_spans
+        self.http_methods_to_capture = tuple(map(str.upper, http_methods_to_capture))
+
+        if isinstance(failed_request_status_codes, Set):
+            self.failed_request_status_codes = (
+                failed_request_status_codes
+            )  # type: Container[int]
+        else:
+            warnings.warn(
+                "Passing a list or None for failed_request_status_codes is deprecated. "
+                "Please pass a set of int instead.",
+                DeprecationWarning,
+                stacklevel=2,
+            )
+
+            if failed_request_status_codes is None:
+                self.failed_request_status_codes = _DEFAULT_FAILED_REQUEST_STATUS_CODES
+            else:
+                self.failed_request_status_codes = HttpCodeRangeContainer(
+                    failed_request_status_codes
+                )
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        version = parse_version(STARLETTE_VERSION)
+
+        if version is None:
+            raise DidNotEnable(
+                "Unparsable Starlette version: {}".format(STARLETTE_VERSION)
+            )
+
+        patch_middlewares()
+        patch_asgi_app()
+        patch_request_response()
+
+        if version >= (0, 24):
+            patch_templates()
+
+
+def _enable_span_for_middleware(middleware_class):
+    # type: (Any) -> type
+    old_call = middleware_class.__call__
+
+    async def _create_span_call(app, scope, receive, send, **kwargs):
+        # type: (Any, Dict[str, Any], Callable[[], Awaitable[Dict[str, Any]]], Callable[[Dict[str, Any]], Awaitable[None]], Any) -> None
+        integration = sentry_sdk.get_client().get_integration(StarletteIntegration)
+        if integration is None or not integration.middleware_spans:
+            return await old_call(app, scope, receive, send, **kwargs)
+
+        middleware_name = app.__class__.__name__
+
+        # Update transaction name with middleware name
+        name, source = _get_transaction_from_middleware(app, scope, integration)
+        if name is not None:
+            sentry_sdk.get_current_scope().set_transaction_name(
+                name,
+                source=source,
+            )
+
+        with sentry_sdk.start_span(
+            op=OP.MIDDLEWARE_STARLETTE,
+            name=middleware_name,
+            origin=StarletteIntegration.origin,
+        ) as middleware_span:
+            middleware_span.set_tag("starlette.middleware_name", middleware_name)
+
+            # Creating spans for the "receive" callback
+            async def _sentry_receive(*args, **kwargs):
+                # type: (*Any, **Any) -> Any
+                with sentry_sdk.start_span(
+                    op=OP.MIDDLEWARE_STARLETTE_RECEIVE,
+                    name=getattr(receive, "__qualname__", str(receive)),
+                    origin=StarletteIntegration.origin,
+                ) as span:
+                    span.set_tag("starlette.middleware_name", middleware_name)
+                    return await receive(*args, **kwargs)
+
+            receive_name = getattr(receive, "__name__", str(receive))
+            receive_patched = receive_name == "_sentry_receive"
+            new_receive = _sentry_receive if not receive_patched else receive
+
+            # Creating spans for the "send" callback
+            async def _sentry_send(*args, **kwargs):
+                # type: (*Any, **Any) -> Any
+                with sentry_sdk.start_span(
+                    op=OP.MIDDLEWARE_STARLETTE_SEND,
+                    name=getattr(send, "__qualname__", str(send)),
+                    origin=StarletteIntegration.origin,
+                ) as span:
+                    span.set_tag("starlette.middleware_name", middleware_name)
+                    return await send(*args, **kwargs)
+
+            send_name = getattr(send, "__name__", str(send))
+            send_patched = send_name == "_sentry_send"
+            new_send = _sentry_send if not send_patched else send
+
+            return await old_call(app, scope, new_receive, new_send, **kwargs)
+
+    not_yet_patched = old_call.__name__ not in [
+        "_create_span_call",
+        "_sentry_authenticationmiddleware_call",
+        "_sentry_exceptionmiddleware_call",
+    ]
+
+    if not_yet_patched:
+        middleware_class.__call__ = _create_span_call
+
+    return middleware_class
+
+
+@ensure_integration_enabled(StarletteIntegration)
+def _capture_exception(exception, handled=False):
+    # type: (BaseException, **Any) -> None
+    event, hint = event_from_exception(
+        exception,
+        client_options=sentry_sdk.get_client().options,
+        mechanism={"type": StarletteIntegration.identifier, "handled": handled},
+    )
+
+    sentry_sdk.capture_event(event, hint=hint)
+
+
+def patch_exception_middleware(middleware_class):
+    # type: (Any) -> None
+    """
+    Capture all exceptions in Starlette app and
+    also extract user information.
+    """
+    old_middleware_init = middleware_class.__init__
+
+    not_yet_patched = "_sentry_middleware_init" not in str(old_middleware_init)
+
+    if not_yet_patched:
+
+        def _sentry_middleware_init(self, *args, **kwargs):
+            # type: (Any, Any, Any) -> None
+            old_middleware_init(self, *args, **kwargs)
+
+            # Patch existing exception handlers
+            old_handlers = self._exception_handlers.copy()
+
+            async def _sentry_patched_exception_handler(self, *args, **kwargs):
+                # type: (Any, Any, Any) -> None
+                integration = sentry_sdk.get_client().get_integration(
+                    StarletteIntegration
+                )
+
+                exp = args[0]
+
+                if integration is not None:
+                    is_http_server_error = (
+                        hasattr(exp, "status_code")
+                        and isinstance(exp.status_code, int)
+                        and exp.status_code in integration.failed_request_status_codes
+                    )
+                    if is_http_server_error:
+                        _capture_exception(exp, handled=True)
+
+                # Find a matching handler
+                old_handler = None
+                for cls in type(exp).__mro__:
+                    if cls in old_handlers:
+                        old_handler = old_handlers[cls]
+                        break
+
+                if old_handler is None:
+                    return
+
+                if _is_async_callable(old_handler):
+                    return await old_handler(self, *args, **kwargs)
+                else:
+                    return old_handler(self, *args, **kwargs)
+
+            for key in self._exception_handlers.keys():
+                self._exception_handlers[key] = _sentry_patched_exception_handler
+
+        middleware_class.__init__ = _sentry_middleware_init
+
+        old_call = middleware_class.__call__
+
+        async def _sentry_exceptionmiddleware_call(self, scope, receive, send):
+            # type: (Dict[str, Any], Dict[str, Any], Callable[[], Awaitable[Dict[str, Any]]], Callable[[Dict[str, Any]], Awaitable[None]]) -> None
+            # Also add the user (that was eventually set by be Authentication middle
+            # that was called before this middleware). This is done because the authentication
+            # middleware sets the user in the scope and then (in the same function)
+            # calls this exception middelware. In case there is no exception (or no handler
+            # for the type of exception occuring) then the exception bubbles up and setting the
+            # user information into the sentry scope is done in auth middleware and the
+            # ASGI middleware will then send everything to Sentry and this is fine.
+            # But if there is an exception happening that the exception middleware here
+            # has a handler for, it will send the exception directly to Sentry, so we need
+            # the user information right now.
+            # This is why we do it here.
+            _add_user_to_sentry_scope(scope)
+            await old_call(self, scope, receive, send)
+
+        middleware_class.__call__ = _sentry_exceptionmiddleware_call
+
+
+@ensure_integration_enabled(StarletteIntegration)
+def _add_user_to_sentry_scope(scope):
+    # type: (Dict[str, Any]) -> None
+    """
+    Extracts user information from the ASGI scope and
+    adds it to Sentry's scope.
+    """
+    if "user" not in scope:
+        return
+
+    if not should_send_default_pii():
+        return
+
+    user_info = {}  # type: Dict[str, Any]
+    starlette_user = scope["user"]
+
+    username = getattr(starlette_user, "username", None)
+    if username:
+        user_info.setdefault("username", starlette_user.username)
+
+    user_id = getattr(starlette_user, "id", None)
+    if user_id:
+        user_info.setdefault("id", starlette_user.id)
+
+    email = getattr(starlette_user, "email", None)
+    if email:
+        user_info.setdefault("email", starlette_user.email)
+
+    sentry_scope = sentry_sdk.get_isolation_scope()
+    sentry_scope.user = user_info
+
+
+def patch_authentication_middleware(middleware_class):
+    # type: (Any) -> None
+    """
+    Add user information to Sentry scope.
+    """
+    old_call = middleware_class.__call__
+
+    not_yet_patched = "_sentry_authenticationmiddleware_call" not in str(old_call)
+
+    if not_yet_patched:
+
+        async def _sentry_authenticationmiddleware_call(self, scope, receive, send):
+            # type: (Dict[str, Any], Dict[str, Any], Callable[[], Awaitable[Dict[str, Any]]], Callable[[Dict[str, Any]], Awaitable[None]]) -> None
+            await old_call(self, scope, receive, send)
+            _add_user_to_sentry_scope(scope)
+
+        middleware_class.__call__ = _sentry_authenticationmiddleware_call
+
+
+def patch_middlewares():
+    # type: () -> None
+    """
+    Patches Starlettes `Middleware` class to record
+    spans for every middleware invoked.
+    """
+    old_middleware_init = Middleware.__init__
+
+    not_yet_patched = "_sentry_middleware_init" not in str(old_middleware_init)
+
+    if not_yet_patched:
+
+        def _sentry_middleware_init(self, cls, *args, **kwargs):
+            # type: (Any, Any, Any, Any) -> None
+            if cls == SentryAsgiMiddleware:
+                return old_middleware_init(self, cls, *args, **kwargs)
+
+            span_enabled_cls = _enable_span_for_middleware(cls)
+            old_middleware_init(self, span_enabled_cls, *args, **kwargs)
+
+            if cls == AuthenticationMiddleware:
+                patch_authentication_middleware(cls)
+
+            if cls == ExceptionMiddleware:
+                patch_exception_middleware(cls)
+
+        Middleware.__init__ = _sentry_middleware_init
+
+
+def patch_asgi_app():
+    # type: () -> None
+    """
+    Instrument Starlette ASGI app using the SentryAsgiMiddleware.
+    """
+    old_app = Starlette.__call__
+
+    async def _sentry_patched_asgi_app(self, scope, receive, send):
+        # type: (Starlette, StarletteScope, Receive, Send) -> None
+        integration = sentry_sdk.get_client().get_integration(StarletteIntegration)
+        if integration is None:
+            return await old_app(self, scope, receive, send)
+
+        middleware = SentryAsgiMiddleware(
+            lambda *a, **kw: old_app(self, *a, **kw),
+            mechanism_type=StarletteIntegration.identifier,
+            transaction_style=integration.transaction_style,
+            span_origin=StarletteIntegration.origin,
+            http_methods_to_capture=(
+                integration.http_methods_to_capture
+                if integration
+                else DEFAULT_HTTP_METHODS_TO_CAPTURE
+            ),
+            asgi_version=3,
+        )
+
+        return await middleware(scope, receive, send)
+
+    Starlette.__call__ = _sentry_patched_asgi_app
+
+
+# This was vendored in from Starlette to support Starlette 0.19.1 because
+# this function was only introduced in 0.20.x
+def _is_async_callable(obj):
+    # type: (Any) -> bool
+    while isinstance(obj, functools.partial):
+        obj = obj.func
+
+    return asyncio.iscoroutinefunction(obj) or (
+        callable(obj) and asyncio.iscoroutinefunction(obj.__call__)
+    )
+
+
+def patch_request_response():
+    # type: () -> None
+    old_request_response = starlette.routing.request_response
+
+    def _sentry_request_response(func):
+        # type: (Callable[[Any], Any]) -> ASGIApp
+        old_func = func
+
+        is_coroutine = _is_async_callable(old_func)
+        if is_coroutine:
+
+            async def _sentry_async_func(*args, **kwargs):
+                # type: (*Any, **Any) -> Any
+                integration = sentry_sdk.get_client().get_integration(
+                    StarletteIntegration
+                )
+                if integration is None:
+                    return await old_func(*args, **kwargs)
+
+                request = args[0]
+
+                _set_transaction_name_and_source(
+                    sentry_sdk.get_current_scope(),
+                    integration.transaction_style,
+                    request,
+                )
+
+                sentry_scope = sentry_sdk.get_isolation_scope()
+                extractor = StarletteRequestExtractor(request)
+                info = await extractor.extract_request_info()
+
+                def _make_request_event_processor(req, integration):
+                    # type: (Any, Any) -> Callable[[Event, dict[str, Any]], Event]
+                    def event_processor(event, hint):
+                        # type: (Event, Dict[str, Any]) -> Event
+
+                        # Add info from request to event
+                        request_info = event.get("request", {})
+                        if info:
+                            if "cookies" in info:
+                                request_info["cookies"] = info["cookies"]
+                            if "data" in info:
+                                request_info["data"] = info["data"]
+                        event["request"] = deepcopy(request_info)
+
+                        return event
+
+                    return event_processor
+
+                sentry_scope._name = StarletteIntegration.identifier
+                sentry_scope.add_event_processor(
+                    _make_request_event_processor(request, integration)
+                )
+
+                return await old_func(*args, **kwargs)
+
+            func = _sentry_async_func
+
+        else:
+
+            @functools.wraps(old_func)
+            def _sentry_sync_func(*args, **kwargs):
+                # type: (*Any, **Any) -> Any
+                integration = sentry_sdk.get_client().get_integration(
+                    StarletteIntegration
+                )
+                if integration is None:
+                    return old_func(*args, **kwargs)
+
+                current_scope = sentry_sdk.get_current_scope()
+                if current_scope.transaction is not None:
+                    current_scope.transaction.update_active_thread()
+
+                sentry_scope = sentry_sdk.get_isolation_scope()
+                if sentry_scope.profile is not None:
+                    sentry_scope.profile.update_active_thread_id()
+
+                request = args[0]
+
+                _set_transaction_name_and_source(
+                    sentry_scope, integration.transaction_style, request
+                )
+
+                extractor = StarletteRequestExtractor(request)
+                cookies = extractor.extract_cookies_from_request()
+
+                def _make_request_event_processor(req, integration):
+                    # type: (Any, Any) -> Callable[[Event, dict[str, Any]], Event]
+                    def event_processor(event, hint):
+                        # type: (Event, dict[str, Any]) -> Event
+
+                        # Extract information from request
+                        request_info = event.get("request", {})
+                        if cookies:
+                            request_info["cookies"] = cookies
+
+                        event["request"] = deepcopy(request_info)
+
+                        return event
+
+                    return event_processor
+
+                sentry_scope._name = StarletteIntegration.identifier
+                sentry_scope.add_event_processor(
+                    _make_request_event_processor(request, integration)
+                )
+
+                return old_func(*args, **kwargs)
+
+            func = _sentry_sync_func
+
+        return old_request_response(func)
+
+    starlette.routing.request_response = _sentry_request_response
+
+
+def patch_templates():
+    # type: () -> None
+
+    # If markupsafe is not installed, then Jinja2 is not installed
+    # (markupsafe is a dependency of Jinja2)
+    # In this case we do not need to patch the Jinja2Templates class
+    try:
+        from markupsafe import Markup
+    except ImportError:
+        return  # Nothing to do
+
+    from starlette.templating import Jinja2Templates  # type: ignore
+
+    old_jinja2templates_init = Jinja2Templates.__init__
+
+    not_yet_patched = "_sentry_jinja2templates_init" not in str(
+        old_jinja2templates_init
+    )
+
+    if not_yet_patched:
+
+        def _sentry_jinja2templates_init(self, *args, **kwargs):
+            # type: (Jinja2Templates, *Any, **Any) -> None
+            def add_sentry_trace_meta(request):
+                # type: (Request) -> Dict[str, Any]
+                trace_meta = Markup(
+                    sentry_sdk.get_current_scope().trace_propagation_meta()
+                )
+                return {
+                    "sentry_trace_meta": trace_meta,
+                }
+
+            kwargs.setdefault("context_processors", [])
+
+            if add_sentry_trace_meta not in kwargs["context_processors"]:
+                kwargs["context_processors"].append(add_sentry_trace_meta)
+
+            return old_jinja2templates_init(self, *args, **kwargs)
+
+        Jinja2Templates.__init__ = _sentry_jinja2templates_init
+
+
+class StarletteRequestExtractor:
+    """
+    Extracts useful information from the Starlette request
+    (like form data or cookies) and adds it to the Sentry event.
+    """
+
+    request = None  # type: Request
+
+    def __init__(self, request):
+        # type: (StarletteRequestExtractor, Request) -> None
+        self.request = request
+
+    def extract_cookies_from_request(self):
+        # type: (StarletteRequestExtractor) -> Optional[Dict[str, Any]]
+        cookies = None  # type: Optional[Dict[str, Any]]
+        if should_send_default_pii():
+            cookies = self.cookies()
+
+        return cookies
+
+    async def extract_request_info(self):
+        # type: (StarletteRequestExtractor) -> Optional[Dict[str, Any]]
+        client = sentry_sdk.get_client()
+
+        request_info = {}  # type: Dict[str, Any]
+
+        with capture_internal_exceptions():
+            # Add cookies
+            if should_send_default_pii():
+                request_info["cookies"] = self.cookies()
+
+            # If there is no body, just return the cookies
+            content_length = await self.content_length()
+            if not content_length:
+                return request_info
+
+            # Add annotation if body is too big
+            if content_length and not request_body_within_bounds(
+                client, content_length
+            ):
+                request_info["data"] = AnnotatedValue.removed_because_over_size_limit()
+                return request_info
+
+            # Add JSON body, if it is a JSON request
+            json = await self.json()
+            if json:
+                request_info["data"] = json
+                return request_info
+
+            # Add form as key/value pairs, if request has form data
+            form = await self.form()
+            if form:
+                form_data = {}
+                for key, val in form.items():
+                    is_file = isinstance(val, UploadFile)
+                    form_data[key] = (
+                        val
+                        if not is_file
+                        else AnnotatedValue.removed_because_raw_data()
+                    )
+
+                request_info["data"] = form_data
+                return request_info
+
+            # Raw data, do not add body just an annotation
+            request_info["data"] = AnnotatedValue.removed_because_raw_data()
+            return request_info
+
+    async def content_length(self):
+        # type: (StarletteRequestExtractor) -> Optional[int]
+        if "content-length" in self.request.headers:
+            return int(self.request.headers["content-length"])
+
+        return None
+
+    def cookies(self):
+        # type: (StarletteRequestExtractor) -> Dict[str, Any]
+        return self.request.cookies
+
+    async def form(self):
+        # type: (StarletteRequestExtractor) -> Any
+        if multipart is None:
+            return None
+
+        # Parse the body first to get it cached, as Starlette does not cache form() as it
+        # does with body() and json() https://github.com/encode/starlette/discussions/1933
+        # Calling `.form()` without calling `.body()` first will
+        # potentially break the users project.
+        await self.request.body()
+
+        return await self.request.form()
+
+    def is_json(self):
+        # type: (StarletteRequestExtractor) -> bool
+        return _is_json_content_type(self.request.headers.get("content-type"))
+
+    async def json(self):
+        # type: (StarletteRequestExtractor) -> Optional[Dict[str, Any]]
+        if not self.is_json():
+            return None
+        try:
+            return await self.request.json()
+        except JSONDecodeError:
+            return None
+
+
+def _transaction_name_from_router(scope):
+    # type: (StarletteScope) -> Optional[str]
+    router = scope.get("router")
+    if not router:
+        return None
+
+    for route in router.routes:
+        match = route.matches(scope)
+        if match[0] == Match.FULL:
+            try:
+                return route.path
+            except AttributeError:
+                # routes added via app.host() won't have a path attribute
+                return scope.get("path")
+
+    return None
+
+
+def _set_transaction_name_and_source(scope, transaction_style, request):
+    # type: (sentry_sdk.Scope, str, Any) -> None
+    name = None
+    source = SOURCE_FOR_STYLE[transaction_style]
+
+    if transaction_style == "endpoint":
+        endpoint = request.scope.get("endpoint")
+        if endpoint:
+            name = transaction_from_function(endpoint) or None
+
+    elif transaction_style == "url":
+        name = _transaction_name_from_router(request.scope)
+
+    if name is None:
+        name = _DEFAULT_TRANSACTION_NAME
+        source = TransactionSource.ROUTE
+
+    scope.set_transaction_name(name, source=source)
+
+
+def _get_transaction_from_middleware(app, asgi_scope, integration):
+    # type: (Any, Dict[str, Any], StarletteIntegration) -> Tuple[Optional[str], Optional[str]]
+    name = None
+    source = None
+
+    if integration.transaction_style == "endpoint":
+        name = transaction_from_function(app.__class__)
+        source = TransactionSource.COMPONENT
+    elif integration.transaction_style == "url":
+        name = _transaction_name_from_router(asgi_scope)
+        source = TransactionSource.ROUTE
+
+    return name, source
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/starlite.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/starlite.py
new file mode 100644
index 0000000000000000000000000000000000000000..b402aa218422ed02c4e50f53ec497d38f3234b33
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/starlite.py
@@ -0,0 +1,292 @@
+import sentry_sdk
+from sentry_sdk.consts import OP
+from sentry_sdk.integrations import DidNotEnable, Integration
+from sentry_sdk.integrations.asgi import SentryAsgiMiddleware
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.tracing import SOURCE_FOR_STYLE, TransactionSource
+from sentry_sdk.utils import (
+    ensure_integration_enabled,
+    event_from_exception,
+    transaction_from_function,
+)
+
+try:
+    from starlite import Request, Starlite, State  # type: ignore
+    from starlite.handlers.base import BaseRouteHandler  # type: ignore
+    from starlite.middleware import DefineMiddleware  # type: ignore
+    from starlite.plugins.base import get_plugin_for_value  # type: ignore
+    from starlite.routes.http import HTTPRoute  # type: ignore
+    from starlite.utils import ConnectionDataExtractor, is_async_callable, Ref  # type: ignore
+    from pydantic import BaseModel  # type: ignore
+except ImportError:
+    raise DidNotEnable("Starlite is not installed")
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Optional, Union
+    from starlite.types import (  # type: ignore
+        ASGIApp,
+        Hint,
+        HTTPReceiveMessage,
+        HTTPScope,
+        Message,
+        Middleware,
+        Receive,
+        Scope as StarliteScope,
+        Send,
+        WebSocketReceiveMessage,
+    )
+    from starlite import MiddlewareProtocol
+    from sentry_sdk._types import Event
+
+
+_DEFAULT_TRANSACTION_NAME = "generic Starlite request"
+
+
+class StarliteIntegration(Integration):
+    identifier = "starlite"
+    origin = f"auto.http.{identifier}"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        patch_app_init()
+        patch_middlewares()
+        patch_http_route_handle()
+
+
+class SentryStarliteASGIMiddleware(SentryAsgiMiddleware):
+    def __init__(self, app, span_origin=StarliteIntegration.origin):
+        # type: (ASGIApp, str) -> None
+        super().__init__(
+            app=app,
+            unsafe_context_data=False,
+            transaction_style="endpoint",
+            mechanism_type="asgi",
+            span_origin=span_origin,
+            asgi_version=3,
+        )
+
+
+def patch_app_init():
+    # type: () -> None
+    """
+    Replaces the Starlite class's `__init__` function in order to inject `after_exception` handlers and set the
+    `SentryStarliteASGIMiddleware` as the outmost middleware in the stack.
+    See:
+    - https://starlite-api.github.io/starlite/usage/0-the-starlite-app/5-application-hooks/#after-exception
+    - https://starlite-api.github.io/starlite/usage/7-middleware/0-middleware-intro/
+    """
+    old__init__ = Starlite.__init__
+
+    @ensure_integration_enabled(StarliteIntegration, old__init__)
+    def injection_wrapper(self, *args, **kwargs):
+        # type: (Starlite, *Any, **Any) -> None
+        after_exception = kwargs.pop("after_exception", [])
+        kwargs.update(
+            after_exception=[
+                exception_handler,
+                *(
+                    after_exception
+                    if isinstance(after_exception, list)
+                    else [after_exception]
+                ),
+            ]
+        )
+
+        middleware = kwargs.get("middleware") or []
+        kwargs["middleware"] = [SentryStarliteASGIMiddleware, *middleware]
+        old__init__(self, *args, **kwargs)
+
+    Starlite.__init__ = injection_wrapper
+
+
+def patch_middlewares():
+    # type: () -> None
+    old_resolve_middleware_stack = BaseRouteHandler.resolve_middleware
+
+    @ensure_integration_enabled(StarliteIntegration, old_resolve_middleware_stack)
+    def resolve_middleware_wrapper(self):
+        # type: (BaseRouteHandler) -> list[Middleware]
+        return [
+            enable_span_for_middleware(middleware)
+            for middleware in old_resolve_middleware_stack(self)
+        ]
+
+    BaseRouteHandler.resolve_middleware = resolve_middleware_wrapper
+
+
+def enable_span_for_middleware(middleware):
+    # type: (Middleware) -> Middleware
+    if (
+        not hasattr(middleware, "__call__")  # noqa: B004
+        or middleware is SentryStarliteASGIMiddleware
+    ):
+        return middleware
+
+    if isinstance(middleware, DefineMiddleware):
+        old_call = middleware.middleware.__call__  # type: ASGIApp
+    else:
+        old_call = middleware.__call__
+
+    async def _create_span_call(self, scope, receive, send):
+        # type: (MiddlewareProtocol, StarliteScope, Receive, Send) -> None
+        if sentry_sdk.get_client().get_integration(StarliteIntegration) is None:
+            return await old_call(self, scope, receive, send)
+
+        middleware_name = self.__class__.__name__
+        with sentry_sdk.start_span(
+            op=OP.MIDDLEWARE_STARLITE,
+            name=middleware_name,
+            origin=StarliteIntegration.origin,
+        ) as middleware_span:
+            middleware_span.set_tag("starlite.middleware_name", middleware_name)
+
+            # Creating spans for the "receive" callback
+            async def _sentry_receive(*args, **kwargs):
+                # type: (*Any, **Any) -> Union[HTTPReceiveMessage, WebSocketReceiveMessage]
+                if sentry_sdk.get_client().get_integration(StarliteIntegration) is None:
+                    return await receive(*args, **kwargs)
+                with sentry_sdk.start_span(
+                    op=OP.MIDDLEWARE_STARLITE_RECEIVE,
+                    name=getattr(receive, "__qualname__", str(receive)),
+                    origin=StarliteIntegration.origin,
+                ) as span:
+                    span.set_tag("starlite.middleware_name", middleware_name)
+                    return await receive(*args, **kwargs)
+
+            receive_name = getattr(receive, "__name__", str(receive))
+            receive_patched = receive_name == "_sentry_receive"
+            new_receive = _sentry_receive if not receive_patched else receive
+
+            # Creating spans for the "send" callback
+            async def _sentry_send(message):
+                # type: (Message) -> None
+                if sentry_sdk.get_client().get_integration(StarliteIntegration) is None:
+                    return await send(message)
+                with sentry_sdk.start_span(
+                    op=OP.MIDDLEWARE_STARLITE_SEND,
+                    name=getattr(send, "__qualname__", str(send)),
+                    origin=StarliteIntegration.origin,
+                ) as span:
+                    span.set_tag("starlite.middleware_name", middleware_name)
+                    return await send(message)
+
+            send_name = getattr(send, "__name__", str(send))
+            send_patched = send_name == "_sentry_send"
+            new_send = _sentry_send if not send_patched else send
+
+            return await old_call(self, scope, new_receive, new_send)
+
+    not_yet_patched = old_call.__name__ not in ["_create_span_call"]
+
+    if not_yet_patched:
+        if isinstance(middleware, DefineMiddleware):
+            middleware.middleware.__call__ = _create_span_call
+        else:
+            middleware.__call__ = _create_span_call
+
+    return middleware
+
+
+def patch_http_route_handle():
+    # type: () -> None
+    old_handle = HTTPRoute.handle
+
+    async def handle_wrapper(self, scope, receive, send):
+        # type: (HTTPRoute, HTTPScope, Receive, Send) -> None
+        if sentry_sdk.get_client().get_integration(StarliteIntegration) is None:
+            return await old_handle(self, scope, receive, send)
+
+        sentry_scope = sentry_sdk.get_isolation_scope()
+        request = scope["app"].request_class(
+            scope=scope, receive=receive, send=send
+        )  # type: Request[Any, Any]
+        extracted_request_data = ConnectionDataExtractor(
+            parse_body=True, parse_query=True
+        )(request)
+        body = extracted_request_data.pop("body")
+
+        request_data = await body
+
+        def event_processor(event, _):
+            # type: (Event, Hint) -> Event
+            route_handler = scope.get("route_handler")
+
+            request_info = event.get("request", {})
+            request_info["content_length"] = len(scope.get("_body", b""))
+            if should_send_default_pii():
+                request_info["cookies"] = extracted_request_data["cookies"]
+            if request_data is not None:
+                request_info["data"] = request_data
+
+            func = None
+            if route_handler.name is not None:
+                tx_name = route_handler.name
+            elif isinstance(route_handler.fn, Ref):
+                func = route_handler.fn.value
+            else:
+                func = route_handler.fn
+            if func is not None:
+                tx_name = transaction_from_function(func)
+
+            tx_info = {"source": SOURCE_FOR_STYLE["endpoint"]}
+
+            if not tx_name:
+                tx_name = _DEFAULT_TRANSACTION_NAME
+                tx_info = {"source": TransactionSource.ROUTE}
+
+            event.update(
+                {
+                    "request": request_info,
+                    "transaction": tx_name,
+                    "transaction_info": tx_info,
+                }
+            )
+            return event
+
+        sentry_scope._name = StarliteIntegration.identifier
+        sentry_scope.add_event_processor(event_processor)
+
+        return await old_handle(self, scope, receive, send)
+
+    HTTPRoute.handle = handle_wrapper
+
+
+def retrieve_user_from_scope(scope):
+    # type: (StarliteScope) -> Optional[dict[str, Any]]
+    scope_user = scope.get("user")
+    if not scope_user:
+        return None
+    if isinstance(scope_user, dict):
+        return scope_user
+    if isinstance(scope_user, BaseModel):
+        return scope_user.dict()
+    if hasattr(scope_user, "asdict"):  # dataclasses
+        return scope_user.asdict()
+
+    plugin = get_plugin_for_value(scope_user)
+    if plugin and not is_async_callable(plugin.to_dict):
+        return plugin.to_dict(scope_user)
+
+    return None
+
+
+@ensure_integration_enabled(StarliteIntegration)
+def exception_handler(exc, scope, _):
+    # type: (Exception, StarliteScope, State) -> None
+    user_info = None  # type: Optional[dict[str, Any]]
+    if should_send_default_pii():
+        user_info = retrieve_user_from_scope(scope)
+    if user_info and isinstance(user_info, dict):
+        sentry_scope = sentry_sdk.get_isolation_scope()
+        sentry_scope.set_user(user_info)
+
+    event, hint = event_from_exception(
+        exc,
+        client_options=sentry_sdk.get_client().options,
+        mechanism={"type": StarliteIntegration.identifier, "handled": False},
+    )
+
+    sentry_sdk.capture_event(event, hint=hint)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/statsig.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/statsig.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d84eb8aa2db3ed71714c7623760da77a43ec4af
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/statsig.py
@@ -0,0 +1,37 @@
+from functools import wraps
+from typing import Any, TYPE_CHECKING
+
+from sentry_sdk.feature_flags import add_feature_flag
+from sentry_sdk.integrations import Integration, DidNotEnable, _check_minimum_version
+from sentry_sdk.utils import parse_version
+
+try:
+    from statsig import statsig as statsig_module
+    from statsig.version import __version__ as STATSIG_VERSION
+except ImportError:
+    raise DidNotEnable("statsig is not installed")
+
+if TYPE_CHECKING:
+    from statsig.statsig_user import StatsigUser
+
+
+class StatsigIntegration(Integration):
+    identifier = "statsig"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        version = parse_version(STATSIG_VERSION)
+        _check_minimum_version(StatsigIntegration, version, "statsig")
+
+        # Wrap and patch evaluation method(s) in the statsig module
+        old_check_gate = statsig_module.check_gate
+
+        @wraps(old_check_gate)
+        def sentry_check_gate(user, gate, *args, **kwargs):
+            # type: (StatsigUser, str, *Any, **Any) -> Any
+            enabled = old_check_gate(user, gate, *args, **kwargs)
+            add_feature_flag(gate, enabled)
+            return enabled
+
+        statsig_module.check_gate = sentry_check_gate
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/stdlib.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/stdlib.py
new file mode 100644
index 0000000000000000000000000000000000000000..d388c5bca67f2147c51214908706c2e9cdaae041
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/stdlib.py
@@ -0,0 +1,265 @@
+import os
+import subprocess
+import sys
+import platform
+from http.client import HTTPConnection
+
+import sentry_sdk
+from sentry_sdk.consts import OP, SPANDATA
+from sentry_sdk.integrations import Integration
+from sentry_sdk.scope import add_global_event_processor
+from sentry_sdk.tracing_utils import EnvironHeaders, should_propagate_trace
+from sentry_sdk.utils import (
+    SENSITIVE_DATA_SUBSTITUTE,
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    is_sentry_url,
+    logger,
+    safe_repr,
+    parse_url,
+)
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Callable
+    from typing import Dict
+    from typing import Optional
+    from typing import List
+
+    from sentry_sdk._types import Event, Hint
+
+
+_RUNTIME_CONTEXT = {
+    "name": platform.python_implementation(),
+    "version": "%s.%s.%s" % (sys.version_info[:3]),
+    "build": sys.version,
+}  # type: dict[str, object]
+
+
+class StdlibIntegration(Integration):
+    identifier = "stdlib"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        _install_httplib()
+        _install_subprocess()
+
+        @add_global_event_processor
+        def add_python_runtime_context(event, hint):
+            # type: (Event, Hint) -> Optional[Event]
+            if sentry_sdk.get_client().get_integration(StdlibIntegration) is not None:
+                contexts = event.setdefault("contexts", {})
+                if isinstance(contexts, dict) and "runtime" not in contexts:
+                    contexts["runtime"] = _RUNTIME_CONTEXT
+
+            return event
+
+
+def _install_httplib():
+    # type: () -> None
+    real_putrequest = HTTPConnection.putrequest
+    real_getresponse = HTTPConnection.getresponse
+
+    def putrequest(self, method, url, *args, **kwargs):
+        # type: (HTTPConnection, str, str, *Any, **Any) -> Any
+        host = self.host
+        port = self.port
+        default_port = self.default_port
+
+        client = sentry_sdk.get_client()
+        if client.get_integration(StdlibIntegration) is None or is_sentry_url(
+            client, host
+        ):
+            return real_putrequest(self, method, url, *args, **kwargs)
+
+        real_url = url
+        if real_url is None or not real_url.startswith(("http://", "https://")):
+            real_url = "%s://%s%s%s" % (
+                default_port == 443 and "https" or "http",
+                host,
+                port != default_port and ":%s" % port or "",
+                url,
+            )
+
+        parsed_url = None
+        with capture_internal_exceptions():
+            parsed_url = parse_url(real_url, sanitize=False)
+
+        span = sentry_sdk.start_span(
+            op=OP.HTTP_CLIENT,
+            name="%s %s"
+            % (method, parsed_url.url if parsed_url else SENSITIVE_DATA_SUBSTITUTE),
+            origin="auto.http.stdlib.httplib",
+        )
+        span.set_data(SPANDATA.HTTP_METHOD, method)
+        if parsed_url is not None:
+            span.set_data("url", parsed_url.url)
+            span.set_data(SPANDATA.HTTP_QUERY, parsed_url.query)
+            span.set_data(SPANDATA.HTTP_FRAGMENT, parsed_url.fragment)
+
+        rv = real_putrequest(self, method, url, *args, **kwargs)
+
+        if should_propagate_trace(client, real_url):
+            for (
+                key,
+                value,
+            ) in sentry_sdk.get_current_scope().iter_trace_propagation_headers(
+                span=span
+            ):
+                logger.debug(
+                    "[Tracing] Adding `{key}` header {value} to outgoing request to {real_url}.".format(
+                        key=key, value=value, real_url=real_url
+                    )
+                )
+                self.putheader(key, value)
+
+        self._sentrysdk_span = span  # type: ignore[attr-defined]
+
+        return rv
+
+    def getresponse(self, *args, **kwargs):
+        # type: (HTTPConnection, *Any, **Any) -> Any
+        span = getattr(self, "_sentrysdk_span", None)
+
+        if span is None:
+            return real_getresponse(self, *args, **kwargs)
+
+        try:
+            rv = real_getresponse(self, *args, **kwargs)
+
+            span.set_http_status(int(rv.status))
+            span.set_data("reason", rv.reason)
+        finally:
+            span.finish()
+
+        return rv
+
+    HTTPConnection.putrequest = putrequest  # type: ignore[method-assign]
+    HTTPConnection.getresponse = getresponse  # type: ignore[method-assign]
+
+
+def _init_argument(args, kwargs, name, position, setdefault_callback=None):
+    # type: (List[Any], Dict[Any, Any], str, int, Optional[Callable[[Any], Any]]) -> Any
+    """
+    given (*args, **kwargs) of a function call, retrieve (and optionally set a
+    default for) an argument by either name or position.
+
+    This is useful for wrapping functions with complex type signatures and
+    extracting a few arguments without needing to redefine that function's
+    entire type signature.
+    """
+
+    if name in kwargs:
+        rv = kwargs[name]
+        if setdefault_callback is not None:
+            rv = setdefault_callback(rv)
+        if rv is not None:
+            kwargs[name] = rv
+    elif position < len(args):
+        rv = args[position]
+        if setdefault_callback is not None:
+            rv = setdefault_callback(rv)
+        if rv is not None:
+            args[position] = rv
+    else:
+        rv = setdefault_callback and setdefault_callback(None)
+        if rv is not None:
+            kwargs[name] = rv
+
+    return rv
+
+
+def _install_subprocess():
+    # type: () -> None
+    old_popen_init = subprocess.Popen.__init__
+
+    @ensure_integration_enabled(StdlibIntegration, old_popen_init)
+    def sentry_patched_popen_init(self, *a, **kw):
+        # type: (subprocess.Popen[Any], *Any, **Any) -> None
+        # Convert from tuple to list to be able to set values.
+        a = list(a)
+
+        args = _init_argument(a, kw, "args", 0) or []
+        cwd = _init_argument(a, kw, "cwd", 9)
+
+        # if args is not a list or tuple (and e.g. some iterator instead),
+        # let's not use it at all. There are too many things that can go wrong
+        # when trying to collect an iterator into a list and setting that list
+        # into `a` again.
+        #
+        # Also invocations where `args` is not a sequence are not actually
+        # legal. They just happen to work under CPython.
+        description = None
+
+        if isinstance(args, (list, tuple)) and len(args) < 100:
+            with capture_internal_exceptions():
+                description = " ".join(map(str, args))
+
+        if description is None:
+            description = safe_repr(args)
+
+        env = None
+
+        with sentry_sdk.start_span(
+            op=OP.SUBPROCESS,
+            name=description,
+            origin="auto.subprocess.stdlib.subprocess",
+        ) as span:
+            for k, v in sentry_sdk.get_current_scope().iter_trace_propagation_headers(
+                span=span
+            ):
+                if env is None:
+                    env = _init_argument(
+                        a,
+                        kw,
+                        "env",
+                        10,
+                        lambda x: dict(x if x is not None else os.environ),
+                    )
+                env["SUBPROCESS_" + k.upper().replace("-", "_")] = v
+
+            if cwd:
+                span.set_data("subprocess.cwd", cwd)
+
+            rv = old_popen_init(self, *a, **kw)
+
+            span.set_tag("subprocess.pid", self.pid)
+            return rv
+
+    subprocess.Popen.__init__ = sentry_patched_popen_init  # type: ignore
+
+    old_popen_wait = subprocess.Popen.wait
+
+    @ensure_integration_enabled(StdlibIntegration, old_popen_wait)
+    def sentry_patched_popen_wait(self, *a, **kw):
+        # type: (subprocess.Popen[Any], *Any, **Any) -> Any
+        with sentry_sdk.start_span(
+            op=OP.SUBPROCESS_WAIT,
+            origin="auto.subprocess.stdlib.subprocess",
+        ) as span:
+            span.set_tag("subprocess.pid", self.pid)
+            return old_popen_wait(self, *a, **kw)
+
+    subprocess.Popen.wait = sentry_patched_popen_wait  # type: ignore
+
+    old_popen_communicate = subprocess.Popen.communicate
+
+    @ensure_integration_enabled(StdlibIntegration, old_popen_communicate)
+    def sentry_patched_popen_communicate(self, *a, **kw):
+        # type: (subprocess.Popen[Any], *Any, **Any) -> Any
+        with sentry_sdk.start_span(
+            op=OP.SUBPROCESS_COMMUNICATE,
+            origin="auto.subprocess.stdlib.subprocess",
+        ) as span:
+            span.set_tag("subprocess.pid", self.pid)
+            return old_popen_communicate(self, *a, **kw)
+
+    subprocess.Popen.communicate = sentry_patched_popen_communicate  # type: ignore
+
+
+def get_subprocess_traceparent_headers():
+    # type: () -> EnvironHeaders
+    return EnvironHeaders(os.environ, prefix="SUBPROCESS_")
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/strawberry.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/strawberry.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae7d273079096a3f06b72e34d16dcc111191a572
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/strawberry.py
@@ -0,0 +1,393 @@
+import functools
+import hashlib
+from inspect import isawaitable
+
+import sentry_sdk
+from sentry_sdk.consts import OP
+from sentry_sdk.integrations import _check_minimum_version, Integration, DidNotEnable
+from sentry_sdk.integrations.logging import ignore_logger
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.tracing import TransactionSource
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    ensure_integration_enabled,
+    event_from_exception,
+    logger,
+    package_version,
+    _get_installed_modules,
+)
+
+try:
+    from functools import cached_property
+except ImportError:
+    # The strawberry integration requires Python 3.8+. functools.cached_property
+    # was added in 3.8, so this check is technically not needed, but since this
+    # is an auto-enabling integration, we might get to executing this import in
+    # lower Python versions, so we need to deal with it.
+    raise DidNotEnable("strawberry-graphql integration requires Python 3.8 or newer")
+
+try:
+    from strawberry import Schema
+    from strawberry.extensions import SchemaExtension
+    from strawberry.extensions.tracing.utils import (
+        should_skip_tracing as strawberry_should_skip_tracing,
+    )
+    from strawberry.http import async_base_view, sync_base_view
+except ImportError:
+    raise DidNotEnable("strawberry-graphql is not installed")
+
+try:
+    from strawberry.extensions.tracing import (
+        SentryTracingExtension as StrawberrySentryAsyncExtension,
+        SentryTracingExtensionSync as StrawberrySentrySyncExtension,
+    )
+except ImportError:
+    StrawberrySentryAsyncExtension = None
+    StrawberrySentrySyncExtension = None
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any, Callable, Generator, List, Optional
+    from graphql import GraphQLError, GraphQLResolveInfo
+    from strawberry.http import GraphQLHTTPResponse
+    from strawberry.types import ExecutionContext
+    from sentry_sdk._types import Event, EventProcessor
+
+
+ignore_logger("strawberry.execution")
+
+
+class StrawberryIntegration(Integration):
+    identifier = "strawberry"
+    origin = f"auto.graphql.{identifier}"
+
+    def __init__(self, async_execution=None):
+        # type: (Optional[bool]) -> None
+        if async_execution not in (None, False, True):
+            raise ValueError(
+                'Invalid value for async_execution: "{}" (must be bool)'.format(
+                    async_execution
+                )
+            )
+        self.async_execution = async_execution
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        version = package_version("strawberry-graphql")
+        _check_minimum_version(StrawberryIntegration, version, "strawberry-graphql")
+
+        _patch_schema_init()
+        _patch_views()
+
+
+def _patch_schema_init():
+    # type: () -> None
+    old_schema_init = Schema.__init__
+
+    @functools.wraps(old_schema_init)
+    def _sentry_patched_schema_init(self, *args, **kwargs):
+        # type: (Schema, Any, Any) -> None
+        integration = sentry_sdk.get_client().get_integration(StrawberryIntegration)
+        if integration is None:
+            return old_schema_init(self, *args, **kwargs)
+
+        extensions = kwargs.get("extensions") or []
+
+        if integration.async_execution is not None:
+            should_use_async_extension = integration.async_execution
+        else:
+            # try to figure it out ourselves
+            should_use_async_extension = _guess_if_using_async(extensions)
+
+            logger.info(
+                "Assuming strawberry is running %s. If not, initialize it as StrawberryIntegration(async_execution=%s).",
+                "async" if should_use_async_extension else "sync",
+                "False" if should_use_async_extension else "True",
+            )
+
+        # remove the built in strawberry sentry extension, if present
+        extensions = [
+            extension
+            for extension in extensions
+            if extension
+            not in (StrawberrySentryAsyncExtension, StrawberrySentrySyncExtension)
+        ]
+
+        # add our extension
+        extensions.append(
+            SentryAsyncExtension if should_use_async_extension else SentrySyncExtension
+        )
+
+        kwargs["extensions"] = extensions
+
+        return old_schema_init(self, *args, **kwargs)
+
+    Schema.__init__ = _sentry_patched_schema_init  # type: ignore[method-assign]
+
+
+class SentryAsyncExtension(SchemaExtension):
+    def __init__(
+        self,
+        *,
+        execution_context=None,
+    ):
+        # type: (Any, Optional[ExecutionContext]) -> None
+        if execution_context:
+            self.execution_context = execution_context
+
+    @cached_property
+    def _resource_name(self):
+        # type: () -> str
+        query_hash = self.hash_query(self.execution_context.query)  # type: ignore
+
+        if self.execution_context.operation_name:
+            return "{}:{}".format(self.execution_context.operation_name, query_hash)
+
+        return query_hash
+
+    def hash_query(self, query):
+        # type: (str) -> str
+        return hashlib.md5(query.encode("utf-8")).hexdigest()
+
+    def on_operation(self):
+        # type: () -> Generator[None, None, None]
+        self._operation_name = self.execution_context.operation_name
+
+        operation_type = "query"
+        op = OP.GRAPHQL_QUERY
+
+        if self.execution_context.query is None:
+            self.execution_context.query = ""
+
+        if self.execution_context.query.strip().startswith("mutation"):
+            operation_type = "mutation"
+            op = OP.GRAPHQL_MUTATION
+        elif self.execution_context.query.strip().startswith("subscription"):
+            operation_type = "subscription"
+            op = OP.GRAPHQL_SUBSCRIPTION
+
+        description = operation_type
+        if self._operation_name:
+            description += " {}".format(self._operation_name)
+
+        sentry_sdk.add_breadcrumb(
+            category="graphql.operation",
+            data={
+                "operation_name": self._operation_name,
+                "operation_type": operation_type,
+            },
+        )
+
+        scope = sentry_sdk.get_isolation_scope()
+        event_processor = _make_request_event_processor(self.execution_context)
+        scope.add_event_processor(event_processor)
+
+        span = sentry_sdk.get_current_span()
+        if span:
+            self.graphql_span = span.start_child(
+                op=op,
+                name=description,
+                origin=StrawberryIntegration.origin,
+            )
+        else:
+            self.graphql_span = sentry_sdk.start_span(
+                op=op,
+                name=description,
+                origin=StrawberryIntegration.origin,
+            )
+
+        self.graphql_span.set_data("graphql.operation.type", operation_type)
+        self.graphql_span.set_data("graphql.operation.name", self._operation_name)
+        self.graphql_span.set_data("graphql.document", self.execution_context.query)
+        self.graphql_span.set_data("graphql.resource_name", self._resource_name)
+
+        yield
+
+        transaction = self.graphql_span.containing_transaction
+        if transaction and self.execution_context.operation_name:
+            transaction.name = self.execution_context.operation_name
+            transaction.source = TransactionSource.COMPONENT
+            transaction.op = op
+
+        self.graphql_span.finish()
+
+    def on_validate(self):
+        # type: () -> Generator[None, None, None]
+        self.validation_span = self.graphql_span.start_child(
+            op=OP.GRAPHQL_VALIDATE,
+            name="validation",
+            origin=StrawberryIntegration.origin,
+        )
+
+        yield
+
+        self.validation_span.finish()
+
+    def on_parse(self):
+        # type: () -> Generator[None, None, None]
+        self.parsing_span = self.graphql_span.start_child(
+            op=OP.GRAPHQL_PARSE,
+            name="parsing",
+            origin=StrawberryIntegration.origin,
+        )
+
+        yield
+
+        self.parsing_span.finish()
+
+    def should_skip_tracing(self, _next, info):
+        # type: (Callable[[Any, GraphQLResolveInfo, Any, Any], Any], GraphQLResolveInfo) -> bool
+        return strawberry_should_skip_tracing(_next, info)
+
+    async def _resolve(self, _next, root, info, *args, **kwargs):
+        # type: (Callable[[Any, GraphQLResolveInfo, Any, Any], Any], Any, GraphQLResolveInfo, str, Any) -> Any
+        result = _next(root, info, *args, **kwargs)
+
+        if isawaitable(result):
+            result = await result
+
+        return result
+
+    async def resolve(self, _next, root, info, *args, **kwargs):
+        # type: (Callable[[Any, GraphQLResolveInfo, Any, Any], Any], Any, GraphQLResolveInfo, str, Any) -> Any
+        if self.should_skip_tracing(_next, info):
+            return await self._resolve(_next, root, info, *args, **kwargs)
+
+        field_path = "{}.{}".format(info.parent_type, info.field_name)
+
+        with self.graphql_span.start_child(
+            op=OP.GRAPHQL_RESOLVE,
+            name="resolving {}".format(field_path),
+            origin=StrawberryIntegration.origin,
+        ) as span:
+            span.set_data("graphql.field_name", info.field_name)
+            span.set_data("graphql.parent_type", info.parent_type.name)
+            span.set_data("graphql.field_path", field_path)
+            span.set_data("graphql.path", ".".join(map(str, info.path.as_list())))
+
+            return await self._resolve(_next, root, info, *args, **kwargs)
+
+
+class SentrySyncExtension(SentryAsyncExtension):
+    def resolve(self, _next, root, info, *args, **kwargs):
+        # type: (Callable[[Any, Any, Any, Any], Any], Any, GraphQLResolveInfo, str, Any) -> Any
+        if self.should_skip_tracing(_next, info):
+            return _next(root, info, *args, **kwargs)
+
+        field_path = "{}.{}".format(info.parent_type, info.field_name)
+
+        with self.graphql_span.start_child(
+            op=OP.GRAPHQL_RESOLVE,
+            name="resolving {}".format(field_path),
+            origin=StrawberryIntegration.origin,
+        ) as span:
+            span.set_data("graphql.field_name", info.field_name)
+            span.set_data("graphql.parent_type", info.parent_type.name)
+            span.set_data("graphql.field_path", field_path)
+            span.set_data("graphql.path", ".".join(map(str, info.path.as_list())))
+
+            return _next(root, info, *args, **kwargs)
+
+
+def _patch_views():
+    # type: () -> None
+    old_async_view_handle_errors = async_base_view.AsyncBaseHTTPView._handle_errors
+    old_sync_view_handle_errors = sync_base_view.SyncBaseHTTPView._handle_errors
+
+    def _sentry_patched_async_view_handle_errors(self, errors, response_data):
+        # type: (Any, List[GraphQLError], GraphQLHTTPResponse) -> None
+        old_async_view_handle_errors(self, errors, response_data)
+        _sentry_patched_handle_errors(self, errors, response_data)
+
+    def _sentry_patched_sync_view_handle_errors(self, errors, response_data):
+        # type: (Any, List[GraphQLError], GraphQLHTTPResponse) -> None
+        old_sync_view_handle_errors(self, errors, response_data)
+        _sentry_patched_handle_errors(self, errors, response_data)
+
+    @ensure_integration_enabled(StrawberryIntegration)
+    def _sentry_patched_handle_errors(self, errors, response_data):
+        # type: (Any, List[GraphQLError], GraphQLHTTPResponse) -> None
+        if not errors:
+            return
+
+        scope = sentry_sdk.get_isolation_scope()
+        event_processor = _make_response_event_processor(response_data)
+        scope.add_event_processor(event_processor)
+
+        with capture_internal_exceptions():
+            for error in errors:
+                event, hint = event_from_exception(
+                    error,
+                    client_options=sentry_sdk.get_client().options,
+                    mechanism={
+                        "type": StrawberryIntegration.identifier,
+                        "handled": False,
+                    },
+                )
+                sentry_sdk.capture_event(event, hint=hint)
+
+    async_base_view.AsyncBaseHTTPView._handle_errors = (  # type: ignore[method-assign]
+        _sentry_patched_async_view_handle_errors
+    )
+    sync_base_view.SyncBaseHTTPView._handle_errors = (  # type: ignore[method-assign]
+        _sentry_patched_sync_view_handle_errors
+    )
+
+
+def _make_request_event_processor(execution_context):
+    # type: (ExecutionContext) -> EventProcessor
+
+    def inner(event, hint):
+        # type: (Event, dict[str, Any]) -> Event
+        with capture_internal_exceptions():
+            if should_send_default_pii():
+                request_data = event.setdefault("request", {})
+                request_data["api_target"] = "graphql"
+
+                if not request_data.get("data"):
+                    data = {"query": execution_context.query}  # type: dict[str, Any]
+                    if execution_context.variables:
+                        data["variables"] = execution_context.variables
+                    if execution_context.operation_name:
+                        data["operationName"] = execution_context.operation_name
+
+                    request_data["data"] = data
+
+            else:
+                try:
+                    del event["request"]["data"]
+                except (KeyError, TypeError):
+                    pass
+
+        return event
+
+    return inner
+
+
+def _make_response_event_processor(response_data):
+    # type: (GraphQLHTTPResponse) -> EventProcessor
+
+    def inner(event, hint):
+        # type: (Event, dict[str, Any]) -> Event
+        with capture_internal_exceptions():
+            if should_send_default_pii():
+                contexts = event.setdefault("contexts", {})
+                contexts["response"] = {"data": response_data}
+
+        return event
+
+    return inner
+
+
+def _guess_if_using_async(extensions):
+    # type: (List[SchemaExtension]) -> bool
+    if StrawberrySentryAsyncExtension in extensions:
+        return True
+    elif StrawberrySentrySyncExtension in extensions:
+        return False
+
+    return bool(
+        {"starlette", "starlite", "litestar", "fastapi"} & set(_get_installed_modules())
+    )
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/sys_exit.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/sys_exit.py
new file mode 100644
index 0000000000000000000000000000000000000000..2341e11359114ba6628c4c712d53e97e87ccd8be
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/sys_exit.py
@@ -0,0 +1,70 @@
+import functools
+import sys
+
+import sentry_sdk
+from sentry_sdk.utils import capture_internal_exceptions, event_from_exception
+from sentry_sdk.integrations import Integration
+from sentry_sdk._types import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from collections.abc import Callable
+    from typing import NoReturn, Union
+
+
+class SysExitIntegration(Integration):
+    """Captures sys.exit calls and sends them as events to Sentry.
+
+    By default, SystemExit exceptions are not captured by the SDK. Enabling this integration will capture SystemExit
+    exceptions generated by sys.exit calls and send them to Sentry.
+
+    This integration, in its default configuration, only captures the sys.exit call if the exit code is a non-zero and
+    non-None value (unsuccessful exits). Pass `capture_successful_exits=True` to capture successful exits as well.
+    Note that the integration does not capture SystemExit exceptions raised outside a call to sys.exit.
+    """
+
+    identifier = "sys_exit"
+
+    def __init__(self, *, capture_successful_exits=False):
+        # type: (bool) -> None
+        self._capture_successful_exits = capture_successful_exits
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        SysExitIntegration._patch_sys_exit()
+
+    @staticmethod
+    def _patch_sys_exit():
+        # type: () -> None
+        old_exit = sys.exit  # type: Callable[[Union[str, int, None]], NoReturn]
+
+        @functools.wraps(old_exit)
+        def sentry_patched_exit(__status=0):
+            # type: (Union[str, int, None]) -> NoReturn
+            # @ensure_integration_enabled ensures that this is non-None
+            integration = sentry_sdk.get_client().get_integration(SysExitIntegration)
+            if integration is None:
+                old_exit(__status)
+
+            try:
+                old_exit(__status)
+            except SystemExit as e:
+                with capture_internal_exceptions():
+                    if integration._capture_successful_exits or __status not in (
+                        0,
+                        None,
+                    ):
+                        _capture_exception(e)
+                raise e
+
+        sys.exit = sentry_patched_exit
+
+
+def _capture_exception(exc):
+    # type: (SystemExit) -> None
+    event, hint = event_from_exception(
+        exc,
+        client_options=sentry_sdk.get_client().options,
+        mechanism={"type": SysExitIntegration.identifier, "handled": False},
+    )
+    sentry_sdk.capture_event(event, hint=hint)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/threading.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/threading.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc4f539228d8ecc75e575e10912bb05ecb27e5f7
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/threading.py
@@ -0,0 +1,150 @@
+import sys
+import warnings
+from functools import wraps
+from threading import Thread, current_thread
+
+import sentry_sdk
+from sentry_sdk.integrations import Integration
+from sentry_sdk.scope import use_isolation_scope, use_scope
+from sentry_sdk.utils import (
+    event_from_exception,
+    capture_internal_exceptions,
+    logger,
+    reraise,
+)
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import TypeVar
+    from typing import Callable
+    from typing import Optional
+
+    from sentry_sdk._types import ExcInfo
+
+    F = TypeVar("F", bound=Callable[..., Any])
+
+
+class ThreadingIntegration(Integration):
+    identifier = "threading"
+
+    def __init__(self, propagate_hub=None, propagate_scope=True):
+        # type: (Optional[bool], bool) -> None
+        if propagate_hub is not None:
+            logger.warning(
+                "Deprecated: propagate_hub is deprecated. This will be removed in the future."
+            )
+
+        # Note: propagate_hub did not have any effect on propagation of scope data
+        # scope data was always propagated no matter what the value of propagate_hub was
+        # This is why the default for propagate_scope is True
+
+        self.propagate_scope = propagate_scope
+
+        if propagate_hub is not None:
+            self.propagate_scope = propagate_hub
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        old_start = Thread.start
+
+        try:
+            from django import VERSION as django_version  # noqa: N811
+            import channels  # type: ignore[import-not-found]
+
+            channels_version = channels.__version__
+        except ImportError:
+            django_version = None
+            channels_version = None
+
+        @wraps(old_start)
+        def sentry_start(self, *a, **kw):
+            # type: (Thread, *Any, **Any) -> Any
+            integration = sentry_sdk.get_client().get_integration(ThreadingIntegration)
+            if integration is None:
+                return old_start(self, *a, **kw)
+
+            if integration.propagate_scope:
+                if (
+                    sys.version_info < (3, 9)
+                    and channels_version is not None
+                    and channels_version < "4.0.0"
+                    and django_version is not None
+                    and django_version >= (3, 0)
+                    and django_version < (4, 0)
+                ):
+                    warnings.warn(
+                        "There is a known issue with Django channels 2.x and 3.x when using Python 3.8 or older. "
+                        "(Async support is emulated using threads and some Sentry data may be leaked between those threads.) "
+                        "Please either upgrade to Django channels 4.0+, use Django's async features "
+                        "available in Django 3.1+ instead of Django channels, or upgrade to Python 3.9+.",
+                        stacklevel=2,
+                    )
+                    isolation_scope = sentry_sdk.get_isolation_scope()
+                    current_scope = sentry_sdk.get_current_scope()
+
+                else:
+                    isolation_scope = sentry_sdk.get_isolation_scope().fork()
+                    current_scope = sentry_sdk.get_current_scope().fork()
+            else:
+                isolation_scope = None
+                current_scope = None
+
+            # Patching instance methods in `start()` creates a reference cycle if
+            # done in a naive way. See
+            # https://github.com/getsentry/sentry-python/pull/434
+            #
+            # In threading module, using current_thread API will access current thread instance
+            # without holding it to avoid a reference cycle in an easier way.
+            with capture_internal_exceptions():
+                new_run = _wrap_run(
+                    isolation_scope,
+                    current_scope,
+                    getattr(self.run, "__func__", self.run),
+                )
+                self.run = new_run  # type: ignore
+
+            return old_start(self, *a, **kw)
+
+        Thread.start = sentry_start  # type: ignore
+
+
+def _wrap_run(isolation_scope_to_use, current_scope_to_use, old_run_func):
+    # type: (Optional[sentry_sdk.Scope], Optional[sentry_sdk.Scope], F) -> F
+    @wraps(old_run_func)
+    def run(*a, **kw):
+        # type: (*Any, **Any) -> Any
+        def _run_old_run_func():
+            # type: () -> Any
+            try:
+                self = current_thread()
+                return old_run_func(self, *a[1:], **kw)
+            except Exception:
+                reraise(*_capture_exception())
+
+        if isolation_scope_to_use is not None and current_scope_to_use is not None:
+            with use_isolation_scope(isolation_scope_to_use):
+                with use_scope(current_scope_to_use):
+                    return _run_old_run_func()
+        else:
+            return _run_old_run_func()
+
+    return run  # type: ignore
+
+
+def _capture_exception():
+    # type: () -> ExcInfo
+    exc_info = sys.exc_info()
+
+    client = sentry_sdk.get_client()
+    if client.get_integration(ThreadingIntegration) is not None:
+        event, hint = event_from_exception(
+            exc_info,
+            client_options=client.options,
+            mechanism={"type": "threading", "handled": False},
+        )
+        sentry_sdk.capture_event(event, hint=hint)
+
+    return exc_info
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/tornado.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/tornado.py
new file mode 100644
index 0000000000000000000000000000000000000000..83fe5e94e8abd56c150fb51cb1b4399bfb4c990d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/tornado.py
@@ -0,0 +1,220 @@
+import weakref
+import contextlib
+from inspect import iscoroutinefunction
+
+import sentry_sdk
+from sentry_sdk.api import continue_trace
+from sentry_sdk.consts import OP
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.tracing import TransactionSource
+from sentry_sdk.utils import (
+    HAS_REAL_CONTEXTVARS,
+    CONTEXTVARS_ERROR_MESSAGE,
+    ensure_integration_enabled,
+    event_from_exception,
+    capture_internal_exceptions,
+    transaction_from_function,
+)
+from sentry_sdk.integrations import _check_minimum_version, Integration, DidNotEnable
+from sentry_sdk.integrations._wsgi_common import (
+    RequestExtractor,
+    _filter_headers,
+    _is_json_content_type,
+)
+from sentry_sdk.integrations.logging import ignore_logger
+
+try:
+    from tornado import version_info as TORNADO_VERSION
+    from tornado.web import RequestHandler, HTTPError
+    from tornado.gen import coroutine
+except ImportError:
+    raise DidNotEnable("Tornado not installed")
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Optional
+    from typing import Dict
+    from typing import Callable
+    from typing import Generator
+
+    from sentry_sdk._types import Event, EventProcessor
+
+
+class TornadoIntegration(Integration):
+    identifier = "tornado"
+    origin = f"auto.http.{identifier}"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        _check_minimum_version(TornadoIntegration, TORNADO_VERSION)
+
+        if not HAS_REAL_CONTEXTVARS:
+            # Tornado is async. We better have contextvars or we're going to leak
+            # state between requests.
+            raise DidNotEnable(
+                "The tornado integration for Sentry requires Python 3.7+ or the aiocontextvars package"
+                + CONTEXTVARS_ERROR_MESSAGE
+            )
+
+        ignore_logger("tornado.access")
+
+        old_execute = RequestHandler._execute
+
+        awaitable = iscoroutinefunction(old_execute)
+
+        if awaitable:
+            # Starting Tornado 6 RequestHandler._execute method is a standard Python coroutine (async/await)
+            # In that case our method should be a coroutine function too
+            async def sentry_execute_request_handler(self, *args, **kwargs):
+                # type: (RequestHandler, *Any, **Any) -> Any
+                with _handle_request_impl(self):
+                    return await old_execute(self, *args, **kwargs)
+
+        else:
+
+            @coroutine  # type: ignore
+            def sentry_execute_request_handler(self, *args, **kwargs):
+                # type: (RequestHandler, *Any, **Any) -> Any
+                with _handle_request_impl(self):
+                    result = yield from old_execute(self, *args, **kwargs)
+                    return result
+
+        RequestHandler._execute = sentry_execute_request_handler
+
+        old_log_exception = RequestHandler.log_exception
+
+        def sentry_log_exception(self, ty, value, tb, *args, **kwargs):
+            # type: (Any, type, BaseException, Any, *Any, **Any) -> Optional[Any]
+            _capture_exception(ty, value, tb)
+            return old_log_exception(self, ty, value, tb, *args, **kwargs)
+
+        RequestHandler.log_exception = sentry_log_exception
+
+
+@contextlib.contextmanager
+def _handle_request_impl(self):
+    # type: (RequestHandler) -> Generator[None, None, None]
+    integration = sentry_sdk.get_client().get_integration(TornadoIntegration)
+
+    if integration is None:
+        yield
+
+    weak_handler = weakref.ref(self)
+
+    with sentry_sdk.isolation_scope() as scope:
+        headers = self.request.headers
+
+        scope.clear_breadcrumbs()
+        processor = _make_event_processor(weak_handler)
+        scope.add_event_processor(processor)
+
+        transaction = continue_trace(
+            headers,
+            op=OP.HTTP_SERVER,
+            # Like with all other integrations, this is our
+            # fallback transaction in case there is no route.
+            # sentry_urldispatcher_resolve is responsible for
+            # setting a transaction name later.
+            name="generic Tornado request",
+            source=TransactionSource.ROUTE,
+            origin=TornadoIntegration.origin,
+        )
+
+        with sentry_sdk.start_transaction(
+            transaction, custom_sampling_context={"tornado_request": self.request}
+        ):
+            yield
+
+
+@ensure_integration_enabled(TornadoIntegration)
+def _capture_exception(ty, value, tb):
+    # type: (type, BaseException, Any) -> None
+    if isinstance(value, HTTPError):
+        return
+
+    event, hint = event_from_exception(
+        (ty, value, tb),
+        client_options=sentry_sdk.get_client().options,
+        mechanism={"type": "tornado", "handled": False},
+    )
+
+    sentry_sdk.capture_event(event, hint=hint)
+
+
+def _make_event_processor(weak_handler):
+    # type: (Callable[[], RequestHandler]) -> EventProcessor
+    def tornado_processor(event, hint):
+        # type: (Event, dict[str, Any]) -> Event
+        handler = weak_handler()
+        if handler is None:
+            return event
+
+        request = handler.request
+
+        with capture_internal_exceptions():
+            method = getattr(handler, handler.request.method.lower())
+            event["transaction"] = transaction_from_function(method) or ""
+            event["transaction_info"] = {"source": TransactionSource.COMPONENT}
+
+        with capture_internal_exceptions():
+            extractor = TornadoRequestExtractor(request)
+            extractor.extract_into_event(event)
+
+            request_info = event["request"]
+
+            request_info["url"] = "%s://%s%s" % (
+                request.protocol,
+                request.host,
+                request.path,
+            )
+
+            request_info["query_string"] = request.query
+            request_info["method"] = request.method
+            request_info["env"] = {"REMOTE_ADDR": request.remote_ip}
+            request_info["headers"] = _filter_headers(dict(request.headers))
+
+        with capture_internal_exceptions():
+            if handler.current_user and should_send_default_pii():
+                event.setdefault("user", {}).setdefault("is_authenticated", True)
+
+        return event
+
+    return tornado_processor
+
+
+class TornadoRequestExtractor(RequestExtractor):
+    def content_length(self):
+        # type: () -> int
+        if self.request.body is None:
+            return 0
+        return len(self.request.body)
+
+    def cookies(self):
+        # type: () -> Dict[str, str]
+        return {k: v.value for k, v in self.request.cookies.items()}
+
+    def raw_data(self):
+        # type: () -> bytes
+        return self.request.body
+
+    def form(self):
+        # type: () -> Dict[str, Any]
+        return {
+            k: [v.decode("latin1", "replace") for v in vs]
+            for k, vs in self.request.body_arguments.items()
+        }
+
+    def is_json(self):
+        # type: () -> bool
+        return _is_json_content_type(self.request.headers.get("content-type"))
+
+    def files(self):
+        # type: () -> Dict[str, Any]
+        return {k: v[0] for k, v in self.request.files.items() if v}
+
+    def size_of_file(self, file):
+        # type: (Any) -> int
+        return len(file.body or ())
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/trytond.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/trytond.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c44c593a4bdb830b4d3f1aae5f4642e82215dd3
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/trytond.py
@@ -0,0 +1,50 @@
+import sentry_sdk
+from sentry_sdk.integrations import Integration
+from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware
+from sentry_sdk.utils import ensure_integration_enabled, event_from_exception
+
+from trytond.exceptions import TrytonException  # type: ignore
+from trytond.wsgi import app  # type: ignore
+
+
+# TODO: trytond-worker, trytond-cron and trytond-admin intergations
+
+
+class TrytondWSGIIntegration(Integration):
+    identifier = "trytond_wsgi"
+    origin = f"auto.http.{identifier}"
+
+    def __init__(self):  # type: () -> None
+        pass
+
+    @staticmethod
+    def setup_once():  # type: () -> None
+        app.wsgi_app = SentryWsgiMiddleware(
+            app.wsgi_app,
+            span_origin=TrytondWSGIIntegration.origin,
+        )
+
+        @ensure_integration_enabled(TrytondWSGIIntegration)
+        def error_handler(e):  # type: (Exception) -> None
+            if isinstance(e, TrytonException):
+                return
+            else:
+                client = sentry_sdk.get_client()
+                event, hint = event_from_exception(
+                    e,
+                    client_options=client.options,
+                    mechanism={"type": "trytond", "handled": False},
+                )
+                sentry_sdk.capture_event(event, hint=hint)
+
+        # Expected error handlers signature was changed
+        # when the error_handler decorator was introduced
+        # in Tryton-5.4
+        if hasattr(app, "error_handler"):
+
+            @app.error_handler
+            def _(app, request, e):  # type: ignore
+                error_handler(e)
+
+        else:
+            app.error_handlers.append(error_handler)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/typer.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/typer.py
new file mode 100644
index 0000000000000000000000000000000000000000..8879d6d0d01e22341a58fe095e02bd4cb543ca30
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/typer.py
@@ -0,0 +1,60 @@
+import sentry_sdk
+from sentry_sdk.utils import (
+    capture_internal_exceptions,
+    event_from_exception,
+)
+from sentry_sdk.integrations import Integration, DidNotEnable
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Callable
+    from typing import Any
+    from typing import Type
+    from typing import Optional
+
+    from types import TracebackType
+
+    Excepthook = Callable[
+        [Type[BaseException], BaseException, Optional[TracebackType]],
+        Any,
+    ]
+
+try:
+    import typer
+except ImportError:
+    raise DidNotEnable("Typer not installed")
+
+
+class TyperIntegration(Integration):
+    identifier = "typer"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        typer.main.except_hook = _make_excepthook(typer.main.except_hook)  # type: ignore
+
+
+def _make_excepthook(old_excepthook):
+    # type: (Excepthook) -> Excepthook
+    def sentry_sdk_excepthook(type_, value, traceback):
+        # type: (Type[BaseException], BaseException, Optional[TracebackType]) -> None
+        integration = sentry_sdk.get_client().get_integration(TyperIntegration)
+
+        # Note: If we replace this with ensure_integration_enabled then
+        # we break the exceptiongroup backport;
+        # See: https://github.com/getsentry/sentry-python/issues/3097
+        if integration is None:
+            return old_excepthook(type_, value, traceback)
+
+        with capture_internal_exceptions():
+            event, hint = event_from_exception(
+                (type_, value, traceback),
+                client_options=sentry_sdk.get_client().options,
+                mechanism={"type": "typer", "handled": False},
+            )
+            sentry_sdk.capture_event(event, hint=hint)
+
+        return old_excepthook(type_, value, traceback)
+
+    return sentry_sdk_excepthook
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/unleash.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/unleash.py
new file mode 100644
index 0000000000000000000000000000000000000000..6daa0a411fe0967164be0795c2f73a2fcfa2db18
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/unleash.py
@@ -0,0 +1,33 @@
+from functools import wraps
+from typing import Any
+
+from sentry_sdk.feature_flags import add_feature_flag
+from sentry_sdk.integrations import Integration, DidNotEnable
+
+try:
+    from UnleashClient import UnleashClient
+except ImportError:
+    raise DidNotEnable("UnleashClient is not installed")
+
+
+class UnleashIntegration(Integration):
+    identifier = "unleash"
+
+    @staticmethod
+    def setup_once():
+        # type: () -> None
+        # Wrap and patch evaluation methods (class methods)
+        old_is_enabled = UnleashClient.is_enabled
+
+        @wraps(old_is_enabled)
+        def sentry_is_enabled(self, feature, *args, **kwargs):
+            # type: (UnleashClient, str, *Any, **Any) -> Any
+            enabled = old_is_enabled(self, feature, *args, **kwargs)
+
+            # We have no way of knowing what type of unleash feature this is, so we have to treat
+            # it as a boolean / toggle feature.
+            add_feature_flag(feature, enabled)
+
+            return enabled
+
+        UnleashClient.is_enabled = sentry_is_enabled  # type: ignore
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/wsgi.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/wsgi.py
new file mode 100644
index 0000000000000000000000000000000000000000..e628e50e69e45213358f25699c0ae822d04bcf0b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/integrations/wsgi.py
@@ -0,0 +1,310 @@
+import sys
+from functools import partial
+
+import sentry_sdk
+from sentry_sdk._werkzeug import get_host, _get_headers
+from sentry_sdk.api import continue_trace
+from sentry_sdk.consts import OP
+from sentry_sdk.scope import should_send_default_pii
+from sentry_sdk.integrations._wsgi_common import (
+    DEFAULT_HTTP_METHODS_TO_CAPTURE,
+    _filter_headers,
+    nullcontext,
+)
+from sentry_sdk.sessions import track_session
+from sentry_sdk.scope import use_isolation_scope
+from sentry_sdk.tracing import Transaction, TransactionSource
+from sentry_sdk.utils import (
+    ContextVar,
+    capture_internal_exceptions,
+    event_from_exception,
+    reraise,
+)
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Callable
+    from typing import Dict
+    from typing import Iterator
+    from typing import Any
+    from typing import Tuple
+    from typing import Optional
+    from typing import TypeVar
+    from typing import Protocol
+
+    from sentry_sdk.utils import ExcInfo
+    from sentry_sdk._types import Event, EventProcessor
+
+    WsgiResponseIter = TypeVar("WsgiResponseIter")
+    WsgiResponseHeaders = TypeVar("WsgiResponseHeaders")
+    WsgiExcInfo = TypeVar("WsgiExcInfo")
+
+    class StartResponse(Protocol):
+        def __call__(self, status, response_headers, exc_info=None):  # type: ignore
+            # type: (str, WsgiResponseHeaders, Optional[WsgiExcInfo]) -> WsgiResponseIter
+            pass
+
+
+_wsgi_middleware_applied = ContextVar("sentry_wsgi_middleware_applied")
+
+
+def wsgi_decoding_dance(s, charset="utf-8", errors="replace"):
+    # type: (str, str, str) -> str
+    return s.encode("latin1").decode(charset, errors)
+
+
+def get_request_url(environ, use_x_forwarded_for=False):
+    # type: (Dict[str, str], bool) -> str
+    """Return the absolute URL without query string for the given WSGI
+    environment."""
+    script_name = environ.get("SCRIPT_NAME", "").rstrip("/")
+    path_info = environ.get("PATH_INFO", "").lstrip("/")
+    path = f"{script_name}/{path_info}"
+
+    return "%s://%s/%s" % (
+        environ.get("wsgi.url_scheme"),
+        get_host(environ, use_x_forwarded_for),
+        wsgi_decoding_dance(path).lstrip("/"),
+    )
+
+
+class SentryWsgiMiddleware:
+    __slots__ = (
+        "app",
+        "use_x_forwarded_for",
+        "span_origin",
+        "http_methods_to_capture",
+    )
+
+    def __init__(
+        self,
+        app,  # type: Callable[[Dict[str, str], Callable[..., Any]], Any]
+        use_x_forwarded_for=False,  # type: bool
+        span_origin="manual",  # type: str
+        http_methods_to_capture=DEFAULT_HTTP_METHODS_TO_CAPTURE,  # type: Tuple[str, ...]
+    ):
+        # type: (...) -> None
+        self.app = app
+        self.use_x_forwarded_for = use_x_forwarded_for
+        self.span_origin = span_origin
+        self.http_methods_to_capture = http_methods_to_capture
+
+    def __call__(self, environ, start_response):
+        # type: (Dict[str, str], Callable[..., Any]) -> _ScopedResponse
+        if _wsgi_middleware_applied.get(False):
+            return self.app(environ, start_response)
+
+        _wsgi_middleware_applied.set(True)
+        try:
+            with sentry_sdk.isolation_scope() as scope:
+                with track_session(scope, session_mode="request"):
+                    with capture_internal_exceptions():
+                        scope.clear_breadcrumbs()
+                        scope._name = "wsgi"
+                        scope.add_event_processor(
+                            _make_wsgi_event_processor(
+                                environ, self.use_x_forwarded_for
+                            )
+                        )
+
+                    method = environ.get("REQUEST_METHOD", "").upper()
+                    transaction = None
+                    if method in self.http_methods_to_capture:
+                        transaction = continue_trace(
+                            environ,
+                            op=OP.HTTP_SERVER,
+                            name="generic WSGI request",
+                            source=TransactionSource.ROUTE,
+                            origin=self.span_origin,
+                        )
+
+                    with (
+                        sentry_sdk.start_transaction(
+                            transaction,
+                            custom_sampling_context={"wsgi_environ": environ},
+                        )
+                        if transaction is not None
+                        else nullcontext()
+                    ):
+                        try:
+                            response = self.app(
+                                environ,
+                                partial(
+                                    _sentry_start_response, start_response, transaction
+                                ),
+                            )
+                        except BaseException:
+                            reraise(*_capture_exception())
+        finally:
+            _wsgi_middleware_applied.set(False)
+
+        return _ScopedResponse(scope, response)
+
+
+def _sentry_start_response(  # type: ignore
+    old_start_response,  # type: StartResponse
+    transaction,  # type: Optional[Transaction]
+    status,  # type: str
+    response_headers,  # type: WsgiResponseHeaders
+    exc_info=None,  # type: Optional[WsgiExcInfo]
+):
+    # type: (...) -> WsgiResponseIter
+    with capture_internal_exceptions():
+        status_int = int(status.split(" ", 1)[0])
+        if transaction is not None:
+            transaction.set_http_status(status_int)
+
+    if exc_info is None:
+        # The Django Rest Framework WSGI test client, and likely other
+        # (incorrect) implementations, cannot deal with the exc_info argument
+        # if one is present. Avoid providing a third argument if not necessary.
+        return old_start_response(status, response_headers)
+    else:
+        return old_start_response(status, response_headers, exc_info)
+
+
+def _get_environ(environ):
+    # type: (Dict[str, str]) -> Iterator[Tuple[str, str]]
+    """
+    Returns our explicitly included environment variables we want to
+    capture (server name, port and remote addr if pii is enabled).
+    """
+    keys = ["SERVER_NAME", "SERVER_PORT"]
+    if should_send_default_pii():
+        # make debugging of proxy setup easier. Proxy headers are
+        # in headers.
+        keys += ["REMOTE_ADDR"]
+
+    for key in keys:
+        if key in environ:
+            yield key, environ[key]
+
+
+def get_client_ip(environ):
+    # type: (Dict[str, str]) -> Optional[Any]
+    """
+    Infer the user IP address from various headers. This cannot be used in
+    security sensitive situations since the value may be forged from a client,
+    but it's good enough for the event payload.
+    """
+    try:
+        return environ["HTTP_X_FORWARDED_FOR"].split(",")[0].strip()
+    except (KeyError, IndexError):
+        pass
+
+    try:
+        return environ["HTTP_X_REAL_IP"]
+    except KeyError:
+        pass
+
+    return environ.get("REMOTE_ADDR")
+
+
+def _capture_exception():
+    # type: () -> ExcInfo
+    """
+    Captures the current exception and sends it to Sentry.
+    Returns the ExcInfo tuple to it can be reraised afterwards.
+    """
+    exc_info = sys.exc_info()
+    e = exc_info[1]
+
+    # SystemExit(0) is the only uncaught exception that is expected behavior
+    should_skip_capture = isinstance(e, SystemExit) and e.code in (0, None)
+    if not should_skip_capture:
+        event, hint = event_from_exception(
+            exc_info,
+            client_options=sentry_sdk.get_client().options,
+            mechanism={"type": "wsgi", "handled": False},
+        )
+        sentry_sdk.capture_event(event, hint=hint)
+
+    return exc_info
+
+
+class _ScopedResponse:
+    """
+    Users a separate scope for each response chunk.
+
+    This will make WSGI apps more tolerant against:
+    - WSGI servers streaming responses from a different thread/from
+      different threads than the one that called start_response
+    - close() not being called
+    - WSGI servers streaming responses interleaved from the same thread
+    """
+
+    __slots__ = ("_response", "_scope")
+
+    def __init__(self, scope, response):
+        # type: (sentry_sdk.scope.Scope, Iterator[bytes]) -> None
+        self._scope = scope
+        self._response = response
+
+    def __iter__(self):
+        # type: () -> Iterator[bytes]
+        iterator = iter(self._response)
+
+        while True:
+            with use_isolation_scope(self._scope):
+                try:
+                    chunk = next(iterator)
+                except StopIteration:
+                    break
+                except BaseException:
+                    reraise(*_capture_exception())
+
+            yield chunk
+
+    def close(self):
+        # type: () -> None
+        with use_isolation_scope(self._scope):
+            try:
+                self._response.close()  # type: ignore
+            except AttributeError:
+                pass
+            except BaseException:
+                reraise(*_capture_exception())
+
+
+def _make_wsgi_event_processor(environ, use_x_forwarded_for):
+    # type: (Dict[str, str], bool) -> EventProcessor
+    # It's a bit unfortunate that we have to extract and parse the request data
+    # from the environ so eagerly, but there are a few good reasons for this.
+    #
+    # We might be in a situation where the scope never gets torn down
+    # properly. In that case we will have an unnecessary strong reference to
+    # all objects in the environ (some of which may take a lot of memory) when
+    # we're really just interested in a few of them.
+    #
+    # Keeping the environment around for longer than the request lifecycle is
+    # also not necessarily something uWSGI can deal with:
+    # https://github.com/unbit/uwsgi/issues/1950
+
+    client_ip = get_client_ip(environ)
+    request_url = get_request_url(environ, use_x_forwarded_for)
+    query_string = environ.get("QUERY_STRING")
+    method = environ.get("REQUEST_METHOD")
+    env = dict(_get_environ(environ))
+    headers = _filter_headers(dict(_get_headers(environ)))
+
+    def event_processor(event, hint):
+        # type: (Event, Dict[str, Any]) -> Event
+        with capture_internal_exceptions():
+            # if the code below fails halfway through we at least have some data
+            request_info = event.setdefault("request", {})
+
+            if should_send_default_pii():
+                user_info = event.setdefault("user", {})
+                if client_ip:
+                    user_info.setdefault("ip_address", client_ip)
+
+            request_info["url"] = request_url
+            request_info["query_string"] = query_string
+            request_info["method"] = method
+            request_info["env"] = env
+            request_info["headers"] = headers
+
+        return event
+
+    return event_processor
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bc63e3a6d9d2692e577d05bb77fb549d4b0b15f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/__init__.py
@@ -0,0 +1,49 @@
+from sentry_sdk.profiler.continuous_profiler import (
+    start_profile_session,
+    start_profiler,
+    stop_profile_session,
+    stop_profiler,
+)
+from sentry_sdk.profiler.transaction_profiler import (
+    MAX_PROFILE_DURATION_NS,
+    PROFILE_MINIMUM_SAMPLES,
+    Profile,
+    Scheduler,
+    ThreadScheduler,
+    GeventScheduler,
+    has_profiling_enabled,
+    setup_profiler,
+    teardown_profiler,
+)
+from sentry_sdk.profiler.utils import (
+    DEFAULT_SAMPLING_FREQUENCY,
+    MAX_STACK_DEPTH,
+    get_frame_name,
+    extract_frame,
+    extract_stack,
+    frame_id,
+)
+
+__all__ = [
+    "start_profile_session",  # TODO: Deprecate this in favor of `start_profiler`
+    "start_profiler",
+    "stop_profile_session",  # TODO: Deprecate this in favor of `stop_profiler`
+    "stop_profiler",
+    # DEPRECATED: The following was re-exported for backwards compatibility. It
+    # will be removed from sentry_sdk.profiler in a future release.
+    "MAX_PROFILE_DURATION_NS",
+    "PROFILE_MINIMUM_SAMPLES",
+    "Profile",
+    "Scheduler",
+    "ThreadScheduler",
+    "GeventScheduler",
+    "has_profiling_enabled",
+    "setup_profiler",
+    "teardown_profiler",
+    "DEFAULT_SAMPLING_FREQUENCY",
+    "MAX_STACK_DEPTH",
+    "get_frame_name",
+    "extract_frame",
+    "extract_stack",
+    "frame_id",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..809f6ff2ecca35c40f4f57eef8c4b9a0d66877ca
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/__pycache__/continuous_profiler.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/__pycache__/continuous_profiler.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1aa8e4de837a70a2134b28c9d56b86fe61a83e9e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/__pycache__/continuous_profiler.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/__pycache__/transaction_profiler.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/__pycache__/transaction_profiler.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6cd65b6b22cf682223d680acc384b9408b5d2826
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/__pycache__/transaction_profiler.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/__pycache__/utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e450b349adf19c9b1405b027fe7b3231f2714c7a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/__pycache__/utils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/continuous_profiler.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/continuous_profiler.py
new file mode 100644
index 0000000000000000000000000000000000000000..00dd29e36ce4a9c0eb6d772bf7410bdd40a58f17
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/continuous_profiler.py
@@ -0,0 +1,720 @@
+import atexit
+import os
+import random
+import sys
+import threading
+import time
+import uuid
+import warnings
+from collections import deque
+from datetime import datetime, timezone
+
+from sentry_sdk.consts import VERSION
+from sentry_sdk.envelope import Envelope
+from sentry_sdk._lru_cache import LRUCache
+from sentry_sdk.profiler.utils import (
+    DEFAULT_SAMPLING_FREQUENCY,
+    extract_stack,
+)
+from sentry_sdk.utils import (
+    capture_internal_exception,
+    is_gevent,
+    logger,
+    now,
+    set_in_app_in_frames,
+)
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Callable
+    from typing import Deque
+    from typing import Dict
+    from typing import List
+    from typing import Optional
+    from typing import Set
+    from typing import Type
+    from typing import Union
+    from typing_extensions import TypedDict
+    from sentry_sdk._types import ContinuousProfilerMode, SDKInfo
+    from sentry_sdk.profiler.utils import (
+        ExtractedSample,
+        FrameId,
+        StackId,
+        ThreadId,
+        ProcessedFrame,
+        ProcessedStack,
+    )
+
+    ProcessedSample = TypedDict(
+        "ProcessedSample",
+        {
+            "timestamp": float,
+            "thread_id": ThreadId,
+            "stack_id": int,
+        },
+    )
+
+
+try:
+    from gevent.monkey import get_original
+    from gevent.threadpool import ThreadPool as _ThreadPool
+
+    ThreadPool = _ThreadPool  # type: Optional[Type[_ThreadPool]]
+    thread_sleep = get_original("time", "sleep")
+except ImportError:
+    thread_sleep = time.sleep
+    ThreadPool = None
+
+
+_scheduler = None  # type: Optional[ContinuousScheduler]
+
+
+def setup_continuous_profiler(options, sdk_info, capture_func):
+    # type: (Dict[str, Any], SDKInfo, Callable[[Envelope], None]) -> bool
+    global _scheduler
+
+    if _scheduler is not None:
+        logger.debug("[Profiling] Continuous Profiler is already setup")
+        return False
+
+    if is_gevent():
+        # If gevent has patched the threading modules then we cannot rely on
+        # them to spawn a native thread for sampling.
+        # Instead we default to the GeventContinuousScheduler which is capable of
+        # spawning native threads within gevent.
+        default_profiler_mode = GeventContinuousScheduler.mode
+    else:
+        default_profiler_mode = ThreadContinuousScheduler.mode
+
+    if options.get("profiler_mode") is not None:
+        profiler_mode = options["profiler_mode"]
+    else:
+        # TODO: deprecate this and just use the existing `profiler_mode`
+        experiments = options.get("_experiments", {})
+
+        profiler_mode = (
+            experiments.get("continuous_profiling_mode") or default_profiler_mode
+        )
+
+    frequency = DEFAULT_SAMPLING_FREQUENCY
+
+    if profiler_mode == ThreadContinuousScheduler.mode:
+        _scheduler = ThreadContinuousScheduler(
+            frequency, options, sdk_info, capture_func
+        )
+    elif profiler_mode == GeventContinuousScheduler.mode:
+        _scheduler = GeventContinuousScheduler(
+            frequency, options, sdk_info, capture_func
+        )
+    else:
+        raise ValueError("Unknown continuous profiler mode: {}".format(profiler_mode))
+
+    logger.debug(
+        "[Profiling] Setting up continuous profiler in {mode} mode".format(
+            mode=_scheduler.mode
+        )
+    )
+
+    atexit.register(teardown_continuous_profiler)
+
+    return True
+
+
+def try_autostart_continuous_profiler():
+    # type: () -> None
+
+    # TODO: deprecate this as it'll be replaced by the auto lifecycle option
+
+    if _scheduler is None:
+        return
+
+    if not _scheduler.is_auto_start_enabled():
+        return
+
+    _scheduler.manual_start()
+
+
+def try_profile_lifecycle_trace_start():
+    # type: () -> Union[ContinuousProfile, None]
+    if _scheduler is None:
+        return None
+
+    return _scheduler.auto_start()
+
+
+def start_profiler():
+    # type: () -> None
+    if _scheduler is None:
+        return
+
+    _scheduler.manual_start()
+
+
+def start_profile_session():
+    # type: () -> None
+
+    warnings.warn(
+        "The `start_profile_session` function is deprecated. Please use `start_profile` instead.",
+        DeprecationWarning,
+        stacklevel=2,
+    )
+    start_profiler()
+
+
+def stop_profiler():
+    # type: () -> None
+    if _scheduler is None:
+        return
+
+    _scheduler.manual_stop()
+
+
+def stop_profile_session():
+    # type: () -> None
+
+    warnings.warn(
+        "The `stop_profile_session` function is deprecated. Please use `stop_profile` instead.",
+        DeprecationWarning,
+        stacklevel=2,
+    )
+    stop_profiler()
+
+
+def teardown_continuous_profiler():
+    # type: () -> None
+    stop_profiler()
+
+    global _scheduler
+    _scheduler = None
+
+
+def get_profiler_id():
+    # type: () -> Union[str, None]
+    if _scheduler is None:
+        return None
+    return _scheduler.profiler_id
+
+
+def determine_profile_session_sampling_decision(sample_rate):
+    # type: (Union[float, None]) -> bool
+
+    # `None` is treated as `0.0`
+    if not sample_rate:
+        return False
+
+    return random.random() < float(sample_rate)
+
+
+class ContinuousProfile:
+    active: bool = True
+
+    def stop(self):
+        # type: () -> None
+        self.active = False
+
+
+class ContinuousScheduler:
+    mode = "unknown"  # type: ContinuousProfilerMode
+
+    def __init__(self, frequency, options, sdk_info, capture_func):
+        # type: (int, Dict[str, Any], SDKInfo, Callable[[Envelope], None]) -> None
+        self.interval = 1.0 / frequency
+        self.options = options
+        self.sdk_info = sdk_info
+        self.capture_func = capture_func
+
+        self.lifecycle = self.options.get("profile_lifecycle")
+        profile_session_sample_rate = self.options.get("profile_session_sample_rate")
+        self.sampled = determine_profile_session_sampling_decision(
+            profile_session_sample_rate
+        )
+
+        self.sampler = self.make_sampler()
+        self.buffer = None  # type: Optional[ProfileBuffer]
+        self.pid = None  # type: Optional[int]
+
+        self.running = False
+        self.soft_shutdown = False
+
+        self.new_profiles = deque(maxlen=128)  # type: Deque[ContinuousProfile]
+        self.active_profiles = set()  # type: Set[ContinuousProfile]
+
+    def is_auto_start_enabled(self):
+        # type: () -> bool
+
+        # Ensure that the scheduler only autostarts once per process.
+        # This is necessary because many web servers use forks to spawn
+        # additional processes. And the profiler is only spawned on the
+        # master process, then it often only profiles the main process
+        # and not the ones where the requests are being handled.
+        if self.pid == os.getpid():
+            return False
+
+        experiments = self.options.get("_experiments")
+        if not experiments:
+            return False
+
+        return experiments.get("continuous_profiling_auto_start")
+
+    def auto_start(self):
+        # type: () -> Union[ContinuousProfile, None]
+        if not self.sampled:
+            return None
+
+        if self.lifecycle != "trace":
+            return None
+
+        logger.debug("[Profiling] Auto starting profiler")
+
+        profile = ContinuousProfile()
+
+        self.new_profiles.append(profile)
+        self.ensure_running()
+
+        return profile
+
+    def manual_start(self):
+        # type: () -> None
+        if not self.sampled:
+            return
+
+        if self.lifecycle != "manual":
+            return
+
+        self.ensure_running()
+
+    def manual_stop(self):
+        # type: () -> None
+        if self.lifecycle != "manual":
+            return
+
+        self.teardown()
+
+    def ensure_running(self):
+        # type: () -> None
+        raise NotImplementedError
+
+    def teardown(self):
+        # type: () -> None
+        raise NotImplementedError
+
+    def pause(self):
+        # type: () -> None
+        raise NotImplementedError
+
+    def reset_buffer(self):
+        # type: () -> None
+        self.buffer = ProfileBuffer(
+            self.options, self.sdk_info, PROFILE_BUFFER_SECONDS, self.capture_func
+        )
+
+    @property
+    def profiler_id(self):
+        # type: () -> Union[str, None]
+        if self.buffer is None:
+            return None
+        return self.buffer.profiler_id
+
+    def make_sampler(self):
+        # type: () -> Callable[..., bool]
+        cwd = os.getcwd()
+
+        cache = LRUCache(max_size=256)
+
+        if self.lifecycle == "trace":
+
+            def _sample_stack(*args, **kwargs):
+                # type: (*Any, **Any) -> bool
+                """
+                Take a sample of the stack on all the threads in the process.
+                This should be called at a regular interval to collect samples.
+                """
+
+                # no profiles taking place, so we can stop early
+                if not self.new_profiles and not self.active_profiles:
+                    return True
+
+                # This is the number of profiles we want to pop off.
+                # It's possible another thread adds a new profile to
+                # the list and we spend longer than we want inside
+                # the loop below.
+                #
+                # Also make sure to set this value before extracting
+                # frames so we do not write to any new profiles that
+                # were started after this point.
+                new_profiles = len(self.new_profiles)
+
+                ts = now()
+
+                try:
+                    sample = [
+                        (str(tid), extract_stack(frame, cache, cwd))
+                        for tid, frame in sys._current_frames().items()
+                    ]
+                except AttributeError:
+                    # For some reason, the frame we get doesn't have certain attributes.
+                    # When this happens, we abandon the current sample as it's bad.
+                    capture_internal_exception(sys.exc_info())
+                    return False
+
+                # Move the new profiles into the active_profiles set.
+                #
+                # We cannot directly add the to active_profiles set
+                # in `start_profiling` because it is called from other
+                # threads which can cause a RuntimeError when it the
+                # set sizes changes during iteration without a lock.
+                #
+                # We also want to avoid using a lock here so threads
+                # that are starting profiles are not blocked until it
+                # can acquire the lock.
+                for _ in range(new_profiles):
+                    self.active_profiles.add(self.new_profiles.popleft())
+                inactive_profiles = []
+
+                for profile in self.active_profiles:
+                    if not profile.active:
+                        # If a profile is marked inactive, we buffer it
+                        # to `inactive_profiles` so it can be removed.
+                        # We cannot remove it here as it would result
+                        # in a RuntimeError.
+                        inactive_profiles.append(profile)
+
+                for profile in inactive_profiles:
+                    self.active_profiles.remove(profile)
+
+                if self.buffer is not None:
+                    self.buffer.write(ts, sample)
+
+                return False
+
+        else:
+
+            def _sample_stack(*args, **kwargs):
+                # type: (*Any, **Any) -> bool
+                """
+                Take a sample of the stack on all the threads in the process.
+                This should be called at a regular interval to collect samples.
+                """
+
+                ts = now()
+
+                try:
+                    sample = [
+                        (str(tid), extract_stack(frame, cache, cwd))
+                        for tid, frame in sys._current_frames().items()
+                    ]
+                except AttributeError:
+                    # For some reason, the frame we get doesn't have certain attributes.
+                    # When this happens, we abandon the current sample as it's bad.
+                    capture_internal_exception(sys.exc_info())
+                    return False
+
+                if self.buffer is not None:
+                    self.buffer.write(ts, sample)
+
+                return False
+
+        return _sample_stack
+
+    def run(self):
+        # type: () -> None
+        last = time.perf_counter()
+
+        while self.running:
+            self.soft_shutdown = self.sampler()
+
+            # some time may have elapsed since the last time
+            # we sampled, so we need to account for that and
+            # not sleep for too long
+            elapsed = time.perf_counter() - last
+            if elapsed < self.interval:
+                thread_sleep(self.interval - elapsed)
+
+            # the soft shutdown happens here to give it a chance
+            # for the profiler to be reused
+            if self.soft_shutdown:
+                self.running = False
+
+                # make sure to explicitly exit the profiler here or there might
+                # be multiple profilers at once
+                break
+
+            # after sleeping, make sure to take the current
+            # timestamp so we can use it next iteration
+            last = time.perf_counter()
+
+        if self.buffer is not None:
+            self.buffer.flush()
+            self.buffer = None
+
+
+class ThreadContinuousScheduler(ContinuousScheduler):
+    """
+    This scheduler is based on running a daemon thread that will call
+    the sampler at a regular interval.
+    """
+
+    mode = "thread"  # type: ContinuousProfilerMode
+    name = "sentry.profiler.ThreadContinuousScheduler"
+
+    def __init__(self, frequency, options, sdk_info, capture_func):
+        # type: (int, Dict[str, Any], SDKInfo, Callable[[Envelope], None]) -> None
+        super().__init__(frequency, options, sdk_info, capture_func)
+
+        self.thread = None  # type: Optional[threading.Thread]
+        self.lock = threading.Lock()
+
+    def ensure_running(self):
+        # type: () -> None
+
+        self.soft_shutdown = False
+
+        pid = os.getpid()
+
+        # is running on the right process
+        if self.running and self.pid == pid:
+            return
+
+        with self.lock:
+            # another thread may have tried to acquire the lock
+            # at the same time so it may start another thread
+            # make sure to check again before proceeding
+            if self.running and self.pid == pid:
+                return
+
+            self.pid = pid
+            self.running = True
+
+            # if the profiler thread is changing,
+            # we should create a new buffer along with it
+            self.reset_buffer()
+
+            # make sure the thread is a daemon here otherwise this
+            # can keep the application running after other threads
+            # have exited
+            self.thread = threading.Thread(name=self.name, target=self.run, daemon=True)
+
+            try:
+                self.thread.start()
+            except RuntimeError:
+                # Unfortunately at this point the interpreter is in a state that no
+                # longer allows us to spawn a thread and we have to bail.
+                self.running = False
+                self.thread = None
+
+    def teardown(self):
+        # type: () -> None
+        if self.running:
+            self.running = False
+
+        if self.thread is not None:
+            self.thread.join()
+            self.thread = None
+
+        self.buffer = None
+
+
+class GeventContinuousScheduler(ContinuousScheduler):
+    """
+    This scheduler is based on the thread scheduler but adapted to work with
+    gevent. When using gevent, it may monkey patch the threading modules
+    (`threading` and `_thread`). This results in the use of greenlets instead
+    of native threads.
+
+    This is an issue because the sampler CANNOT run in a greenlet because
+    1. Other greenlets doing sync work will prevent the sampler from running
+    2. The greenlet runs in the same thread as other greenlets so when taking
+       a sample, other greenlets will have been evicted from the thread. This
+       results in a sample containing only the sampler's code.
+    """
+
+    mode = "gevent"  # type: ContinuousProfilerMode
+
+    def __init__(self, frequency, options, sdk_info, capture_func):
+        # type: (int, Dict[str, Any], SDKInfo, Callable[[Envelope], None]) -> None
+
+        if ThreadPool is None:
+            raise ValueError("Profiler mode: {} is not available".format(self.mode))
+
+        super().__init__(frequency, options, sdk_info, capture_func)
+
+        self.thread = None  # type: Optional[_ThreadPool]
+        self.lock = threading.Lock()
+
+    def ensure_running(self):
+        # type: () -> None
+
+        self.soft_shutdown = False
+
+        pid = os.getpid()
+
+        # is running on the right process
+        if self.running and self.pid == pid:
+            return
+
+        with self.lock:
+            # another thread may have tried to acquire the lock
+            # at the same time so it may start another thread
+            # make sure to check again before proceeding
+            if self.running and self.pid == pid:
+                return
+
+            self.pid = pid
+            self.running = True
+
+            # if the profiler thread is changing,
+            # we should create a new buffer along with it
+            self.reset_buffer()
+
+            self.thread = ThreadPool(1)  # type: ignore[misc]
+            try:
+                self.thread.spawn(self.run)
+            except RuntimeError:
+                # Unfortunately at this point the interpreter is in a state that no
+                # longer allows us to spawn a thread and we have to bail.
+                self.running = False
+                self.thread = None
+
+    def teardown(self):
+        # type: () -> None
+        if self.running:
+            self.running = False
+
+        if self.thread is not None:
+            self.thread.join()
+            self.thread = None
+
+        self.buffer = None
+
+
+PROFILE_BUFFER_SECONDS = 60
+
+
+class ProfileBuffer:
+    def __init__(self, options, sdk_info, buffer_size, capture_func):
+        # type: (Dict[str, Any], SDKInfo, int, Callable[[Envelope], None]) -> None
+        self.options = options
+        self.sdk_info = sdk_info
+        self.buffer_size = buffer_size
+        self.capture_func = capture_func
+
+        self.profiler_id = uuid.uuid4().hex
+        self.chunk = ProfileChunk()
+
+        # Make sure to use the same clock to compute a sample's monotonic timestamp
+        # to ensure the timestamps are correctly aligned.
+        self.start_monotonic_time = now()
+
+        # Make sure the start timestamp is defined only once per profiler id.
+        # This prevents issues with clock drift within a single profiler session.
+        #
+        # Subtracting the start_monotonic_time here to find a fixed starting position
+        # for relative monotonic timestamps for each sample.
+        self.start_timestamp = (
+            datetime.now(timezone.utc).timestamp() - self.start_monotonic_time
+        )
+
+    def write(self, monotonic_time, sample):
+        # type: (float, ExtractedSample) -> None
+        if self.should_flush(monotonic_time):
+            self.flush()
+            self.chunk = ProfileChunk()
+            self.start_monotonic_time = now()
+
+        self.chunk.write(self.start_timestamp + monotonic_time, sample)
+
+    def should_flush(self, monotonic_time):
+        # type: (float) -> bool
+
+        # If the delta between the new monotonic time and the start monotonic time
+        # exceeds the buffer size, it means we should flush the chunk
+        return monotonic_time - self.start_monotonic_time >= self.buffer_size
+
+    def flush(self):
+        # type: () -> None
+        chunk = self.chunk.to_json(self.profiler_id, self.options, self.sdk_info)
+        envelope = Envelope()
+        envelope.add_profile_chunk(chunk)
+        self.capture_func(envelope)
+
+
+class ProfileChunk:
+    def __init__(self):
+        # type: () -> None
+        self.chunk_id = uuid.uuid4().hex
+
+        self.indexed_frames = {}  # type: Dict[FrameId, int]
+        self.indexed_stacks = {}  # type: Dict[StackId, int]
+        self.frames = []  # type: List[ProcessedFrame]
+        self.stacks = []  # type: List[ProcessedStack]
+        self.samples = []  # type: List[ProcessedSample]
+
+    def write(self, ts, sample):
+        # type: (float, ExtractedSample) -> None
+        for tid, (stack_id, frame_ids, frames) in sample:
+            try:
+                # Check if the stack is indexed first, this lets us skip
+                # indexing frames if it's not necessary
+                if stack_id not in self.indexed_stacks:
+                    for i, frame_id in enumerate(frame_ids):
+                        if frame_id not in self.indexed_frames:
+                            self.indexed_frames[frame_id] = len(self.indexed_frames)
+                            self.frames.append(frames[i])
+
+                    self.indexed_stacks[stack_id] = len(self.indexed_stacks)
+                    self.stacks.append(
+                        [self.indexed_frames[frame_id] for frame_id in frame_ids]
+                    )
+
+                self.samples.append(
+                    {
+                        "timestamp": ts,
+                        "thread_id": tid,
+                        "stack_id": self.indexed_stacks[stack_id],
+                    }
+                )
+            except AttributeError:
+                # For some reason, the frame we get doesn't have certain attributes.
+                # When this happens, we abandon the current sample as it's bad.
+                capture_internal_exception(sys.exc_info())
+
+    def to_json(self, profiler_id, options, sdk_info):
+        # type: (str, Dict[str, Any], SDKInfo) -> Dict[str, Any]
+        profile = {
+            "frames": self.frames,
+            "stacks": self.stacks,
+            "samples": self.samples,
+            "thread_metadata": {
+                str(thread.ident): {
+                    "name": str(thread.name),
+                }
+                for thread in threading.enumerate()
+            },
+        }
+
+        set_in_app_in_frames(
+            profile["frames"],
+            options["in_app_exclude"],
+            options["in_app_include"],
+            options["project_root"],
+        )
+
+        payload = {
+            "chunk_id": self.chunk_id,
+            "client_sdk": {
+                "name": sdk_info["name"],
+                "version": VERSION,
+            },
+            "platform": "python",
+            "profile": profile,
+            "profiler_id": profiler_id,
+            "version": "2",
+        }
+
+        for key in "release", "environment", "dist":
+            if options[key] is not None:
+                payload[key] = str(options[key]).strip()
+
+        return payload
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/transaction_profiler.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/transaction_profiler.py
new file mode 100644
index 0000000000000000000000000000000000000000..3743b7c905f5fb782373cb63565f25e5eb2e68e8
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/transaction_profiler.py
@@ -0,0 +1,837 @@
+"""
+This file is originally based on code from https://github.com/nylas/nylas-perftools,
+which is published under the following license:
+
+The MIT License (MIT)
+
+Copyright (c) 2014 Nylas
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+"""
+
+import atexit
+import os
+import platform
+import random
+import sys
+import threading
+import time
+import uuid
+import warnings
+from abc import ABC, abstractmethod
+from collections import deque
+
+import sentry_sdk
+from sentry_sdk._lru_cache import LRUCache
+from sentry_sdk.profiler.utils import (
+    DEFAULT_SAMPLING_FREQUENCY,
+    extract_stack,
+)
+from sentry_sdk.utils import (
+    capture_internal_exception,
+    get_current_thread_meta,
+    is_gevent,
+    is_valid_sample_rate,
+    logger,
+    nanosecond_time,
+    set_in_app_in_frames,
+)
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Any
+    from typing import Callable
+    from typing import Deque
+    from typing import Dict
+    from typing import List
+    from typing import Optional
+    from typing import Set
+    from typing import Type
+    from typing_extensions import TypedDict
+
+    from sentry_sdk.profiler.utils import (
+        ProcessedStack,
+        ProcessedFrame,
+        ProcessedThreadMetadata,
+        FrameId,
+        StackId,
+        ThreadId,
+        ExtractedSample,
+    )
+    from sentry_sdk._types import Event, SamplingContext, ProfilerMode
+
+    ProcessedSample = TypedDict(
+        "ProcessedSample",
+        {
+            "elapsed_since_start_ns": str,
+            "thread_id": ThreadId,
+            "stack_id": int,
+        },
+    )
+
+    ProcessedProfile = TypedDict(
+        "ProcessedProfile",
+        {
+            "frames": List[ProcessedFrame],
+            "stacks": List[ProcessedStack],
+            "samples": List[ProcessedSample],
+            "thread_metadata": Dict[ThreadId, ProcessedThreadMetadata],
+        },
+    )
+
+
+try:
+    from gevent.monkey import get_original
+    from gevent.threadpool import ThreadPool as _ThreadPool
+
+    ThreadPool = _ThreadPool  # type: Optional[Type[_ThreadPool]]
+    thread_sleep = get_original("time", "sleep")
+except ImportError:
+    thread_sleep = time.sleep
+
+    ThreadPool = None
+
+
+_scheduler = None  # type: Optional[Scheduler]
+
+
+# The minimum number of unique samples that must exist in a profile to be
+# considered valid.
+PROFILE_MINIMUM_SAMPLES = 2
+
+
+def has_profiling_enabled(options):
+    # type: (Dict[str, Any]) -> bool
+    profiles_sampler = options["profiles_sampler"]
+    if profiles_sampler is not None:
+        return True
+
+    profiles_sample_rate = options["profiles_sample_rate"]
+    if profiles_sample_rate is not None and profiles_sample_rate > 0:
+        return True
+
+    profiles_sample_rate = options["_experiments"].get("profiles_sample_rate")
+    if profiles_sample_rate is not None:
+        logger.warning(
+            "_experiments['profiles_sample_rate'] is deprecated. "
+            "Please use the non-experimental profiles_sample_rate option "
+            "directly."
+        )
+        if profiles_sample_rate > 0:
+            return True
+
+    return False
+
+
+def setup_profiler(options):
+    # type: (Dict[str, Any]) -> bool
+    global _scheduler
+
+    if _scheduler is not None:
+        logger.debug("[Profiling] Profiler is already setup")
+        return False
+
+    frequency = DEFAULT_SAMPLING_FREQUENCY
+
+    if is_gevent():
+        # If gevent has patched the threading modules then we cannot rely on
+        # them to spawn a native thread for sampling.
+        # Instead we default to the GeventScheduler which is capable of
+        # spawning native threads within gevent.
+        default_profiler_mode = GeventScheduler.mode
+    else:
+        default_profiler_mode = ThreadScheduler.mode
+
+    if options.get("profiler_mode") is not None:
+        profiler_mode = options["profiler_mode"]
+    else:
+        profiler_mode = options.get("_experiments", {}).get("profiler_mode")
+        if profiler_mode is not None:
+            logger.warning(
+                "_experiments['profiler_mode'] is deprecated. Please use the "
+                "non-experimental profiler_mode option directly."
+            )
+        profiler_mode = profiler_mode or default_profiler_mode
+
+    if (
+        profiler_mode == ThreadScheduler.mode
+        # for legacy reasons, we'll keep supporting sleep mode for this scheduler
+        or profiler_mode == "sleep"
+    ):
+        _scheduler = ThreadScheduler(frequency=frequency)
+    elif profiler_mode == GeventScheduler.mode:
+        _scheduler = GeventScheduler(frequency=frequency)
+    else:
+        raise ValueError("Unknown profiler mode: {}".format(profiler_mode))
+
+    logger.debug(
+        "[Profiling] Setting up profiler in {mode} mode".format(mode=_scheduler.mode)
+    )
+    _scheduler.setup()
+
+    atexit.register(teardown_profiler)
+
+    return True
+
+
+def teardown_profiler():
+    # type: () -> None
+
+    global _scheduler
+
+    if _scheduler is not None:
+        _scheduler.teardown()
+
+    _scheduler = None
+
+
+MAX_PROFILE_DURATION_NS = int(3e10)  # 30 seconds
+
+
+class Profile:
+    def __init__(
+        self,
+        sampled,  # type: Optional[bool]
+        start_ns,  # type: int
+        hub=None,  # type: Optional[sentry_sdk.Hub]
+        scheduler=None,  # type: Optional[Scheduler]
+    ):
+        # type: (...) -> None
+        self.scheduler = _scheduler if scheduler is None else scheduler
+
+        self.event_id = uuid.uuid4().hex  # type: str
+
+        self.sampled = sampled  # type: Optional[bool]
+
+        # Various framework integrations are capable of overwriting the active thread id.
+        # If it is set to `None` at the end of the profile, we fall back to the default.
+        self._default_active_thread_id = get_current_thread_meta()[0] or 0  # type: int
+        self.active_thread_id = None  # type: Optional[int]
+
+        try:
+            self.start_ns = start_ns  # type: int
+        except AttributeError:
+            self.start_ns = 0
+
+        self.stop_ns = 0  # type: int
+        self.active = False  # type: bool
+
+        self.indexed_frames = {}  # type: Dict[FrameId, int]
+        self.indexed_stacks = {}  # type: Dict[StackId, int]
+        self.frames = []  # type: List[ProcessedFrame]
+        self.stacks = []  # type: List[ProcessedStack]
+        self.samples = []  # type: List[ProcessedSample]
+
+        self.unique_samples = 0
+
+        # Backwards compatibility with the old hub property
+        self._hub = None  # type: Optional[sentry_sdk.Hub]
+        if hub is not None:
+            self._hub = hub
+            warnings.warn(
+                "The `hub` parameter is deprecated. Please do not use it.",
+                DeprecationWarning,
+                stacklevel=2,
+            )
+
+    def update_active_thread_id(self):
+        # type: () -> None
+        self.active_thread_id = get_current_thread_meta()[0]
+        logger.debug(
+            "[Profiling] updating active thread id to {tid}".format(
+                tid=self.active_thread_id
+            )
+        )
+
+    def _set_initial_sampling_decision(self, sampling_context):
+        # type: (SamplingContext) -> None
+        """
+        Sets the profile's sampling decision according to the following
+        precedence rules:
+
+        1. If the transaction to be profiled is not sampled, that decision
+        will be used, regardless of anything else.
+
+        2. Use `profiles_sample_rate` to decide.
+        """
+
+        # The corresponding transaction was not sampled,
+        # so don't generate a profile for it.
+        if not self.sampled:
+            logger.debug(
+                "[Profiling] Discarding profile because transaction is discarded."
+            )
+            self.sampled = False
+            return
+
+        # The profiler hasn't been properly initialized.
+        if self.scheduler is None:
+            logger.debug(
+                "[Profiling] Discarding profile because profiler was not started."
+            )
+            self.sampled = False
+            return
+
+        client = sentry_sdk.get_client()
+        if not client.is_active():
+            self.sampled = False
+            return
+
+        options = client.options
+
+        if callable(options.get("profiles_sampler")):
+            sample_rate = options["profiles_sampler"](sampling_context)
+        elif options["profiles_sample_rate"] is not None:
+            sample_rate = options["profiles_sample_rate"]
+        else:
+            sample_rate = options["_experiments"].get("profiles_sample_rate")
+
+        # The profiles_sample_rate option was not set, so profiling
+        # was never enabled.
+        if sample_rate is None:
+            logger.debug(
+                "[Profiling] Discarding profile because profiling was not enabled."
+            )
+            self.sampled = False
+            return
+
+        if not is_valid_sample_rate(sample_rate, source="Profiling"):
+            logger.warning(
+                "[Profiling] Discarding profile because of invalid sample rate."
+            )
+            self.sampled = False
+            return
+
+        # Now we roll the dice. random.random is inclusive of 0, but not of 1,
+        # so strict < is safe here. In case sample_rate is a boolean, cast it
+        # to a float (True becomes 1.0 and False becomes 0.0)
+        self.sampled = random.random() < float(sample_rate)
+
+        if self.sampled:
+            logger.debug("[Profiling] Initializing profile")
+        else:
+            logger.debug(
+                "[Profiling] Discarding profile because it's not included in the random sample (sample rate = {sample_rate})".format(
+                    sample_rate=float(sample_rate)
+                )
+            )
+
+    def start(self):
+        # type: () -> None
+        if not self.sampled or self.active:
+            return
+
+        assert self.scheduler, "No scheduler specified"
+        logger.debug("[Profiling] Starting profile")
+        self.active = True
+        if not self.start_ns:
+            self.start_ns = nanosecond_time()
+        self.scheduler.start_profiling(self)
+
+    def stop(self):
+        # type: () -> None
+        if not self.sampled or not self.active:
+            return
+
+        assert self.scheduler, "No scheduler specified"
+        logger.debug("[Profiling] Stopping profile")
+        self.active = False
+        self.stop_ns = nanosecond_time()
+
+    def __enter__(self):
+        # type: () -> Profile
+        scope = sentry_sdk.get_isolation_scope()
+        old_profile = scope.profile
+        scope.profile = self
+
+        self._context_manager_state = (scope, old_profile)
+
+        self.start()
+
+        return self
+
+    def __exit__(self, ty, value, tb):
+        # type: (Optional[Any], Optional[Any], Optional[Any]) -> None
+        self.stop()
+
+        scope, old_profile = self._context_manager_state
+        del self._context_manager_state
+
+        scope.profile = old_profile
+
+    def write(self, ts, sample):
+        # type: (int, ExtractedSample) -> None
+        if not self.active:
+            return
+
+        if ts < self.start_ns:
+            return
+
+        offset = ts - self.start_ns
+        if offset > MAX_PROFILE_DURATION_NS:
+            self.stop()
+            return
+
+        self.unique_samples += 1
+
+        elapsed_since_start_ns = str(offset)
+
+        for tid, (stack_id, frame_ids, frames) in sample:
+            try:
+                # Check if the stack is indexed first, this lets us skip
+                # indexing frames if it's not necessary
+                if stack_id not in self.indexed_stacks:
+                    for i, frame_id in enumerate(frame_ids):
+                        if frame_id not in self.indexed_frames:
+                            self.indexed_frames[frame_id] = len(self.indexed_frames)
+                            self.frames.append(frames[i])
+
+                    self.indexed_stacks[stack_id] = len(self.indexed_stacks)
+                    self.stacks.append(
+                        [self.indexed_frames[frame_id] for frame_id in frame_ids]
+                    )
+
+                self.samples.append(
+                    {
+                        "elapsed_since_start_ns": elapsed_since_start_ns,
+                        "thread_id": tid,
+                        "stack_id": self.indexed_stacks[stack_id],
+                    }
+                )
+            except AttributeError:
+                # For some reason, the frame we get doesn't have certain attributes.
+                # When this happens, we abandon the current sample as it's bad.
+                capture_internal_exception(sys.exc_info())
+
+    def process(self):
+        # type: () -> ProcessedProfile
+
+        # This collects the thread metadata at the end of a profile. Doing it
+        # this way means that any threads that terminate before the profile ends
+        # will not have any metadata associated with it.
+        thread_metadata = {
+            str(thread.ident): {
+                "name": str(thread.name),
+            }
+            for thread in threading.enumerate()
+        }  # type: Dict[str, ProcessedThreadMetadata]
+
+        return {
+            "frames": self.frames,
+            "stacks": self.stacks,
+            "samples": self.samples,
+            "thread_metadata": thread_metadata,
+        }
+
+    def to_json(self, event_opt, options):
+        # type: (Event, Dict[str, Any]) -> Dict[str, Any]
+        profile = self.process()
+
+        set_in_app_in_frames(
+            profile["frames"],
+            options["in_app_exclude"],
+            options["in_app_include"],
+            options["project_root"],
+        )
+
+        return {
+            "environment": event_opt.get("environment"),
+            "event_id": self.event_id,
+            "platform": "python",
+            "profile": profile,
+            "release": event_opt.get("release", ""),
+            "timestamp": event_opt["start_timestamp"],
+            "version": "1",
+            "device": {
+                "architecture": platform.machine(),
+            },
+            "os": {
+                "name": platform.system(),
+                "version": platform.release(),
+            },
+            "runtime": {
+                "name": platform.python_implementation(),
+                "version": platform.python_version(),
+            },
+            "transactions": [
+                {
+                    "id": event_opt["event_id"],
+                    "name": event_opt["transaction"],
+                    # we start the transaction before the profile and this is
+                    # the transaction start time relative to the profile, so we
+                    # hardcode it to 0 until we can start the profile before
+                    "relative_start_ns": "0",
+                    # use the duration of the profile instead of the transaction
+                    # because we end the transaction after the profile
+                    "relative_end_ns": str(self.stop_ns - self.start_ns),
+                    "trace_id": event_opt["contexts"]["trace"]["trace_id"],
+                    "active_thread_id": str(
+                        self._default_active_thread_id
+                        if self.active_thread_id is None
+                        else self.active_thread_id
+                    ),
+                }
+            ],
+        }
+
+    def valid(self):
+        # type: () -> bool
+        client = sentry_sdk.get_client()
+        if not client.is_active():
+            return False
+
+        if not has_profiling_enabled(client.options):
+            return False
+
+        if self.sampled is None or not self.sampled:
+            if client.transport:
+                client.transport.record_lost_event(
+                    "sample_rate", data_category="profile"
+                )
+            return False
+
+        if self.unique_samples < PROFILE_MINIMUM_SAMPLES:
+            if client.transport:
+                client.transport.record_lost_event(
+                    "insufficient_data", data_category="profile"
+                )
+            logger.debug("[Profiling] Discarding profile because insufficient samples.")
+            return False
+
+        return True
+
+    @property
+    def hub(self):
+        # type: () -> Optional[sentry_sdk.Hub]
+        warnings.warn(
+            "The `hub` attribute is deprecated. Please do not access it.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        return self._hub
+
+    @hub.setter
+    def hub(self, value):
+        # type: (Optional[sentry_sdk.Hub]) -> None
+        warnings.warn(
+            "The `hub` attribute is deprecated. Please do not set it.",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        self._hub = value
+
+
+class Scheduler(ABC):
+    mode = "unknown"  # type: ProfilerMode
+
+    def __init__(self, frequency):
+        # type: (int) -> None
+        self.interval = 1.0 / frequency
+
+        self.sampler = self.make_sampler()
+
+        # cap the number of new profiles at any time so it does not grow infinitely
+        self.new_profiles = deque(maxlen=128)  # type: Deque[Profile]
+        self.active_profiles = set()  # type: Set[Profile]
+
+    def __enter__(self):
+        # type: () -> Scheduler
+        self.setup()
+        return self
+
+    def __exit__(self, ty, value, tb):
+        # type: (Optional[Any], Optional[Any], Optional[Any]) -> None
+        self.teardown()
+
+    @abstractmethod
+    def setup(self):
+        # type: () -> None
+        pass
+
+    @abstractmethod
+    def teardown(self):
+        # type: () -> None
+        pass
+
+    def ensure_running(self):
+        # type: () -> None
+        """
+        Ensure the scheduler is running. By default, this method is a no-op.
+        The method should be overridden by any implementation for which it is
+        relevant.
+        """
+        return None
+
+    def start_profiling(self, profile):
+        # type: (Profile) -> None
+        self.ensure_running()
+        self.new_profiles.append(profile)
+
+    def make_sampler(self):
+        # type: () -> Callable[..., None]
+        cwd = os.getcwd()
+
+        cache = LRUCache(max_size=256)
+
+        def _sample_stack(*args, **kwargs):
+            # type: (*Any, **Any) -> None
+            """
+            Take a sample of the stack on all the threads in the process.
+            This should be called at a regular interval to collect samples.
+            """
+            # no profiles taking place, so we can stop early
+            if not self.new_profiles and not self.active_profiles:
+                # make sure to clear the cache if we're not profiling so we dont
+                # keep a reference to the last stack of frames around
+                return
+
+            # This is the number of profiles we want to pop off.
+            # It's possible another thread adds a new profile to
+            # the list and we spend longer than we want inside
+            # the loop below.
+            #
+            # Also make sure to set this value before extracting
+            # frames so we do not write to any new profiles that
+            # were started after this point.
+            new_profiles = len(self.new_profiles)
+
+            now = nanosecond_time()
+
+            try:
+                sample = [
+                    (str(tid), extract_stack(frame, cache, cwd))
+                    for tid, frame in sys._current_frames().items()
+                ]
+            except AttributeError:
+                # For some reason, the frame we get doesn't have certain attributes.
+                # When this happens, we abandon the current sample as it's bad.
+                capture_internal_exception(sys.exc_info())
+                return
+
+            # Move the new profiles into the active_profiles set.
+            #
+            # We cannot directly add the to active_profiles set
+            # in `start_profiling` because it is called from other
+            # threads which can cause a RuntimeError when it the
+            # set sizes changes during iteration without a lock.
+            #
+            # We also want to avoid using a lock here so threads
+            # that are starting profiles are not blocked until it
+            # can acquire the lock.
+            for _ in range(new_profiles):
+                self.active_profiles.add(self.new_profiles.popleft())
+
+            inactive_profiles = []
+
+            for profile in self.active_profiles:
+                if profile.active:
+                    profile.write(now, sample)
+                else:
+                    # If a profile is marked inactive, we buffer it
+                    # to `inactive_profiles` so it can be removed.
+                    # We cannot remove it here as it would result
+                    # in a RuntimeError.
+                    inactive_profiles.append(profile)
+
+            for profile in inactive_profiles:
+                self.active_profiles.remove(profile)
+
+        return _sample_stack
+
+
+class ThreadScheduler(Scheduler):
+    """
+    This scheduler is based on running a daemon thread that will call
+    the sampler at a regular interval.
+    """
+
+    mode = "thread"  # type: ProfilerMode
+    name = "sentry.profiler.ThreadScheduler"
+
+    def __init__(self, frequency):
+        # type: (int) -> None
+        super().__init__(frequency=frequency)
+
+        # used to signal to the thread that it should stop
+        self.running = False
+        self.thread = None  # type: Optional[threading.Thread]
+        self.pid = None  # type: Optional[int]
+        self.lock = threading.Lock()
+
+    def setup(self):
+        # type: () -> None
+        pass
+
+    def teardown(self):
+        # type: () -> None
+        if self.running:
+            self.running = False
+            if self.thread is not None:
+                self.thread.join()
+
+    def ensure_running(self):
+        # type: () -> None
+        """
+        Check that the profiler has an active thread to run in, and start one if
+        that's not the case.
+
+        Note that this might fail (e.g. in Python 3.12 it's not possible to
+        spawn new threads at interpreter shutdown). In that case self.running
+        will be False after running this function.
+        """
+        pid = os.getpid()
+
+        # is running on the right process
+        if self.running and self.pid == pid:
+            return
+
+        with self.lock:
+            # another thread may have tried to acquire the lock
+            # at the same time so it may start another thread
+            # make sure to check again before proceeding
+            if self.running and self.pid == pid:
+                return
+
+            self.pid = pid
+            self.running = True
+
+            # make sure the thread is a daemon here otherwise this
+            # can keep the application running after other threads
+            # have exited
+            self.thread = threading.Thread(name=self.name, target=self.run, daemon=True)
+            try:
+                self.thread.start()
+            except RuntimeError:
+                # Unfortunately at this point the interpreter is in a state that no
+                # longer allows us to spawn a thread and we have to bail.
+                self.running = False
+                self.thread = None
+                return
+
+    def run(self):
+        # type: () -> None
+        last = time.perf_counter()
+
+        while self.running:
+            self.sampler()
+
+            # some time may have elapsed since the last time
+            # we sampled, so we need to account for that and
+            # not sleep for too long
+            elapsed = time.perf_counter() - last
+            if elapsed < self.interval:
+                thread_sleep(self.interval - elapsed)
+
+            # after sleeping, make sure to take the current
+            # timestamp so we can use it next iteration
+            last = time.perf_counter()
+
+
+class GeventScheduler(Scheduler):
+    """
+    This scheduler is based on the thread scheduler but adapted to work with
+    gevent. When using gevent, it may monkey patch the threading modules
+    (`threading` and `_thread`). This results in the use of greenlets instead
+    of native threads.
+
+    This is an issue because the sampler CANNOT run in a greenlet because
+    1. Other greenlets doing sync work will prevent the sampler from running
+    2. The greenlet runs in the same thread as other greenlets so when taking
+       a sample, other greenlets will have been evicted from the thread. This
+       results in a sample containing only the sampler's code.
+    """
+
+    mode = "gevent"  # type: ProfilerMode
+    name = "sentry.profiler.GeventScheduler"
+
+    def __init__(self, frequency):
+        # type: (int) -> None
+
+        if ThreadPool is None:
+            raise ValueError("Profiler mode: {} is not available".format(self.mode))
+
+        super().__init__(frequency=frequency)
+
+        # used to signal to the thread that it should stop
+        self.running = False
+        self.thread = None  # type: Optional[_ThreadPool]
+        self.pid = None  # type: Optional[int]
+
+        # This intentionally uses the gevent patched threading.Lock.
+        # The lock will be required when first trying to start profiles
+        # as we need to spawn the profiler thread from the greenlets.
+        self.lock = threading.Lock()
+
+    def setup(self):
+        # type: () -> None
+        pass
+
+    def teardown(self):
+        # type: () -> None
+        if self.running:
+            self.running = False
+            if self.thread is not None:
+                self.thread.join()
+
+    def ensure_running(self):
+        # type: () -> None
+        pid = os.getpid()
+
+        # is running on the right process
+        if self.running and self.pid == pid:
+            return
+
+        with self.lock:
+            # another thread may have tried to acquire the lock
+            # at the same time so it may start another thread
+            # make sure to check again before proceeding
+            if self.running and self.pid == pid:
+                return
+
+            self.pid = pid
+            self.running = True
+
+            self.thread = ThreadPool(1)  # type: ignore[misc]
+            try:
+                self.thread.spawn(self.run)
+            except RuntimeError:
+                # Unfortunately at this point the interpreter is in a state that no
+                # longer allows us to spawn a thread and we have to bail.
+                self.running = False
+                self.thread = None
+                return
+
+    def run(self):
+        # type: () -> None
+        last = time.perf_counter()
+
+        while self.running:
+            self.sampler()
+
+            # some time may have elapsed since the last time
+            # we sampled, so we need to account for that and
+            # not sleep for too long
+            elapsed = time.perf_counter() - last
+            if elapsed < self.interval:
+                thread_sleep(self.interval - elapsed)
+
+            # after sleeping, make sure to take the current
+            # timestamp so we can use it next iteration
+            last = time.perf_counter()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/utils.py b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..3554cddb5d0acf0991eb273f99aab9aab89389be
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/sentry_sdk/profiler/utils.py
@@ -0,0 +1,199 @@
+import os
+from collections import deque
+
+from sentry_sdk._compat import PY311
+from sentry_sdk.utils import filename_for_module
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from sentry_sdk._lru_cache import LRUCache
+    from types import FrameType
+    from typing import Deque
+    from typing import List
+    from typing import Optional
+    from typing import Sequence
+    from typing import Tuple
+    from typing_extensions import TypedDict
+
+    ThreadId = str
+
+    ProcessedStack = List[int]
+
+    ProcessedFrame = TypedDict(
+        "ProcessedFrame",
+        {
+            "abs_path": str,
+            "filename": Optional[str],
+            "function": str,
+            "lineno": int,
+            "module": Optional[str],
+        },
+    )
+
+    ProcessedThreadMetadata = TypedDict(
+        "ProcessedThreadMetadata",
+        {"name": str},
+    )
+
+    FrameId = Tuple[
+        str,  # abs_path
+        int,  # lineno
+        str,  # function
+    ]
+    FrameIds = Tuple[FrameId, ...]
+
+    # The exact value of this id is not very meaningful. The purpose
+    # of this id is to give us a compact and unique identifier for a
+    # raw stack that can be used as a key to a dictionary so that it
+    # can be used during the sampled format generation.
+    StackId = Tuple[int, int]
+
+    ExtractedStack = Tuple[StackId, FrameIds, List[ProcessedFrame]]
+    ExtractedSample = Sequence[Tuple[ThreadId, ExtractedStack]]
+
+# The default sampling frequency to use. This is set at 101 in order to
+# mitigate the effects of lockstep sampling.
+DEFAULT_SAMPLING_FREQUENCY = 101
+
+
+# We want to impose a stack depth limit so that samples aren't too large.
+MAX_STACK_DEPTH = 128
+
+
+if PY311:
+
+    def get_frame_name(frame):
+        # type: (FrameType) -> str
+        return frame.f_code.co_qualname
+
+else:
+
+    def get_frame_name(frame):
+        # type: (FrameType) -> str
+
+        f_code = frame.f_code
+        co_varnames = f_code.co_varnames
+
+        # co_name only contains the frame name.  If the frame was a method,
+        # the class name will NOT be included.
+        name = f_code.co_name
+
+        # if it was a method, we can get the class name by inspecting
+        # the f_locals for the `self` argument
+        try:
+            if (
+                # the co_varnames start with the frame's positional arguments
+                # and we expect the first to be `self` if its an instance method
+                co_varnames
+                and co_varnames[0] == "self"
+                and "self" in frame.f_locals
+            ):
+                for cls in type(frame.f_locals["self"]).__mro__:
+                    if name in cls.__dict__:
+                        return "{}.{}".format(cls.__name__, name)
+        except (AttributeError, ValueError):
+            pass
+
+        # if it was a class method, (decorated with `@classmethod`)
+        # we can get the class name by inspecting the f_locals for the `cls` argument
+        try:
+            if (
+                # the co_varnames start with the frame's positional arguments
+                # and we expect the first to be `cls` if its a class method
+                co_varnames
+                and co_varnames[0] == "cls"
+                and "cls" in frame.f_locals
+            ):
+                for cls in frame.f_locals["cls"].__mro__:
+                    if name in cls.__dict__:
+                        return "{}.{}".format(cls.__name__, name)
+        except (AttributeError, ValueError):
+            pass
+
+        # nothing we can do if it is a staticmethod (decorated with @staticmethod)
+
+        # we've done all we can, time to give up and return what we have
+        return name
+
+
+def frame_id(raw_frame):
+    # type: (FrameType) -> FrameId
+    return (raw_frame.f_code.co_filename, raw_frame.f_lineno, get_frame_name(raw_frame))
+
+
+def extract_frame(fid, raw_frame, cwd):
+    # type: (FrameId, FrameType, str) -> ProcessedFrame
+    abs_path = raw_frame.f_code.co_filename
+
+    try:
+        module = raw_frame.f_globals["__name__"]
+    except Exception:
+        module = None
+
+    # namedtuples can be many times slower when initialing
+    # and accessing attribute so we opt to use a tuple here instead
+    return {
+        # This originally was `os.path.abspath(abs_path)` but that had
+        # a large performance overhead.
+        #
+        # According to docs, this is equivalent to
+        # `os.path.normpath(os.path.join(os.getcwd(), path))`.
+        # The `os.getcwd()` call is slow here, so we precompute it.
+        #
+        # Additionally, since we are using normalized path already,
+        # we skip calling `os.path.normpath` entirely.
+        "abs_path": os.path.join(cwd, abs_path),
+        "module": module,
+        "filename": filename_for_module(module, abs_path) or None,
+        "function": fid[2],
+        "lineno": raw_frame.f_lineno,
+    }
+
+
+def extract_stack(
+    raw_frame,  # type: Optional[FrameType]
+    cache,  # type: LRUCache
+    cwd,  # type: str
+    max_stack_depth=MAX_STACK_DEPTH,  # type: int
+):
+    # type: (...) -> ExtractedStack
+    """
+    Extracts the stack starting the specified frame. The extracted stack
+    assumes the specified frame is the top of the stack, and works back
+    to the bottom of the stack.
+
+    In the event that the stack is more than `MAX_STACK_DEPTH` frames deep,
+    only the first `MAX_STACK_DEPTH` frames will be returned.
+    """
+
+    raw_frames = deque(maxlen=max_stack_depth)  # type: Deque[FrameType]
+
+    while raw_frame is not None:
+        f_back = raw_frame.f_back
+        raw_frames.append(raw_frame)
+        raw_frame = f_back
+
+    frame_ids = tuple(frame_id(raw_frame) for raw_frame in raw_frames)
+    frames = []
+    for i, fid in enumerate(frame_ids):
+        frame = cache.get(fid)
+        if frame is None:
+            frame = extract_frame(fid, raw_frames[i], cwd)
+            cache.set(fid, frame)
+        frames.append(frame)
+
+    # Instead of mapping the stack into frame ids and hashing
+    # that as a tuple, we can directly hash the stack.
+    # This saves us from having to generate yet another list.
+    # Additionally, using the stack as the key directly is
+    # costly because the stack can be large, so we pre-hash
+    # the stack, and use the hash as the key as this will be
+    # needed a few times to improve performance.
+    #
+    # To Reduce the likelihood of hash collisions, we include
+    # the stack depth. This means that only stacks of the same
+    # depth can suffer from hash collisions.
+    stack_id = len(raw_frames), hash(frame_ids)
+
+    return stack_id, frame_ids, frames
diff --git a/tool_server/.venv/lib/python3.12/site-packages/soxr-0.5.0.post1.dist-info/licenses/COPYING.LGPL b/tool_server/.venv/lib/python3.12/site-packages/soxr-0.5.0.post1.dist-info/licenses/COPYING.LGPL
new file mode 100644
index 0000000000000000000000000000000000000000..551cb4acb9d8ce4270b11c8267704c2fb447f22b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/soxr-0.5.0.post1.dist-info/licenses/COPYING.LGPL
@@ -0,0 +1,502 @@
+		  GNU LESSER GENERAL PUBLIC LICENSE
+		       Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL.  It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+			    Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+  This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it.  You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+  When we speak of free software, we are referring to freedom of use,
+not price.  Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+  To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights.  These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+  For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you.  You must make sure that they, too, receive or can get the source
+code.  If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it.  And you must show them these terms so they know their rights.
+
+  We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+  To protect each distributor, we want to make it very clear that
+there is no warranty for the free library.  Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+  Finally, software patents pose a constant threat to the existence of
+any free program.  We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder.  Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+  Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License.  This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License.  We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+  When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library.  The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom.  The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+  We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License.  It also provides other free software developers Less
+of an advantage over competing non-free programs.  These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries.  However, the Lesser license provides advantages in certain
+special circumstances.
+
+  For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard.  To achieve this, non-free programs must be
+allowed to use the library.  A more frequent case is that a free
+library does the same job as widely used non-free libraries.  In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+  In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software.  For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+  Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.  Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library".  The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+		  GNU LESSER GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+  A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+  The "Library", below, refers to any such software library or work
+which has been distributed under these terms.  A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language.  (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+  "Source code" for a work means the preferred form of the work for
+making modifications to it.  For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+  Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it).  Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+  1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+  You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+  2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) The modified work must itself be a software library.
+
+    b) You must cause the files modified to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    c) You must cause the whole of the work to be licensed at no
+    charge to all third parties under the terms of this License.
+
+    d) If a facility in the modified Library refers to a function or a
+    table of data to be supplied by an application program that uses
+    the facility, other than as an argument passed when the facility
+    is invoked, then you must make a good faith effort to ensure that,
+    in the event an application does not supply such function or
+    table, the facility still operates, and performs whatever part of
+    its purpose remains meaningful.
+
+    (For example, a function in a library to compute square roots has
+    a purpose that is entirely well-defined independent of the
+    application.  Therefore, Subsection 2d requires that any
+    application-supplied function or table used by this function must
+    be optional: if the application does not supply it, the square
+    root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library.  To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License.  (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.)  Do not make any other change in
+these notices.
+
+  Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+  This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+  4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+  If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library".  Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+  However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library".  The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+  When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library.  The
+threshold for this to be true is not precisely defined by law.
+
+  If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work.  (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+  Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+  6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+  You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License.  You must supply a copy of this License.  If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License.  Also, you must do one
+of these things:
+
+    a) Accompany the work with the complete corresponding
+    machine-readable source code for the Library including whatever
+    changes were used in the work (which must be distributed under
+    Sections 1 and 2 above); and, if the work is an executable linked
+    with the Library, with the complete machine-readable "work that
+    uses the Library", as object code and/or source code, so that the
+    user can modify the Library and then relink to produce a modified
+    executable containing the modified Library.  (It is understood
+    that the user who changes the contents of definitions files in the
+    Library will not necessarily be able to recompile the application
+    to use the modified definitions.)
+
+    b) Use a suitable shared library mechanism for linking with the
+    Library.  A suitable mechanism is one that (1) uses at run time a
+    copy of the library already present on the user's computer system,
+    rather than copying library functions into the executable, and (2)
+    will operate properly with a modified version of the library, if
+    the user installs one, as long as the modified version is
+    interface-compatible with the version that the work was made with.
+
+    c) Accompany the work with a written offer, valid for at
+    least three years, to give the same user the materials
+    specified in Subsection 6a, above, for a charge no more
+    than the cost of performing this distribution.
+
+    d) If distribution of the work is made by offering access to copy
+    from a designated place, offer equivalent access to copy the above
+    specified materials from the same place.
+
+    e) Verify that the user has already received a copy of these
+    materials or that you have already sent this user a copy.
+
+  For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it.  However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+  It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system.  Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+  7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+    a) Accompany the combined library with a copy of the same work
+    based on the Library, uncombined with any other library
+    facilities.  This must be distributed under the terms of the
+    Sections above.
+
+    b) Give prominent notice with the combined library of the fact
+    that part of it is a work based on the Library, and explaining
+    where to find the accompanying uncombined form of the same work.
+
+  8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License.  Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License.  However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+  9. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Library or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+  10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+  11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded.  In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+  13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation.  If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+  14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission.  For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this.  Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+			    NO WARRANTY
+
+  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+		     END OF TERMS AND CONDITIONS
+
+           How to Apply These Terms to Your New Libraries
+
+  If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change.  You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+  To apply these terms, attach the following notices to the library.  It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+    
+    Copyright (C)   
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the
+  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+  , 1 April 1990
+  Ty Coon, President of Vice
+
+That's all there is to it!
diff --git a/tool_server/.venv/lib/python3.12/site-packages/soxr-0.5.0.post1.dist-info/licenses/LICENSE-PFFFT.txt b/tool_server/.venv/lib/python3.12/site-packages/soxr-0.5.0.post1.dist-info/licenses/LICENSE-PFFFT.txt
new file mode 100644
index 0000000000000000000000000000000000000000..fa3a3618b1562e95368979c74bbb6bc28cf822de
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/soxr-0.5.0.post1.dist-info/licenses/LICENSE-PFFFT.txt
@@ -0,0 +1,52 @@
+Copyright (c) 2013  Julien Pommier ( pommier@modartt.com )
+
+Based on original fortran 77 code from FFTPACKv4 from NETLIB
+(http://www.netlib.org/fftpack), authored by Dr Paul Swarztrauber
+of NCAR, in 1985.
+
+As confirmed by the NCAR fftpack software curators, the following
+FFTPACKv5 license applies to FFTPACKv4 sources. My changes are
+released under the same terms.
+
+FFTPACK license:
+
+http://www.cisl.ucar.edu/css/software/fftpack5/ftpk.html
+
+Copyright (c) 2004 the University Corporation for Atmospheric
+Research ("UCAR"). All rights reserved. Developed by NCAR's
+Computational and Information Systems Laboratory, UCAR,
+www.cisl.ucar.edu.
+
+Redistribution and use of the Software in source and binary forms,
+with or without modification, is permitted provided that the
+following conditions are met:
+
+- Neither the names of NCAR's Computational and Information Systems
+Laboratory, the University Corporation for Atmospheric Research,
+nor the names of its sponsors or contributors may be used to
+endorse or promote products derived from this Software without
+specific prior written permission.
+
+- Redistributions of source code must retain the above copyright
+notices, this list of conditions, and the disclaimer below.
+
+- Redistributions in binary form must reproduce the above copyright
+notice, this list of conditions, and the disclaimer below in the
+documentation and/or other materials provided with the
+distribution.
+
+THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT
+HOLDERS BE LIABLE FOR ANY CLAIM, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+SOFTWARE.
+
+
+PFFFT : a Pretty Fast FFT.
+
+This file is largerly based on the original FFTPACK implementation, modified in
+order to take advantage of SIMD instructions of modern CPUs.
diff --git a/tool_server/.venv/lib/python3.12/site-packages/soxr-0.5.0.post1.dist-info/licenses/LICENSE-libsoxr.txt b/tool_server/.venv/lib/python3.12/site-packages/soxr-0.5.0.post1.dist-info/licenses/LICENSE-libsoxr.txt
new file mode 100644
index 0000000000000000000000000000000000000000..43e5a7165867ba2bdcfcec5719b07adf3329545e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/soxr-0.5.0.post1.dist-info/licenses/LICENSE-libsoxr.txt
@@ -0,0 +1,23 @@
+SoX Resampler Library       Copyright (c) 2007-18 robs@users.sourceforge.net
+
+This library is free software; you can redistribute it and/or modify it
+under the terms of the GNU Lesser General Public License as published by
+the Free Software Foundation; either version 2.1 of the License, or (at
+your option) any later version.
+
+This library is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
+General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License
+along with this library; if not, see .
+
+
+Notes
+
+1. Re software in the `examples' directory: works that are not resampling
+examples but are based on the given examples -- for example, applications using
+the library -- shall not be considered to be derivative works of the examples.
+
+2. If building with pffft.c, see the licence embedded in that file.
diff --git a/tool_server/.venv/lib/python3.12/site-packages/soxr-0.5.0.post1.dist-info/licenses/LICENSE.txt b/tool_server/.venv/lib/python3.12/site-packages/soxr-0.5.0.post1.dist-info/licenses/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..5352afe334aa6ca288f2251f7ff2591dd27bd09a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/soxr-0.5.0.post1.dist-info/licenses/LICENSE.txt
@@ -0,0 +1,15 @@
+Python-SoXR, Resampler library for Python.
+Copyright (c) 2021 Myungchul Keum
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License
+along with this library; if not, see .
diff --git a/tool_server/.venv/lib/python3.12/site-packages/soxr/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/soxr/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..15747e3bc51ed1ade2e94de784e245d8d3f59248
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/soxr/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/soxr/__pycache__/_version.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/soxr/__pycache__/_version.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fa7df98e3718cbe81e3b1f93a63afb4244c71fcf
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/soxr/__pycache__/_version.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6a04254390c7cbe5a643c5b94625d2ceaf11c799
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/__pycache__/compiler.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/__pycache__/compiler.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ba35159c14fd452246641f98d572630d5b813ff7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/__pycache__/compiler.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/__pycache__/driver.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/__pycache__/driver.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1efa076f645895a8d977182d254c4c2eb4a221d5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/__pycache__/driver.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/Openacc/cupti_openacc.h b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/Openacc/cupti_openacc.h
new file mode 100644
index 0000000000000000000000000000000000000000..b7ea50da7beb2187e77f7606dd70faed0e4b4add
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/Openacc/cupti_openacc.h
@@ -0,0 +1,98 @@
+/*
+ * Copyright 2017 NVIDIA Corporation.  All rights reserved.
+ *
+ * NOTICE TO LICENSEE:
+ *
+ * This source code and/or documentation ("Licensed Deliverables") are
+ * subject to NVIDIA intellectual property rights under U.S. and
+ * international Copyright laws.
+ *
+ * These Licensed Deliverables contained herein is PROPRIETARY and
+ * CONFIDENTIAL to NVIDIA and is being provided under the terms and
+ * conditions of a form of NVIDIA software license agreement by and
+ * between NVIDIA and Licensee ("License Agreement") or electronically
+ * accepted by Licensee.  Notwithstanding any terms or conditions to
+ * the contrary in the License Agreement, reproduction or disclosure
+ * of the Licensed Deliverables to any third party without the express
+ * written consent of NVIDIA is prohibited.
+ *
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+ * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
+ * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE.  IT IS
+ * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
+ * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
+ * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
+ * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+ * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
+ * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * OF THESE LICENSED DELIVERABLES.
+ *
+ * U.S. Government End Users.  These Licensed Deliverables are a
+ * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
+ * 1995), consisting of "commercial computer software" and "commercial
+ * computer software documentation" as such terms are used in 48
+ * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
+ * only as a commercial end item.  Consistent with 48 C.F.R.12.212 and
+ * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
+ * U.S. Government End Users acquire the Licensed Deliverables with
+ * only those rights set forth herein.
+ *
+ * Any use of the Licensed Deliverables in individual and commercial
+ * software must include, in the user documentation and internal
+ * comments to the code, the above Disclaimer and U.S. Government End
+ * Users Notice.
+ */
+
+#include 
+
+#if !defined(_CUPTI_OPENACC_H_)
+#define _CUPTI_OPENACC_H_
+
+#ifndef CUPTIAPI
+#ifdef _WIN32
+#define CUPTIAPI __stdcall
+#else
+#define CUPTIAPI
+#endif
+#endif
+
+#if defined(__LP64__)
+#define CUPTILP64 1
+#elif defined(_WIN64)
+#define CUPTILP64 1
+#else
+#undef CUPTILP64
+#endif
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+#if defined(__GNUC__) && defined(CUPTI_LIB)
+    #pragma GCC visibility push(default)
+#endif
+
+/**
+ * \brief Initialize OpenACC support
+ *
+ * \param profRegister function of type acc_prof_reg as obtained from acc_register_library
+ * \param profUnregister function of type acc_prof_reg as obtained from acc_register_library
+ * \param profLookup function of type acc_prof_lookup as obtained from acc_register_library
+ */
+CUptiResult CUPTIAPI
+cuptiOpenACCInitialize(void *profRegister, void *profUnregister, void *profLookup);
+
+#if defined(__GNUC__) && defined(CUPTI_LIB)
+    #pragma GCC visibility pop
+#endif
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif /*_CUPTI_OPENACC_H_*/
+
diff --git a/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/Openmp/cupti_openmp.h b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/Openmp/cupti_openmp.h
new file mode 100644
index 0000000000000000000000000000000000000000..303dd42878fb02774d872c197ccc27b17f2af69e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/Openmp/cupti_openmp.h
@@ -0,0 +1,100 @@
+/*
+ * Copyright 2018 NVIDIA Corporation.  All rights reserved.
+ *
+ * NOTICE TO LICENSEE:
+ *
+ * This source code and/or documentation ("Licensed Deliverables") are
+ * subject to NVIDIA intellectual property rights under U.S. and
+ * international Copyright laws.
+ *
+ * These Licensed Deliverables contained herein is PROPRIETARY and
+ * CONFIDENTIAL to NVIDIA and is being provided under the terms and
+ * conditions of a form of NVIDIA software license agreement by and
+ * between NVIDIA and Licensee ("License Agreement") or electronically
+ * accepted by Licensee.  Notwithstanding any terms or conditions to
+ * the contrary in the License Agreement, reproduction or disclosure
+ * of the Licensed Deliverables to any third party without the express
+ * written consent of NVIDIA is prohibited.
+ *
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+ * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
+ * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE.  IT IS
+ * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
+ * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
+ * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
+ * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+ * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
+ * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * OF THESE LICENSED DELIVERABLES.
+ *
+ * U.S. Government End Users.  These Licensed Deliverables are a
+ * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
+ * 1995), consisting of "commercial computer software" and "commercial
+ * computer software documentation" as such terms are used in 48
+ * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
+ * only as a commercial end item.  Consistent with 48 C.F.R.12.212 and
+ * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
+ * U.S. Government End Users acquire the Licensed Deliverables with
+ * only those rights set forth herein.
+ *
+ * Any use of the Licensed Deliverables in individual and commercial
+ * software must include, in the user documentation and internal
+ * comments to the code, the above Disclaimer and U.S. Government End
+ * Users Notice.
+ */
+
+#include 
+#include "Openmp/omp-tools.h"
+
+#if !defined(_CUPTI_OPENMP_H_)
+#define _CUPTI_OPENMP_H_
+
+#ifndef CUPTIAPI
+#ifdef _WIN32
+#define CUPTIAPI __stdcall
+#else
+#define CUPTIAPI
+#endif
+#endif
+
+#if defined(__LP64__)
+#define CUPTILP64 1
+#elif defined(_WIN64)
+#define CUPTILP64 1
+#else
+#undef CUPTILP64
+#endif
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+#if defined(__GNUC__) && defined(CUPTI_LIB)
+    #pragma GCC visibility push(default)
+#endif
+
+/**
+ * \brief Initialize OPENMP support (deprecated, used before OpenMP 5.0)
+ *
+ */
+int CUPTIAPI cuptiOpenMpInitialize(ompt_function_lookup_t ompt_fn_lookup, const char *runtime_version, unsigned int ompt_version);
+
+/**
+ * \brief Initialize OPENMP support
+ *
+ */
+int CUPTIAPI cuptiOpenMpInitialize_v2(ompt_function_lookup_t lookup, int initial_device_num, ompt_data_t *tool_data);
+
+#if defined(__GNUC__) && defined(CUPTI_LIB)
+    #pragma GCC visibility pop
+#endif
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif /*_CUPTI_OPENMP_H_*/
diff --git a/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/Openmp/omp-tools.h b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/Openmp/omp-tools.h
new file mode 100644
index 0000000000000000000000000000000000000000..276967d07e8f8c0f7686e5b3b15151edf2415ae7
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/Openmp/omp-tools.h
@@ -0,0 +1,1083 @@
+/*
+ * include/50/omp-tools.h.var
+ */
+
+//===----------------------------------------------------------------------===//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is dual licensed under the MIT and the University of Illinois Open
+// Source Licenses. See LICENSE.txt for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef __OMPT__
+#define __OMPT__
+
+/*****************************************************************************
+ * system include files
+ *****************************************************************************/
+
+#include 
+#include 
+
+/*****************************************************************************
+ * iteration macros
+ *****************************************************************************/
+
+#define FOREACH_OMPT_INQUIRY_FN(macro)      \
+    macro (ompt_enumerate_states)           \
+    macro (ompt_enumerate_mutex_impls)      \
+                                            \
+    macro (ompt_set_callback)               \
+    macro (ompt_get_callback)               \
+                                            \
+    macro (ompt_get_state)                  \
+                                            \
+    macro (ompt_get_parallel_info)          \
+    macro (ompt_get_task_info)              \
+    macro (ompt_get_task_memory)            \
+    macro (ompt_get_thread_data)            \
+    macro (ompt_get_unique_id)              \
+    macro (ompt_finalize_tool)              \
+                                            \
+    macro(ompt_get_num_procs)               \
+    macro(ompt_get_num_places)              \
+    macro(ompt_get_place_proc_ids)          \
+    macro(ompt_get_place_num)               \
+    macro(ompt_get_partition_place_nums)    \
+    macro(ompt_get_proc_id)                 \
+                                            \
+    macro(ompt_get_target_info)             \
+    macro(ompt_get_num_devices)
+
+#define FOREACH_OMPT_STATE(macro)                                                                \
+                                                                                                \
+    /* first available state */                                                                 \
+    macro (ompt_state_undefined, 0x102)      /* undefined thread state */                        \
+                                                                                                \
+    /* work states (0..15) */                                                                   \
+    macro (ompt_state_work_serial, 0x000)    /* working outside parallel */                      \
+    macro (ompt_state_work_parallel, 0x001)  /* working within parallel */                       \
+    macro (ompt_state_work_reduction, 0x002) /* performing a reduction */                        \
+                                                                                                \
+    /* barrier wait states (16..31) */                                                          \
+    macro (ompt_state_wait_barrier, 0x010)   /* waiting at a barrier */                          \
+    macro (ompt_state_wait_barrier_implicit_parallel, 0x011)                                     \
+                                            /* implicit barrier at the end of parallel region */\
+    macro (ompt_state_wait_barrier_implicit_workshare, 0x012)                                    \
+                                            /* implicit barrier at the end of worksharing */    \
+    macro (ompt_state_wait_barrier_implicit, 0x013)  /* implicit barrier */                      \
+    macro (ompt_state_wait_barrier_explicit, 0x014)  /* explicit barrier */                      \
+                                                                                                \
+    /* task wait states (32..63) */                                                             \
+    macro (ompt_state_wait_taskwait, 0x020)  /* waiting at a taskwait */                         \
+    macro (ompt_state_wait_taskgroup, 0x021) /* waiting at a taskgroup */                        \
+                                                                                                \
+    /* mutex wait states (64..127) */                                                           \
+    macro (ompt_state_wait_mutex, 0x040)                                                         \
+    macro (ompt_state_wait_lock, 0x041)      /* waiting for lock */                              \
+    macro (ompt_state_wait_critical, 0x042)  /* waiting for critical */                          \
+    macro (ompt_state_wait_atomic, 0x043)    /* waiting for atomic */                            \
+    macro (ompt_state_wait_ordered, 0x044)   /* waiting for ordered */                           \
+                                                                                                \
+    /* target wait states (128..255) */                                                         \
+    macro (ompt_state_wait_target, 0x080)        /* waiting for target region */                 \
+    macro (ompt_state_wait_target_map, 0x081)    /* waiting for target data mapping operation */ \
+    macro (ompt_state_wait_target_update, 0x082) /* waiting for target update operation */       \
+                                                                                                \
+    /* misc (256..511) */                                                                       \
+    macro (ompt_state_idle, 0x100)           /* waiting for work */                              \
+    macro (ompt_state_overhead, 0x101)       /* overhead excluding wait states */                \
+                                                                                                \
+    /* implementation-specific states (512..) */
+
+
+#define FOREACH_KMP_MUTEX_IMPL(macro)                                                \
+    macro (kmp_mutex_impl_none, 0)         /* unknown implementation */              \
+    macro (kmp_mutex_impl_spin, 1)         /* based on spin */                       \
+    macro (kmp_mutex_impl_queuing, 2)      /* based on some fair policy */           \
+    macro (kmp_mutex_impl_speculative, 3)  /* based on HW-supported speculation */
+
+#define FOREACH_OMPT_EVENT(macro)                                                                                        \
+                                                                                                                         \
+    /*--- Mandatory Events ---*/                                                                                         \
+    macro (ompt_callback_thread_begin,      ompt_callback_thread_begin_t,       1) /* thread begin                    */ \
+    macro (ompt_callback_thread_end,        ompt_callback_thread_end_t,         2) /* thread end                      */ \
+                                                                                                                         \
+    macro (ompt_callback_parallel_begin,    ompt_callback_parallel_begin_t,     3) /* parallel begin                  */ \
+    macro (ompt_callback_parallel_end,      ompt_callback_parallel_end_t,       4) /* parallel end                    */ \
+                                                                                                                         \
+    macro (ompt_callback_task_create,       ompt_callback_task_create_t,        5) /* task begin                      */ \
+    macro (ompt_callback_task_schedule,     ompt_callback_task_schedule_t,      6) /* task schedule                   */ \
+    macro (ompt_callback_implicit_task,     ompt_callback_implicit_task_t,      7) /* implicit task                   */ \
+                                                                                                                         \
+    macro (ompt_callback_target,            ompt_callback_target_t,             8) /* target                          */ \
+    macro (ompt_callback_target_data_op,    ompt_callback_target_data_op_t,     9) /* target data op                  */ \
+    macro (ompt_callback_target_submit,     ompt_callback_target_submit_t,     10) /* target  submit                  */ \
+                                                                                                                         \
+    macro (ompt_callback_control_tool,      ompt_callback_control_tool_t,      11) /* control tool                    */ \
+                                                                                                                         \
+    macro (ompt_callback_device_initialize, ompt_callback_device_initialize_t, 12) /* device initialize               */ \
+    macro (ompt_callback_device_finalize,   ompt_callback_device_finalize_t,   13) /* device finalize                 */ \
+                                                                                                                         \
+    macro (ompt_callback_device_load,       ompt_callback_device_load_t,       14) /* device load                     */ \
+    macro (ompt_callback_device_unload,     ompt_callback_device_unload_t,     15) /* device unload                   */ \
+                                                                                                                         \
+    /* Optional Events */                                                                                                \
+    macro (ompt_callback_sync_region_wait,  ompt_callback_sync_region_t,       16) /* sync region wait begin or end   */ \
+                                                                                                                         \
+    macro (ompt_callback_mutex_released,    ompt_callback_mutex_t,             17) /* mutex released                  */ \
+                                                                                                                         \
+    macro (ompt_callback_dependences,       ompt_callback_dependences_t,       18) /* report task dependences         */ \
+    macro (ompt_callback_task_dependence,   ompt_callback_task_dependence_t,   19) /* report task dependence          */ \
+                                                                                                                         \
+    macro (ompt_callback_work,              ompt_callback_work_t,              20) /* task at work begin or end       */ \
+                                                                                                                         \
+    macro (ompt_callback_master,            ompt_callback_master_t,            21) /* task at master begin or end     */ \
+                                                                                                                         \
+    macro (ompt_callback_target_map,        ompt_callback_target_map_t,        22) /* target map                      */ \
+                                                                                                                         \
+    macro (ompt_callback_sync_region,       ompt_callback_sync_region_t,       23) /* sync region begin or end        */ \
+                                                                                                                         \
+    macro (ompt_callback_lock_init,         ompt_callback_mutex_acquire_t,     24) /* lock init                       */ \
+    macro (ompt_callback_lock_destroy,      ompt_callback_mutex_t,             25) /* lock destroy                    */ \
+                                                                                                                         \
+    macro (ompt_callback_mutex_acquire,     ompt_callback_mutex_acquire_t,     26) /* mutex acquire                   */ \
+    macro (ompt_callback_mutex_acquired,    ompt_callback_mutex_t,             27) /* mutex acquired                  */ \
+                                                                                                                         \
+    macro (ompt_callback_nest_lock,         ompt_callback_nest_lock_t,         28) /* nest lock                       */ \
+                                                                                                                         \
+    macro (ompt_callback_flush,             ompt_callback_flush_t,             29) /* after executing flush           */ \
+                                                                                                                         \
+    macro (ompt_callback_cancel,            ompt_callback_cancel_t,            30) /* cancel innermost binding region */ \
+                                                                                                                         \
+    macro (ompt_callback_reduction,         ompt_callback_sync_region_t,       31) /* reduction                       */ \
+                                                                                                                         \
+    macro (ompt_callback_dispatch,          ompt_callback_dispatch_t,          32) /* dispatch of work                */
+
+/*****************************************************************************
+ * implementation specific types
+ *****************************************************************************/
+
+typedef enum kmp_mutex_impl_t {
+#define kmp_mutex_impl_macro(impl, code) impl = code,
+    FOREACH_KMP_MUTEX_IMPL(kmp_mutex_impl_macro)
+#undef kmp_mutex_impl_macro
+} kmp_mutex_impl_t;
+
+/*****************************************************************************
+ * definitions generated from spec
+ *****************************************************************************/
+
+typedef enum ompt_callbacks_t {
+  ompt_callback_thread_begin             = 1,
+  ompt_callback_thread_end               = 2,
+  ompt_callback_parallel_begin           = 3,
+  ompt_callback_parallel_end             = 4,
+  ompt_callback_task_create              = 5,
+  ompt_callback_task_schedule            = 6,
+  ompt_callback_implicit_task            = 7,
+  ompt_callback_target                   = 8,
+  ompt_callback_target_data_op           = 9,
+  ompt_callback_target_submit            = 10,
+  ompt_callback_control_tool             = 11,
+  ompt_callback_device_initialize        = 12,
+  ompt_callback_device_finalize          = 13,
+  ompt_callback_device_load              = 14,
+  ompt_callback_device_unload            = 15,
+  ompt_callback_sync_region_wait         = 16,
+  ompt_callback_mutex_released           = 17,
+  ompt_callback_dependences              = 18,
+  ompt_callback_task_dependence          = 19,
+  ompt_callback_work                     = 20,
+  ompt_callback_master                   = 21,
+  ompt_callback_target_map               = 22,
+  ompt_callback_sync_region              = 23,
+  ompt_callback_lock_init                = 24,
+  ompt_callback_lock_destroy             = 25,
+  ompt_callback_mutex_acquire            = 26,
+  ompt_callback_mutex_acquired           = 27,
+  ompt_callback_nest_lock                = 28,
+  ompt_callback_flush                    = 29,
+  ompt_callback_cancel                   = 30,
+  ompt_callback_reduction                = 31,
+  ompt_callback_dispatch                 = 32
+} ompt_callbacks_t;
+
+typedef enum ompt_record_t {
+  ompt_record_ompt               = 1,
+  ompt_record_native             = 2,
+  ompt_record_invalid            = 3
+} ompt_record_t;
+
+typedef enum ompt_record_native_t {
+  ompt_record_native_info  = 1,
+  ompt_record_native_event = 2
+} ompt_record_native_t;
+
+typedef enum ompt_set_result_t {
+  ompt_set_error            = 0,
+  ompt_set_never            = 1,
+  ompt_set_impossible       = 2,
+  ompt_set_sometimes        = 3,
+  ompt_set_sometimes_paired = 4,
+  ompt_set_always           = 5
+} ompt_set_result_t;
+
+typedef uint64_t ompt_id_t;
+
+typedef uint64_t ompt_device_time_t;
+
+typedef uint64_t ompt_buffer_cursor_t;
+
+typedef enum ompt_thread_t {
+  ompt_thread_initial                 = 1,
+  ompt_thread_worker                  = 2,
+  ompt_thread_other                   = 3,
+  ompt_thread_unknown                 = 4
+} ompt_thread_t;
+
+typedef enum ompt_scope_endpoint_t {
+  ompt_scope_begin                    = 1,
+  ompt_scope_end                      = 2
+} ompt_scope_endpoint_t;
+
+typedef enum ompt_dispatch_t {
+  ompt_dispatch_iteration             = 1,
+  ompt_dispatch_section               = 2
+} ompt_dispatch_t;
+
+typedef enum ompt_sync_region_t {
+  ompt_sync_region_barrier                = 1,
+  ompt_sync_region_barrier_implicit       = 2,
+  ompt_sync_region_barrier_explicit       = 3,
+  ompt_sync_region_barrier_implementation = 4,
+  ompt_sync_region_taskwait               = 5,
+  ompt_sync_region_taskgroup              = 6,
+  ompt_sync_region_reduction              = 7
+} ompt_sync_region_t;
+
+typedef enum ompt_target_data_op_t {
+  ompt_target_data_alloc                = 1,
+  ompt_target_data_transfer_to_device   = 2,
+  ompt_target_data_transfer_from_device = 3,
+  ompt_target_data_delete               = 4,
+  ompt_target_data_associate            = 5,
+  ompt_target_data_disassociate         = 6
+} ompt_target_data_op_t;
+
+typedef enum ompt_work_t {
+  ompt_work_loop               = 1,
+  ompt_work_sections           = 2,
+  ompt_work_single_executor    = 3,
+  ompt_work_single_other       = 4,
+  ompt_work_workshare          = 5,
+  ompt_work_distribute         = 6,
+  ompt_work_taskloop           = 7
+} ompt_work_t;
+
+typedef enum ompt_mutex_t {
+  ompt_mutex_lock                     = 1,
+  ompt_mutex_test_lock                = 2,
+  ompt_mutex_nest_lock                = 3,
+  ompt_mutex_test_nest_lock           = 4,
+  ompt_mutex_critical                 = 5,
+  ompt_mutex_atomic                   = 6,
+  ompt_mutex_ordered                  = 7
+} ompt_mutex_t;
+
+typedef enum ompt_native_mon_flag_t {
+  ompt_native_data_motion_explicit    = 0x01,
+  ompt_native_data_motion_implicit    = 0x02,
+  ompt_native_kernel_invocation       = 0x04,
+  ompt_native_kernel_execution        = 0x08,
+  ompt_native_driver                  = 0x10,
+  ompt_native_runtime                 = 0x20,
+  ompt_native_overhead                = 0x40,
+  ompt_native_idleness                = 0x80
+} ompt_native_mon_flag_t;
+
+typedef enum ompt_task_flag_t {
+  ompt_task_initial                   = 0x00000001,
+  ompt_task_implicit                  = 0x00000002,
+  ompt_task_explicit                  = 0x00000004,
+  ompt_task_target                    = 0x00000008,
+  ompt_task_undeferred                = 0x08000000,
+  ompt_task_untied                    = 0x10000000,
+  ompt_task_final                     = 0x20000000,
+  ompt_task_mergeable                 = 0x40000000,
+  ompt_task_merged                    = 0x80000000
+} ompt_task_flag_t;
+
+typedef enum ompt_task_status_t {
+  ompt_task_complete      = 1,
+  ompt_task_yield         = 2,
+  ompt_task_cancel        = 3,
+  ompt_task_detach        = 4,
+  ompt_task_early_fulfill = 5,
+  ompt_task_late_fulfill  = 6,
+  ompt_task_switch        = 7
+} ompt_task_status_t;
+
+typedef enum ompt_target_t {
+  ompt_target                         = 1,
+  ompt_target_enter_data              = 2,
+  ompt_target_exit_data               = 3,
+  ompt_target_update                  = 4
+} ompt_target_t;
+
+typedef enum ompt_parallel_flag_t {
+  ompt_parallel_invoker_program = 0x00000001,
+  ompt_parallel_invoker_runtime = 0x00000002,
+  ompt_parallel_league          = 0x40000000,
+  ompt_parallel_team            = 0x80000000
+} ompt_parallel_flag_t;
+
+typedef enum ompt_target_map_flag_t {
+  ompt_target_map_flag_to             = 0x01,
+  ompt_target_map_flag_from           = 0x02,
+  ompt_target_map_flag_alloc          = 0x04,
+  ompt_target_map_flag_release        = 0x08,
+  ompt_target_map_flag_delete         = 0x10,
+  ompt_target_map_flag_implicit       = 0x20
+} ompt_target_map_flag_t;
+
+typedef enum ompt_dependence_type_t {
+  ompt_dependence_type_in              = 1,
+  ompt_dependence_type_out             = 2,
+  ompt_dependence_type_inout           = 3,
+  ompt_dependence_type_mutexinoutset   = 4,
+  ompt_dependence_type_source          = 5,
+  ompt_dependence_type_sink            = 6
+} ompt_dependence_type_t;
+
+typedef enum ompt_cancel_flag_t {
+  ompt_cancel_parallel       = 0x01,
+  ompt_cancel_sections       = 0x02,
+  ompt_cancel_loop           = 0x04,
+  ompt_cancel_taskgroup      = 0x08,
+  ompt_cancel_activated      = 0x10,
+  ompt_cancel_detected       = 0x20,
+  ompt_cancel_discarded_task = 0x40
+} ompt_cancel_flag_t;
+
+typedef uint64_t ompt_hwid_t;
+
+typedef uint64_t ompt_wait_id_t;
+
+typedef enum ompt_frame_flag_t {
+  ompt_frame_runtime        = 0x00,
+  ompt_frame_application    = 0x01,
+  ompt_frame_cfa            = 0x10,
+  ompt_frame_framepointer   = 0x20,
+  ompt_frame_stackaddress   = 0x30
+} ompt_frame_flag_t; 
+
+typedef enum ompt_state_t {
+  ompt_state_work_serial                      = 0x000,
+  ompt_state_work_parallel                    = 0x001,
+  ompt_state_work_reduction                   = 0x002,
+
+  ompt_state_wait_barrier                     = 0x010,
+  ompt_state_wait_barrier_implicit_parallel   = 0x011,
+  ompt_state_wait_barrier_implicit_workshare  = 0x012,
+  ompt_state_wait_barrier_implicit            = 0x013,
+  ompt_state_wait_barrier_explicit            = 0x014,
+
+  ompt_state_wait_taskwait                    = 0x020,
+  ompt_state_wait_taskgroup                   = 0x021,
+
+  ompt_state_wait_mutex                       = 0x040,
+  ompt_state_wait_lock                        = 0x041,
+  ompt_state_wait_critical                    = 0x042,
+  ompt_state_wait_atomic                      = 0x043,
+  ompt_state_wait_ordered                     = 0x044,
+
+  ompt_state_wait_target                      = 0x080,
+  ompt_state_wait_target_map                  = 0x081,
+  ompt_state_wait_target_update               = 0x082,
+
+  ompt_state_idle                             = 0x100,
+  ompt_state_overhead                         = 0x101,
+  ompt_state_undefined                        = 0x102
+} ompt_state_t;
+
+typedef uint64_t (*ompt_get_unique_id_t) (void);
+
+typedef uint64_t ompd_size_t;
+
+typedef uint64_t ompd_wait_id_t;
+
+typedef uint64_t ompd_addr_t;
+typedef int64_t  ompd_word_t;
+typedef uint64_t ompd_seg_t;
+
+typedef uint64_t ompd_device_t;
+
+typedef uint64_t ompd_thread_id_t;
+
+typedef enum ompd_scope_t {
+  ompd_scope_global = 1,
+  ompd_scope_address_space = 2,
+  ompd_scope_thread = 3,
+  ompd_scope_parallel = 4,
+  ompd_scope_implicit_task = 5,
+  ompd_scope_task = 6
+} ompd_scope_t;
+
+typedef uint64_t ompd_icv_id_t;
+
+typedef enum ompd_rc_t {
+  ompd_rc_ok = 0,
+  ompd_rc_unavailable = 1,
+  ompd_rc_stale_handle = 2,
+  ompd_rc_bad_input = 3,
+  ompd_rc_error = 4,
+  ompd_rc_unsupported = 5,
+  ompd_rc_needs_state_tracking = 6,
+  ompd_rc_incompatible = 7,
+  ompd_rc_device_read_error = 8,
+  ompd_rc_device_write_error = 9,
+  ompd_rc_nomem = 10,
+} ompd_rc_t;
+
+typedef void (*ompt_interface_fn_t) (void);
+
+typedef ompt_interface_fn_t (*ompt_function_lookup_t) (
+  const char *interface_function_name
+);
+
+typedef union ompt_data_t {
+  uint64_t value;
+  void *ptr;
+} ompt_data_t;
+
+typedef struct ompt_frame_t {
+  ompt_data_t exit_frame;
+  ompt_data_t enter_frame;
+  int exit_frame_flags;
+  int enter_frame_flags;
+} ompt_frame_t;
+
+typedef void (*ompt_callback_t) (void);
+
+typedef void ompt_device_t;
+
+typedef void ompt_buffer_t;
+
+typedef void (*ompt_callback_buffer_request_t) (
+  int device_num,
+  ompt_buffer_t **buffer,
+  size_t *bytes
+);
+
+typedef void (*ompt_callback_buffer_complete_t) (
+  int device_num,
+  ompt_buffer_t *buffer,
+  size_t bytes,
+  ompt_buffer_cursor_t begin,
+  int buffer_owned
+);
+
+typedef void (*ompt_finalize_t) (
+  ompt_data_t *tool_data
+);
+
+typedef int (*ompt_initialize_t) (
+  ompt_function_lookup_t lookup,
+  int initial_device_num,
+  ompt_data_t *tool_data
+);
+
+typedef struct ompt_start_tool_result_t {
+  ompt_initialize_t initialize;
+  ompt_finalize_t finalize;
+  ompt_data_t tool_data;
+} ompt_start_tool_result_t;
+
+typedef struct ompt_record_abstract_t {
+  ompt_record_native_t rclass;
+  const char *type;
+  ompt_device_time_t start_time;
+  ompt_device_time_t end_time;
+  ompt_hwid_t hwid;
+} ompt_record_abstract_t;
+
+typedef struct ompt_dependence_t {
+  ompt_data_t variable;
+  ompt_dependence_type_t dependence_type;
+} ompt_dependence_t;
+
+typedef int (*ompt_enumerate_states_t) (
+  int current_state,
+  int *next_state,
+  const char **next_state_name
+);
+
+typedef int (*ompt_enumerate_mutex_impls_t) (
+  int current_impl,
+  int *next_impl,
+  const char **next_impl_name
+);
+
+typedef ompt_set_result_t (*ompt_set_callback_t) (
+  ompt_callbacks_t event,
+  ompt_callback_t callback
+);
+
+typedef int (*ompt_get_callback_t) (
+  ompt_callbacks_t event,
+  ompt_callback_t *callback
+);
+
+typedef ompt_data_t *(*ompt_get_thread_data_t) (void);
+
+typedef int (*ompt_get_num_procs_t) (void);
+
+typedef int (*ompt_get_num_places_t) (void);
+
+typedef int (*ompt_get_place_proc_ids_t) (
+  int place_num,
+  int ids_size,
+  int *ids
+);
+
+typedef int (*ompt_get_place_num_t) (void);
+
+typedef int (*ompt_get_partition_place_nums_t) (
+  int place_nums_size,
+  int *place_nums
+);
+
+typedef int (*ompt_get_proc_id_t) (void);
+
+typedef int (*ompt_get_state_t) (
+  ompt_wait_id_t *wait_id
+);
+
+typedef int (*ompt_get_parallel_info_t) (
+  int ancestor_level,
+  ompt_data_t **parallel_data,
+  int *team_size
+);
+
+typedef int (*ompt_get_task_info_t) (
+  int ancestor_level,
+  int *flags,
+  ompt_data_t **task_data,
+  ompt_frame_t **task_frame,
+  ompt_data_t **parallel_data,
+  int *thread_num
+);
+
+typedef int (*ompt_get_task_memory_t)(
+  void **addr,
+  size_t *size,
+  int block
+);
+
+typedef int (*ompt_get_target_info_t) (
+  uint64_t *device_num,
+  ompt_id_t *target_id,
+  ompt_id_t *host_op_id
+);
+
+typedef int (*ompt_get_num_devices_t) (void);
+
+typedef void (*ompt_finalize_tool_t) (void);
+
+typedef int (*ompt_get_device_num_procs_t) (
+  ompt_device_t *device
+);
+
+typedef ompt_device_time_t (*ompt_get_device_time_t) (
+  ompt_device_t *device
+);
+
+typedef double (*ompt_translate_time_t) (
+  ompt_device_t *device,
+  ompt_device_time_t time
+);
+
+typedef ompt_set_result_t (*ompt_set_trace_ompt_t) (
+  ompt_device_t *device,
+  unsigned int enable,
+  unsigned int etype
+);
+
+typedef ompt_set_result_t (*ompt_set_trace_native_t) (
+  ompt_device_t *device,
+  int enable,
+  int flags
+);
+
+typedef int (*ompt_start_trace_t) (
+  ompt_device_t *device,
+  ompt_callback_buffer_request_t request,
+  ompt_callback_buffer_complete_t complete
+);
+
+typedef int (*ompt_pause_trace_t) (
+  ompt_device_t *device,
+  int begin_pause
+);
+
+typedef int (*ompt_flush_trace_t) (
+  ompt_device_t *device
+);
+
+typedef int (*ompt_stop_trace_t) (
+  ompt_device_t *device
+);
+
+typedef int (*ompt_advance_buffer_cursor_t) (
+  ompt_device_t *device,
+  ompt_buffer_t *buffer,
+  size_t size,
+  ompt_buffer_cursor_t current,
+  ompt_buffer_cursor_t *next
+);
+
+typedef ompt_record_t (*ompt_get_record_type_t) (
+  ompt_buffer_t *buffer,
+  ompt_buffer_cursor_t current
+);
+
+typedef void *(*ompt_get_record_native_t) (
+  ompt_buffer_t *buffer,
+  ompt_buffer_cursor_t current,
+  ompt_id_t *host_op_id
+);
+
+typedef ompt_record_abstract_t *
+(*ompt_get_record_abstract_t) (
+  void *native_record
+);
+
+typedef void (*ompt_callback_thread_begin_t) (
+  ompt_thread_t thread_type,
+  ompt_data_t *thread_data
+);
+
+typedef struct ompt_record_thread_begin_t {
+  ompt_thread_t thread_type;
+} ompt_record_thread_begin_t;
+
+typedef void (*ompt_callback_thread_end_t) (
+  ompt_data_t *thread_data
+);
+
+typedef void (*ompt_callback_parallel_begin_t) (
+  ompt_data_t *encountering_task_data,
+  const ompt_frame_t *encountering_task_frame,
+  ompt_data_t *parallel_data,
+  unsigned int requested_parallelism,
+  int flags,
+  const void *codeptr_ra
+);
+
+typedef struct ompt_record_parallel_begin_t {
+  ompt_id_t encountering_task_id;
+  ompt_id_t parallel_id;
+  unsigned int requested_parallelism;
+  int flags;
+  const void *codeptr_ra;
+} ompt_record_parallel_begin_t;
+
+typedef void (*ompt_callback_parallel_end_t) (
+  ompt_data_t *parallel_data,
+  ompt_data_t *encountering_task_data,
+  int flags,
+  const void *codeptr_ra
+);
+
+typedef struct ompt_record_parallel_end_t {
+  ompt_id_t parallel_id;
+  ompt_id_t encountering_task_id;
+  int flags;
+  const void *codeptr_ra;
+} ompt_record_parallel_end_t;
+
+typedef void (*ompt_callback_work_t) (
+  ompt_work_t wstype,
+  ompt_scope_endpoint_t endpoint,
+  ompt_data_t *parallel_data,
+  ompt_data_t *task_data,
+  uint64_t count,
+  const void *codeptr_ra
+);
+
+typedef struct ompt_record_work_t {
+  ompt_work_t wstype;
+  ompt_scope_endpoint_t endpoint;
+  ompt_id_t parallel_id;
+  ompt_id_t task_id;
+  uint64_t count;
+  const void *codeptr_ra;
+} ompt_record_work_t;
+
+typedef void (*ompt_callback_dispatch_t) (
+  ompt_data_t *parallel_data,
+  ompt_data_t *task_data,
+  ompt_dispatch_t kind,
+  ompt_data_t instance 
+);
+
+typedef struct ompt_record_dispatch_t {
+  ompt_id_t parallel_id;
+  ompt_id_t task_id;
+  ompt_dispatch_t kind;
+  ompt_data_t instance; 
+} ompt_record_dispatch_t;
+
+typedef void (*ompt_callback_task_create_t) (
+  ompt_data_t *encountering_task_data,
+  const ompt_frame_t *encountering_task_frame,
+  ompt_data_t *new_task_data,
+  int flags,
+  int has_dependences,
+  const void *codeptr_ra
+);
+
+typedef struct ompt_record_task_create_t {
+  ompt_id_t encountering_task_id;
+  ompt_id_t new_task_id;
+  int flags;
+  int has_dependences;
+  const void *codeptr_ra;
+} ompt_record_task_create_t;
+
+typedef void (*ompt_callback_dependences_t) (
+  ompt_data_t *task_data,
+  const ompt_dependence_t *deps,
+  int ndeps
+);
+
+typedef struct ompt_record_dependences_t {
+  ompt_id_t task_id;
+  ompt_dependence_t dep;
+  int ndeps;
+} ompt_record_dependences_t;
+
+typedef void (*ompt_callback_task_dependence_t) (
+  ompt_data_t *src_task_data,
+  ompt_data_t *sink_task_data
+);
+
+typedef struct ompt_record_task_dependence_t {
+  ompt_id_t src_task_id;
+  ompt_id_t sink_task_id;
+} ompt_record_task_dependence_t;
+
+typedef void (*ompt_callback_task_schedule_t) (
+  ompt_data_t *prior_task_data,
+  ompt_task_status_t prior_task_status,
+  ompt_data_t *next_task_data
+);
+
+typedef struct ompt_record_task_schedule_t {
+  ompt_id_t prior_task_id;
+  ompt_task_status_t prior_task_status;
+  ompt_id_t next_task_id;
+} ompt_record_task_schedule_t;
+
+typedef void (*ompt_callback_implicit_task_t) (
+  ompt_scope_endpoint_t endpoint,
+  ompt_data_t *parallel_data,
+  ompt_data_t *task_data,
+  unsigned int actual_parallelism,
+  unsigned int index,
+  int flags
+);
+
+typedef struct ompt_record_implicit_task_t {
+  ompt_scope_endpoint_t endpoint;
+  ompt_id_t parallel_id;
+  ompt_id_t task_id;
+  unsigned int actual_parallelism;
+  unsigned int index;
+  int flags;
+} ompt_record_implicit_task_t;
+
+typedef void (*ompt_callback_master_t) (
+  ompt_scope_endpoint_t endpoint,
+  ompt_data_t *parallel_data,
+  ompt_data_t *task_data,
+  const void *codeptr_ra
+);
+
+typedef struct ompt_record_master_t {
+  ompt_scope_endpoint_t endpoint;
+  ompt_id_t parallel_id;
+  ompt_id_t task_id;
+  const void *codeptr_ra;
+} ompt_record_master_t;
+
+typedef void (*ompt_callback_sync_region_t) (
+  ompt_sync_region_t kind,
+  ompt_scope_endpoint_t endpoint,
+  ompt_data_t *parallel_data,
+  ompt_data_t *task_data,
+  const void *codeptr_ra
+);
+
+typedef struct ompt_record_sync_region_t {
+  ompt_sync_region_t kind;
+  ompt_scope_endpoint_t endpoint;
+  ompt_id_t parallel_id;
+  ompt_id_t task_id;
+  const void *codeptr_ra;
+} ompt_record_sync_region_t;
+
+typedef void (*ompt_callback_mutex_acquire_t) (
+  ompt_mutex_t kind,
+  unsigned int hint,
+  unsigned int impl,
+  ompt_wait_id_t wait_id,
+  const void *codeptr_ra
+);
+
+typedef struct ompt_record_mutex_acquire_t {
+  ompt_mutex_t kind;
+  unsigned int hint;
+  unsigned int impl;
+  ompt_wait_id_t wait_id;
+  const void *codeptr_ra;
+} ompt_record_mutex_acquire_t;
+
+typedef void (*ompt_callback_mutex_t) (
+  ompt_mutex_t kind,
+  ompt_wait_id_t wait_id,
+  const void *codeptr_ra
+);
+
+typedef struct ompt_record_mutex_t {
+  ompt_mutex_t kind;
+  ompt_wait_id_t wait_id;
+  const void *codeptr_ra;
+} ompt_record_mutex_t;
+
+typedef void (*ompt_callback_nest_lock_t) (
+  ompt_scope_endpoint_t endpoint,
+  ompt_wait_id_t wait_id,
+  const void *codeptr_ra
+);
+
+typedef struct ompt_record_nest_lock_t {
+  ompt_scope_endpoint_t endpoint;
+  ompt_wait_id_t wait_id;
+  const void *codeptr_ra;
+} ompt_record_nest_lock_t;
+
+typedef void (*ompt_callback_flush_t) (
+  ompt_data_t *thread_data,
+  const void *codeptr_ra
+);
+
+typedef struct ompt_record_flush_t {
+  const void *codeptr_ra;
+} ompt_record_flush_t;
+
+typedef void (*ompt_callback_cancel_t) (
+  ompt_data_t *task_data,
+  int flags,
+  const void *codeptr_ra
+);
+
+typedef struct ompt_record_cancel_t {
+  ompt_id_t task_id;
+  int flags;
+  const void *codeptr_ra;
+} ompt_record_cancel_t;
+
+typedef void (*ompt_callback_device_initialize_t) (
+  int device_num,
+  const char *type,
+  ompt_device_t *device,
+  ompt_function_lookup_t lookup,
+  const char *documentation
+);
+
+typedef void (*ompt_callback_device_finalize_t) (
+  int device_num
+);
+
+typedef void (*ompt_callback_device_load_t) (
+  int device_num,
+  const char *filename,
+  int64_t offset_in_file,
+  void *vma_in_file,
+  size_t bytes,
+  void *host_addr,
+  void *device_addr,
+  uint64_t module_id
+);
+
+typedef void (*ompt_callback_device_unload_t) (
+  int device_num,
+  uint64_t module_id
+);
+
+typedef void (*ompt_callback_target_data_op_t) (
+  ompt_id_t target_id,
+  ompt_id_t host_op_id,
+  ompt_target_data_op_t optype,
+  void *src_addr,
+  int src_device_num,
+  void *dest_addr,
+  int dest_device_num,
+  size_t bytes,
+  const void *codeptr_ra
+);
+
+typedef struct ompt_record_target_data_op_t {
+  ompt_id_t host_op_id;
+  ompt_target_data_op_t optype;
+  void *src_addr;
+  int src_device_num;
+  void *dest_addr;
+  int dest_device_num;
+  size_t bytes;
+  ompt_device_time_t end_time;
+  const void *codeptr_ra;
+} ompt_record_target_data_op_t;
+
+typedef void (*ompt_callback_target_t) (
+  ompt_target_t kind,
+  ompt_scope_endpoint_t endpoint,
+  int device_num,
+  ompt_data_t *task_data,
+  ompt_id_t target_id,
+  const void *codeptr_ra
+);
+
+typedef struct ompt_record_target_t {
+  ompt_target_t kind;
+  ompt_scope_endpoint_t endpoint;
+  int device_num;
+  ompt_id_t task_id;
+  ompt_id_t target_id;
+  const void *codeptr_ra;
+} ompt_record_target_t;
+
+typedef void (*ompt_callback_target_map_t) (
+  ompt_id_t target_id,
+  unsigned int nitems,
+  void **host_addr,
+  void **device_addr,
+  size_t *bytes,
+  unsigned int *mapping_flags,
+  const void *codeptr_ra
+);
+
+typedef struct ompt_record_target_map_t {
+  ompt_id_t target_id;
+  unsigned int nitems;
+  void **host_addr;
+  void **device_addr;
+  size_t *bytes;
+  unsigned int *mapping_flags;
+  const void *codeptr_ra;
+} ompt_record_target_map_t;
+
+typedef void (*ompt_callback_target_submit_t) (
+  ompt_id_t target_id,
+  ompt_id_t host_op_id,
+  unsigned int requested_num_teams
+);
+
+typedef struct ompt_record_target_kernel_t {
+  ompt_id_t host_op_id;
+  unsigned int requested_num_teams;
+  unsigned int granted_num_teams;
+  ompt_device_time_t end_time;
+} ompt_record_target_kernel_t;
+
+typedef int (*ompt_callback_control_tool_t) (
+  uint64_t command,
+  uint64_t modifier,
+  void *arg,
+  const void *codeptr_ra
+);
+
+typedef struct ompt_record_control_tool_t {
+  uint64_t command;
+  uint64_t modifier;
+  const void *codeptr_ra;
+} ompt_record_control_tool_t;
+
+typedef struct ompd_address_t {
+  ompd_seg_t segment;
+  ompd_addr_t address;
+} ompd_address_t;
+
+typedef struct ompd_frame_info_t {
+  ompd_address_t frame_address;
+  ompd_word_t frame_flag;
+} ompd_frame_info_t;
+
+typedef struct _ompd_aspace_handle ompd_address_space_handle_t;
+typedef struct _ompd_thread_handle ompd_thread_handle_t;
+typedef struct _ompd_parallel_handle ompd_parallel_handle_t;
+typedef struct _ompd_task_handle ompd_task_handle_t;
+
+typedef struct _ompd_aspace_cont ompd_address_space_context_t;
+typedef struct _ompd_thread_cont ompd_thread_context_t;
+
+typedef struct ompd_device_type_sizes_t {
+  uint8_t sizeof_char;
+  uint8_t sizeof_short;
+  uint8_t sizeof_int;
+  uint8_t sizeof_long;
+  uint8_t sizeof_long_long;
+  uint8_t sizeof_pointer;
+} ompd_device_type_sizes_t;
+
+typedef struct ompt_record_ompt_t {
+  ompt_callbacks_t type;
+  ompt_device_time_t time;
+  ompt_id_t thread_id;
+  ompt_id_t target_id;
+  union {
+    ompt_record_thread_begin_t thread_begin;
+    ompt_record_parallel_begin_t parallel_begin;
+    ompt_record_parallel_end_t parallel_end;
+    ompt_record_work_t work;
+    ompt_record_dispatch_t dispatch;
+    ompt_record_task_create_t task_create;
+    ompt_record_dependences_t dependences;
+    ompt_record_task_dependence_t task_dependence;
+    ompt_record_task_schedule_t task_schedule;
+    ompt_record_implicit_task_t implicit_task;
+    ompt_record_master_t master;
+    ompt_record_sync_region_t sync_region;
+    ompt_record_mutex_acquire_t mutex_acquire;
+    ompt_record_mutex_t mutex;
+    ompt_record_nest_lock_t nest_lock;
+    ompt_record_flush_t flush;
+    ompt_record_cancel_t cancel;
+    ompt_record_target_t target;
+    ompt_record_target_data_op_t target_data_op;
+    ompt_record_target_map_t target_map;
+    ompt_record_target_kernel_t target_kernel;
+    ompt_record_control_tool_t control_tool;
+  } record;
+} ompt_record_ompt_t;
+
+typedef ompt_record_ompt_t *(*ompt_get_record_ompt_t) (
+  ompt_buffer_t *buffer,
+  ompt_buffer_cursor_t current
+);
+
+#define ompt_id_none 0
+#define ompt_data_none {0}
+#define ompt_time_none 0
+#define ompt_hwid_none 0
+#define ompt_addr_none ~0
+#define ompt_mutex_impl_none 0
+#define ompt_wait_id_none 0
+
+#define ompd_segment_none 0
+
+#endif /* __OMPT__ */
diff --git a/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/async.h b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/async.h
new file mode 100644
index 0000000000000000000000000000000000000000..1b7dcb2433f2cb7d1ef61290995ac871a901b1e8
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/async.h
@@ -0,0 +1,452 @@
+/* Copyright 1993-2016 NVIDIA Corporation.  All rights reserved.
+ *
+ * NOTICE TO LICENSEE:
+ *
+ * The source code and/or documentation ("Licensed Deliverables") are
+ * subject to NVIDIA intellectual property rights under U.S. and
+ * international Copyright laws.
+ *
+ * The Licensed Deliverables contained herein are PROPRIETARY and
+ * CONFIDENTIAL to NVIDIA and are being provided under the terms and
+ * conditions of a form of NVIDIA software license agreement by and
+ * between NVIDIA and Licensee ("License Agreement") or electronically
+ * accepted by Licensee.  Notwithstanding any terms or conditions to
+ * the contrary in the License Agreement, reproduction or disclosure
+ * of the Licensed Deliverables to any third party without the express
+ * written consent of NVIDIA is prohibited.
+ *
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+ * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
+ * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE.  THEY ARE
+ * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
+ * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
+ * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
+ * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+ * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
+ * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * OF THESE LICENSED DELIVERABLES.
+ *
+ * U.S. Government End Users.  These Licensed Deliverables are a
+ * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
+ * 1995), consisting of "commercial computer software" and "commercial
+ * computer software documentation" as such terms are used in 48
+ * C.F.R. 12.212 (SEPT 1995) and are provided to the U.S. Government
+ * only as a commercial end item.  Consistent with 48 C.F.R.12.212 and
+ * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
+ * U.S. Government End Users acquire the Licensed Deliverables with
+ * only those rights set forth herein.
+ *
+ * Any use of the Licensed Deliverables in individual and commercial
+ * software must include, in the user documentation and internal
+ * comments to the code, the above Disclaimer and U.S. Government End
+ * Users Notice.
+ */
+
+#ifndef _CG_ASYNC_H
+#define _CG_ASYNC_H
+
+#include "helpers.h"
+#include "info.h"
+
+#include 
+
+_CG_BEGIN_NAMESPACE
+
+namespace details {
+// Groups supported by memcpy_async
+template 
+struct _async_copy_group_supported : public _CG_STL_NAMESPACE::false_type {};
+
+template 
+struct _async_copy_group_supported>
+    : public _CG_STL_NAMESPACE::true_type {};
+template <>
+struct _async_copy_group_supported : public _CG_STL_NAMESPACE::true_type {};
+template <>
+struct _async_copy_group_supported : public _CG_STL_NAMESPACE::true_type {};
+
+template 
+using async_copy_group_supported = _async_copy_group_supported>;
+
+// Groups that require optimization
+template 
+struct _async_copy_optimize_tile : public _CG_STL_NAMESPACE::false_type {};
+
+template 
+struct _async_copy_optimize_tile>
+    : public _CG_STL_NAMESPACE::false_type {};
+
+template 
+struct _async_copy_optimize_tile>
+    : public _CG_STL_NAMESPACE::true_type {};
+
+template 
+using async_copy_optimize_tile = _async_copy_optimize_tile>;
+
+// SFINAE helpers for tile optimizations
+template 
+using enable_tile_optimization =
+    typename _CG_STL_NAMESPACE::enable_if::value, void *>::type;
+
+template 
+using disable_tile_optimization =
+    typename _CG_STL_NAMESPACE::enable_if::value, void *>::type;
+
+// Segment for punning to aligned types
+template 
+struct _Segment {
+    int _seg[N];
+};
+
+// Trivial layout guaranteed-aligned copy-async compatible segments
+template 
+struct Segment;
+template <>
+struct __align__(4) Segment<1> : public _Segment<1>{};
+template <>
+struct __align__(8) Segment<2> : public _Segment<2>{};
+template <>
+struct __align__(16) Segment<4> : public _Segment<4>{};
+
+// Interleaved element by element copies from source to dest
+template 
+_CG_STATIC_QUALIFIER void inline_copy(TyGroup &group, TyElem *__restrict__ dst, const TyElem *__restrict__ src,
+                                      size_t count) {
+    const unsigned int rank = group.thread_rank();
+    const unsigned int stride = group.size();
+
+    for (size_t idx = rank; idx < count; idx += stride) {
+        dst[idx] = src[idx];
+    }
+}
+
+template  = nullptr>
+_CG_STATIC_QUALIFIER void accelerated_async_copy(TyGroup &group, TyElem *__restrict__ dst,
+                                                 const TyElem *__restrict__ src, size_t count) {
+    static_assert(async_copy_group_supported::value,
+                  "Async copy is only supported for groups that represent private shared memory");
+
+    if (count == 0) {
+        return;
+    }
+
+    const bool dstIsNotShared = !__isShared(dst);
+    const bool srcIsNotGlobal = !__isGlobal(src);
+
+    if (dstIsNotShared || srcIsNotGlobal) {
+        inline_copy(group, dst, src, count);
+        return;
+    }
+
+    const unsigned int stride = group.size();
+    const unsigned int rank = group.thread_rank();
+    // Efficient copies require warps to operate on the same amount of work at each step.
+    // remainders are handled in a separate stage to prevent branching
+    const unsigned int subWarpMask = (stride - 1);
+    const unsigned int subwarpCopies = (subWarpMask & (unsigned int)count);
+    const unsigned int maxSubwarpRank = min(rank, subwarpCopies - 1);
+
+    const size_t warpCopies = (count & (~subWarpMask));
+
+    for (size_t idx = 0; idx < warpCopies; idx += stride) {
+        size_t _srcIdx = rank + idx;
+        size_t _dstIdx = rank + idx;
+        __pipeline_memcpy_async(dst + _dstIdx, src + _srcIdx, sizeof(TyElem));
+    }
+
+    if (subwarpCopies) {
+        size_t _srcIdx = warpCopies + maxSubwarpRank;
+        size_t _dstIdx = warpCopies + maxSubwarpRank;
+        __pipeline_memcpy_async(dst + _dstIdx, src + _srcIdx, sizeof(TyElem));
+    }
+}
+
+template  = nullptr>
+_CG_STATIC_QUALIFIER void accelerated_async_copy(TyGroup &group, TyElem *__restrict__ dst,
+                                                 const TyElem *__restrict__ src, size_t count) {
+    static_assert(async_copy_group_supported::value,
+                  "Async copy is only supported for groups that represent private shared memory");
+
+    const bool dstIsNotShared = !__isShared(dst);
+    const bool srcIsNotGlobal = !__isGlobal(src);
+
+    if (dstIsNotShared || srcIsNotGlobal) {
+        inline_copy(group, dst, src, count);
+        return;
+    }
+
+    unsigned int stride = group.size();
+    unsigned int rank = group.thread_rank();
+
+    for (size_t idx = rank; idx < count; idx += stride) {
+        size_t _srcIdx = idx;
+        size_t _dstIdx = idx;
+        __pipeline_memcpy_async(dst + _dstIdx, src + _srcIdx, sizeof(TyElem));
+    }
+}
+
+// Determine best possible alignment given an input and initial conditions
+// Attempts to generate as little code as possible, most likely should only be used with 1 and 2 byte alignments
+template 
+_CG_STATIC_QUALIFIER uint32_t find_best_alignment(void *__restrict__ dst, const void *__restrict__ src) {
+    // Narrowing conversion intentional
+    uint32_t base1 = (uint32_t) reinterpret_cast(src);
+    uint32_t base2 = (uint32_t) reinterpret_cast(dst);
+
+    uint32_t diff = ((base1) ^ (base2)) & (MaxAlignment - 1);
+
+    // range [MaxAlignment, alignof(elem)], step: x >> 1
+    // over range of possible alignments, choose best available out of range
+    uint32_t out = MaxAlignment;
+#pragma unroll
+    for (uint32_t alignment = (MaxAlignment >> 1); alignment >= MinAlignment; alignment >>= 1) {
+        if (alignment & diff)
+            out = alignment;
+    }
+
+    return out;
+}
+
+// Determine best possible alignment given an input and initial conditions
+// Attempts to generate as little code as possible, most likely should only be used with 1 and 2 byte alignments
+template 
+_CG_STATIC_QUALIFIER void copy_like(const TyGroup &group, void *__restrict__ _dst, const void *__restrict__ _src,
+                                    size_t count) {
+    const char *src = reinterpret_cast(_src);
+    char *dst = reinterpret_cast(_dst);
+
+    constexpr uint32_t targetAlignment = (uint32_t)alignof(TyType);
+
+    uint32_t base = (uint32_t) reinterpret_cast(src);
+    uint32_t alignOffset = ((~base) + 1) & (targetAlignment - 1);
+
+    inline_copy(group, dst, src, alignOffset);
+    count -= alignOffset;
+    src += alignOffset;
+    dst += alignOffset;
+
+    // Copy using the best available alignment, async_copy expects n-datums, not bytes
+    size_t asyncCount = count / sizeof(TyType);
+    accelerated_async_copy(group, reinterpret_cast(dst), reinterpret_cast(src), asyncCount);
+    asyncCount *= sizeof(TyType);
+
+    count -= asyncCount;
+    src += asyncCount;
+    dst += asyncCount;
+    inline_copy(group, dst, src, count);
+}
+
+// We must determine alignment and manually align src/dst ourselves
+template 
+struct _memcpy_async_align_dispatch {
+    template 
+    _CG_STATIC_QUALIFIER void copy(TyGroup &group, void *__restrict__ dst, const void *__restrict__ src, size_t count) {
+        uint32_t alignment = find_best_alignment(dst, src);
+
+        // Avoid copying the extra bytes if desired copy count is smaller
+        alignment = count < alignment ? AlignHint : alignment;
+
+        switch (alignment) {
+        default:
+        case 1:
+            inline_copy(group, reinterpret_cast(dst), reinterpret_cast(src), count);
+            break;
+        case 2:
+            inline_copy(group, reinterpret_cast(dst), reinterpret_cast(src), count >> 1);
+            break;
+        case 4:
+            copy_like>(group, dst, src, count);
+            break;
+        case 8:
+            copy_like>(group, dst, src, count);
+            break;
+        case 16:
+            copy_like>(group, dst, src, count);
+            break;
+        }
+    }
+};
+
+// Specialization for 4 byte alignments
+template <>
+struct _memcpy_async_align_dispatch<4> {
+    template 
+    _CG_STATIC_QUALIFIER void copy(TyGroup &group, void *__restrict__ _dst, const void *__restrict__ _src,
+                                   size_t count) {
+        const Segment<1> *src = reinterpret_cast *>(_src);
+        Segment<1> *dst = reinterpret_cast *>(_dst);
+
+        // Dispatch straight to aligned LDGSTS calls
+        accelerated_async_copy(group, dst, src, count / sizeof(*dst));
+    }
+};
+
+// Specialization for 8 byte alignments
+template <>
+struct _memcpy_async_align_dispatch<8> {
+    template 
+    _CG_STATIC_QUALIFIER void copy(TyGroup &group, void *__restrict__ _dst, const void *__restrict__ _src,
+                                   size_t count) {
+        const Segment<2> *src = reinterpret_cast *>(_src);
+        Segment<2> *dst = reinterpret_cast *>(_dst);
+
+        // Dispatch straight to aligned LDGSTS calls
+        accelerated_async_copy(group, dst, src, count / sizeof(*dst));
+    }
+};
+
+// Alignments over 16 are truncated to 16 and bypass alignment
+// This is the highest performing memcpy available
+template <>
+struct _memcpy_async_align_dispatch<16> {
+    template 
+    _CG_STATIC_QUALIFIER void copy(TyGroup &group, void *__restrict__ _dst, const void *__restrict__ _src,
+                                   size_t count) {
+        const Segment<4> *src = reinterpret_cast *>(_src);
+        Segment<4> *dst = reinterpret_cast *>(_dst);
+
+        // Dispatch straight to aligned LDGSTS calls
+        accelerated_async_copy(group, dst, src, count / sizeof(*dst));
+    }
+};
+
+// byte-wide API
+template 
+_CG_STATIC_QUALIFIER void _memcpy_async_dispatch_to_aligned_copy(const TyGroup &group, void *__restrict__ _dst,
+                                                                 const void *__restrict__ _src, size_t count) {
+    static_assert(!(Alignment & (Alignment - 1)), "Known static alignment dispatch must be a power of 2");
+    details::_memcpy_async_align_dispatch::copy(group, _dst, _src, count);
+}
+
+// Internal dispatch APIs
+// These deduce the alignments and sizes necessary to invoke the underlying copy engine
+template 
+using is_void = _CG_STL_NAMESPACE::is_same;
+
+template 
+using enable_if_not_void = typename _CG_STL_NAMESPACE::enable_if::value, void *>::type;
+
+template 
+using enable_if_void = typename _CG_STL_NAMESPACE::enable_if::value, void *>::type;
+
+template 
+using enable_if_integral =
+    typename _CG_STL_NAMESPACE::enable_if<_CG_STL_NAMESPACE::is_integral::value, void *>::type;
+
+// byte-wide API using aligned_sized_t
+template  typename Alignment, size_t Hint>
+_CG_STATIC_QUALIFIER void _memcpy_async_bytes(const TyGroup &group, void *__restrict__ _dst,
+                                              const void *__restrict__ _src, const Alignment &count) {
+    constexpr size_t _align = (Hint > 16) ? 16 : Hint;
+
+    details::_memcpy_async_dispatch_to_aligned_copy<_align>(group, _dst, _src, (size_t)count);
+}
+
+// byte-wide API using type for aligment
+template  = nullptr, enable_if_integral = nullptr>
+_CG_STATIC_QUALIFIER void _memcpy_async_bytes(const TyGroup &group, TyElem *__restrict__ _dst,
+                                              const TyElem *__restrict__ _src, const TySize& count) {
+    constexpr size_t _align = (Hint > 16) ? 16 : Hint;
+
+    details::_memcpy_async_dispatch_to_aligned_copy<_align>(group, _dst, _src, count);
+}
+
+// byte-wide API with full alignment deduction required
+template  = nullptr,
+          enable_if_integral = nullptr>
+_CG_STATIC_QUALIFIER void _memcpy_async_bytes(const TyGroup &group, TyElem *__restrict__ _dst,
+                                              const TyElem *__restrict__ _src, const TySize& count) {
+    details::_memcpy_async_dispatch_to_aligned_copy<1>(group, _dst, _src, count);
+}
+
+// 1d-datum API
+template 
+_CG_STATIC_QUALIFIER void _memcpy_async_datum(const TyGroup &group, TyElem *__restrict__ dst, const size_t dstCount,
+                                              const TyElem *__restrict__ src, const size_t srcCount) {
+    constexpr unsigned int _align = Hint;
+    const size_t totalCount = min(dstCount, srcCount) * sizeof(TyElem);
+
+    details::_memcpy_async_dispatch_to_aligned_copy<_align>(group, dst, src, totalCount);
+}
+
+// 1d-datum API using aligned_size_t
+template  typename Alignment, size_t Hint>
+_CG_STATIC_QUALIFIER void _memcpy_async_datum(const TyGroup &group, TyElem *__restrict__ dst, const Alignment &dstCount,
+                                              const TyElem *__restrict__ src, const Alignment &srcCount) {
+    constexpr unsigned int _align = Hint;
+    const size_t totalCount = min((size_t)dstCount, (size_t)srcCount) * sizeof(TyElem);
+
+    details::_memcpy_async_dispatch_to_aligned_copy<_align>(group, dst, src, totalCount);
+}
+
+} // namespace details
+
+/*
+ * Group submit batch of async-copy to cover contiguous 1D array
+ * and commit that batch to eventually wait for completion.
+ */
+template 
+_CG_STATIC_QUALIFIER void memcpy_async(const TyGroup &group, TyElem *__restrict__ _dst, const TyElem *__restrict__ _src,
+                                       const TySizeT &count) {
+    details::_memcpy_async_bytes(group, _dst, _src, count);
+    __pipeline_commit();
+}
+
+/*
+ * Group submit batch of async-copy to cover contiguous 1D array
+ * and commit that batch to eventually wait for completion.
+ * Object counts are in datum sized chunks, not bytes.
+ */
+template 
+_CG_STATIC_QUALIFIER void memcpy_async(const TyGroup &group, TyElem *__restrict__ dst, const DstLayout &dstLayout,
+                                       const TyElem *__restrict__ src, const SrcLayout &srcLayout) {
+    details::_memcpy_async_datum(group, dst, dstLayout, src, srcLayout);
+    __pipeline_commit();
+}
+
+/* Group wait for prior Nth stage of memcpy_async to complete. */
+template 
+_CG_STATIC_QUALIFIER void wait_prior(const TyGroup &group) {
+    __pipeline_wait_prior(Stage);
+    group.sync();
+}
+
+/* Group wait all previously submitted memcpy_async to complete. */
+template 
+_CG_STATIC_QUALIFIER void wait(const TyGroup &group) {
+    __pipeline_wait_prior(0);
+    group.sync();
+}
+
+/***************** CG APIs including pipeline are deprecated *****************/
+
+/* Group submit batch of async-copy to cover of contiguous 1D array
+   to a pipeline and commit the batch*/
+template 
+_CG_DEPRECATED _CG_STATIC_QUALIFIER void memcpy_async(TyGroup &group, TyElem *dst, size_t dstCount, const TyElem *src, size_t srcCount,
+                                       nvcuda::experimental::pipeline &pipe) {
+    details::_memcpy_async_datum(group, dst, dstCount, src, srcCount);
+    pipe.commit();
+}
+
+/* Group wait for prior Nth stage of memcpy_async to complete. */
+template 
+_CG_DEPRECATED _CG_STATIC_QUALIFIER void wait_prior(TyGroup &group, nvcuda::experimental::pipeline &pipe) {
+    pipe.wait_prior();
+    group.sync();
+}
+
+/* Group wait for stage-S of memcpy_async to complete. */
+template 
+_CG_DEPRECATED _CG_STATIC_QUALIFIER void wait(TyGroup &group, nvcuda::experimental::pipeline &pipe, size_t stage) {
+    pipe.wait(stage);
+    group.sync();
+}
+_CG_END_NAMESPACE
+
+#endif // _CG_ASYNC_H
diff --git a/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/coalesced_reduce.h b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/coalesced_reduce.h
new file mode 100644
index 0000000000000000000000000000000000000000..7ba03fc9e4d0c78f07e3e5e1f97aff03e7a3d6f8
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/coalesced_reduce.h
@@ -0,0 +1,95 @@
+ /* Copyright 1993-2016 NVIDIA Corporation.  All rights reserved.
+  *
+  * NOTICE TO LICENSEE:
+  *
+  * The source code and/or documentation ("Licensed Deliverables") are
+  * subject to NVIDIA intellectual property rights under U.S. and
+  * international Copyright laws.
+  *
+  * The Licensed Deliverables contained herein are PROPRIETARY and
+  * CONFIDENTIAL to NVIDIA and are being provided under the terms and
+  * conditions of a form of NVIDIA software license agreement by and
+  * between NVIDIA and Licensee ("License Agreement") or electronically
+  * accepted by Licensee.  Notwithstanding any terms or conditions to
+  * the contrary in the License Agreement, reproduction or disclosure
+  * of the Licensed Deliverables to any third party without the express
+  * written consent of NVIDIA is prohibited.
+  *
+  * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+  * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
+  * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE.  THEY ARE
+  * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
+  * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
+  * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
+  * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
+  * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+  * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
+  * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
+  * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+  * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+  * OF THESE LICENSED DELIVERABLES.
+  *
+  * U.S. Government End Users.  These Licensed Deliverables are a
+  * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
+  * 1995), consisting of "commercial computer software" and "commercial
+  * computer software documentation" as such terms are used in 48
+  * C.F.R. 12.212 (SEPT 1995) and are provided to the U.S. Government
+  * only as a commercial end item.  Consistent with 48 C.F.R.12.212 and
+  * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
+  * U.S. Government End Users acquire the Licensed Deliverables with
+  * only those rights set forth herein.
+  *
+  * Any use of the Licensed Deliverables in individual and commercial
+  * software must include, in the user documentation and internal
+  * comments to the code, the above Disclaimer and U.S. Government End
+  * Users Notice.
+  */
+
+#ifndef _CG_COALESCED_REDUCE_H_
+#define _CG_COALESCED_REDUCE_H_
+
+#include "info.h"
+#include "helpers.h"
+#include "cooperative_groups.h"
+#include "partitioning.h"
+#include "coalesced_scan.h"
+
+_CG_BEGIN_NAMESPACE
+
+namespace details {
+
+template 
+_CG_QUALIFIER auto coalesced_reduce(const __single_warp_thread_block_tile& group, 
+                                    TyVal&& val,
+                                    TyOp&& op) -> decltype(op(val, val)) {
+    auto out = val;
+    for (int mask = TySize >> 1; mask > 0; mask >>= 1) {
+        out = op(out, group.shfl_xor(out, mask));
+    }
+
+    return out;
+}
+
+template 
+_CG_QUALIFIER auto coalesced_reduce(const coalesced_group& group, TyVal&& val, TyOp&& op) -> decltype(op(val, val)) {
+    if (group.size() == 32) {
+        // Full coalesced group can go through faster path by being treated as a tile of size 32
+        auto tile = details::tiled_partition_internal<32, void>();
+        return coalesced_reduce(tile, _CG_STL_NAMESPACE::forward(val), _CG_STL_NAMESPACE::forward(op));
+    }
+    else {
+        auto scan_result =
+            inclusive_scan_non_contiguous(group, _CG_STL_NAMESPACE::forward(val), _CG_STL_NAMESPACE::forward(op));
+        unsigned int group_mask = _coalesced_group_data_access::get_mask(group);
+        unsigned int last_thread_id = 31 - __clz(group_mask);
+        return details::tile::shuffle_dispatch::shfl(
+            _CG_STL_NAMESPACE::forward(scan_result), group_mask, last_thread_id, 32);
+    }
+}
+
+} // details
+
+_CG_END_NAMESPACE
+
+#endif // _CG_COALESCED_REDUCE_H_
diff --git a/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/coalesced_scan.h b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/coalesced_scan.h
new file mode 100644
index 0000000000000000000000000000000000000000..383f4bde059dd8daad7d1c56e99152ea7ee28a08
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/coalesced_scan.h
@@ -0,0 +1,174 @@
+/* Copyright 1993-2016 NVIDIA Corporation.  All rights reserved.
+  *
+  * NOTICE TO LICENSEE:
+  *
+  * The source code and/or documentation ("Licensed Deliverables") are
+  * subject to NVIDIA intellectual property rights under U.S. and
+  * international Copyright laws.
+  *
+  * The Licensed Deliverables contained herein are PROPRIETARY and
+  * CONFIDENTIAL to NVIDIA and are being provided under the terms and
+  * conditions of a form of NVIDIA software license agreement by and
+  * between NVIDIA and Licensee ("License Agreement") or electronically
+  * accepted by Licensee.  Notwithstanding any terms or conditions to
+  * the contrary in the License Agreement, reproduction or disclosure
+  * of the Licensed Deliverables to any third party without the express
+  * written consent of NVIDIA is prohibited.
+  *
+  * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+  * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
+  * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE.  THEY ARE
+  * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
+  * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
+  * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
+  * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
+  * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+  * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
+  * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
+  * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+  * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+  * OF THESE LICENSED DELIVERABLES.
+  *
+  * U.S. Government End Users.  These Licensed Deliverables are a
+  * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
+  * 1995), consisting of "commercial computer software" and "commercial
+  * computer software documentation" as such terms are used in 48
+  * C.F.R. 12.212 (SEPT 1995) and are provided to the U.S. Government
+  * only as a commercial end item.  Consistent with 48 C.F.R.12.212 and
+  * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
+  * U.S. Government End Users acquire the Licensed Deliverables with
+  * only those rights set forth herein.
+  *
+  * Any use of the Licensed Deliverables in individual and commercial
+  * software must include, in the user documentation and internal
+  * comments to the code, the above Disclaimer and U.S. Government End
+  * Users Notice.
+  */
+
+#ifndef _CG_COALESCED_SCAN_H_
+#define _CG_COALESCED_SCAN_H_
+
+#include "info.h"
+#include "helpers.h"
+#include "cooperative_groups.h"
+#include "partitioning.h"
+#include "functional.h"
+
+_CG_BEGIN_NAMESPACE
+
+namespace details {
+
+template 
+_CG_QUALIFIER auto inclusive_scan_contiguous(const TyGroup& group, TyVal&& val, TyOp&& op) -> decltype(op(val, val)) {
+    auto out = val;
+    for (int mask = 1; mask < group.size(); mask <<= 1) {
+        auto tmp = group.shfl_up(out, mask);
+        if (mask <= group.thread_rank()) {
+            out = op(out, tmp);
+        }
+    }
+
+    return out;
+}
+
+template 
+_CG_QUALIFIER auto inclusive_scan_non_contiguous(const TyGroup& group, TyVal&& val, TyOp&& op) -> decltype(op(val, val)) {
+    const unsigned int groupSize = group.size();
+    auto out = val;
+
+    const unsigned int mask = details::_coalesced_group_data_access::get_mask(group);
+    unsigned int lanemask = details::lanemask32_lt() & mask;
+    unsigned int srcLane = details::laneid();
+
+    const unsigned int base = __ffs(mask)-1; /* lane with rank == 0 */
+    const unsigned int rank = __popc(lanemask);
+
+    for (unsigned int i = 1, j = 1; i < groupSize; i <<= 1) {
+        if (i <= rank) {
+            srcLane -= j;
+            j = i; /* maximum possible lane */
+
+            unsigned int begLane = base + rank - i; /* minimum possible lane */
+
+            /*  Next source lane is in the range [ begLane .. srcLane ]
+                *  If begLane < srcLane then do a binary search.
+                */
+            while (begLane < srcLane) {
+                const unsigned int halfLane = (begLane + srcLane) >> 1;
+                const unsigned int halfMask = lanemask >> halfLane;
+                const unsigned int d = __popc(halfMask);
+                if (d < i) {
+                    srcLane = halfLane - 1; /* halfLane too large */
+                }
+                else if ((i < d) || !(halfMask & 0x01)) {
+                    begLane = halfLane + 1; /* halfLane too small */
+                }
+                else {
+                    begLane = srcLane = halfLane; /* happen to hit */
+                }
+            }
+        }
+
+        auto tmp = details::tile::shuffle_dispatch::shfl(out, mask, srcLane, 32);
+        if (i <= rank) {
+            out = op(out, tmp);
+        }
+    }
+    return out;
+}
+
+template 
+_CG_QUALIFIER auto coalesced_inclusive_scan(const __single_warp_thread_block_tile& group,
+                                            TyVal&& val,
+                                            TyOp&& op) -> decltype(op(val, val)) {
+    return inclusive_scan_contiguous(group, _CG_STL_NAMESPACE::forward(val), _CG_STL_NAMESPACE::forward(op));
+}
+
+template 
+_CG_QUALIFIER auto coalesced_inclusive_scan(const coalesced_group& group, TyVal&& val, TyOp&& op) -> decltype(op(val, val)) {
+    if (group.size() == 32) {
+        return inclusive_scan_contiguous(group, _CG_STL_NAMESPACE::forward(val), _CG_STL_NAMESPACE::forward(op));
+    }
+    else {
+        return inclusive_scan_non_contiguous(group, _CG_STL_NAMESPACE::forward(val), _CG_STL_NAMESPACE::forward(op));
+    }
+}
+
+template 
+struct scan_choose_convertion;
+
+template<>
+struct scan_choose_convertion {
+    template 
+    _CG_STATIC_QUALIFIER details::remove_qual convert_inclusive_to_exclusive(const TyGroup& group, TyRes& result, TyVal&& val) {
+        return result - val;
+    }
+};
+
+template<>
+struct scan_choose_convertion {
+    template 
+    _CG_STATIC_QUALIFIER details::remove_qual convert_inclusive_to_exclusive(const TyGroup& group, TyRes& result, TyVal&& val) {
+        auto ret = group.shfl_up(result, 1);
+        if (group.thread_rank() == 0) {
+            return {};
+        }
+        else {
+            return ret;
+        }
+    }
+};
+
+template 
+_CG_QUALIFIER auto convert_inclusive_to_exclusive(const TyGroup& group, TyRes& result, TyVal&& val, TyFn&& op) -> decltype(op(val, val)) {
+    using conversion = scan_choose_convertion<_CG_STL_NAMESPACE::is_same, cooperative_groups::plus>>::value
+                                 && _CG_STL_NAMESPACE::is_integral>::value>;
+    return conversion::convert_inclusive_to_exclusive(group, result, _CG_STL_NAMESPACE::forward(val));
+}
+
+} // details
+
+_CG_END_NAMESPACE
+
+#endif // _CG_COALESCED_SCAN_H_
\ No newline at end of file
diff --git a/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/driver_abi.h b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/driver_abi.h
new file mode 100644
index 0000000000000000000000000000000000000000..9c866fcf740beb709a106057d28e8a2a1ac37924
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/driver_abi.h
@@ -0,0 +1,99 @@
+ /* Copyright 1993-2016 NVIDIA Corporation.  All rights reserved.
+  *
+  * NOTICE TO LICENSEE:
+  *
+  * The source code and/or documentation ("Licensed Deliverables") are
+  * subject to NVIDIA intellectual property rights under U.S. and
+  * international Copyright laws.
+  *
+  * The Licensed Deliverables contained herein are PROPRIETARY and
+  * CONFIDENTIAL to NVIDIA and are being provided under the terms and
+  * conditions of a form of NVIDIA software license agreement by and
+  * between NVIDIA and Licensee ("License Agreement") or electronically
+  * accepted by Licensee.  Notwithstanding any terms or conditions to
+  * the contrary in the License Agreement, reproduction or disclosure
+  * of the Licensed Deliverables to any third party without the express
+  * written consent of NVIDIA is prohibited.
+  *
+  * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+  * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
+  * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE.  THEY ARE
+  * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
+  * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
+  * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
+  * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
+  * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+  * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
+  * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
+  * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+  * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+  * OF THESE LICENSED DELIVERABLES.
+  *
+  * U.S. Government End Users.  These Licensed Deliverables are a
+  * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
+  * 1995), consisting of "commercial computer software" and "commercial
+  * computer software documentation" as such terms are used in 48
+  * C.F.R. 12.212 (SEPT 1995) and are provided to the U.S. Government
+  * only as a commercial end item.  Consistent with 48 C.F.R.12.212 and
+  * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
+  * U.S. Government End Users acquire the Licensed Deliverables with
+  * only those rights set forth herein.
+  *
+  * Any use of the Licensed Deliverables in individual and commercial
+  * software must include, in the user documentation and internal
+  * comments to the code, the above Disclaimer and U.S. Government End
+  * Users Notice.
+  */
+
+#ifndef _CG_DRIVER_API_H
+#define _CG_DRIVER_API_H
+
+#include "info.h"
+
+_CG_BEGIN_NAMESPACE
+
+namespace details {
+    template 
+    _CG_QUALIFIER unsigned int load_env_reg() {
+        // Abort by default
+        _CG_ABORT();
+        return 0;
+    }
+
+    template 
+    _CG_QUALIFIER unsigned long long load_env_reg64() {
+        unsigned long long registerLo = load_env_reg();
+        unsigned long long registerHi = load_env_reg();
+
+        return (registerHi << 32) | registerLo;
+    }
+
+// inline PTX for accessing registers requires an immediate for the special reg
+# define LOAD_ENVREG(NUMBER) \
+    template <> _CG_QUALIFIER unsigned int load_env_reg() { \
+        unsigned int r; \
+        asm ("mov.u32 %0, %%envreg" #NUMBER ";" : "=r"(r)); \
+        return r; \
+    }
+
+    // Instantiate loaders for registers used
+    LOAD_ENVREG(0);
+    LOAD_ENVREG(1);
+    LOAD_ENVREG(2);
+# undef LOAD_ENVREG
+
+    struct grid_workspace {
+        unsigned int wsSize;
+        unsigned int barrier;
+    };
+
+    _CG_QUALIFIER grid_workspace* get_grid_workspace() {
+        unsigned long long gridWsAbiAddress = load_env_reg64<1, 2>();
+        // Interpret the address from envreg 1 and 2 as the driver's grid workspace
+        return (reinterpret_cast(gridWsAbiAddress));
+    }
+}
+_CG_END_NAMESPACE
+
+#endif // _CG_DRIVER_API_H
diff --git a/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/functional.h b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/functional.h
new file mode 100644
index 0000000000000000000000000000000000000000..0f151fe2c270421ba56e22935e84c4bf93790eff
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/functional.h
@@ -0,0 +1,212 @@
+ /* Copyright 1993-2016 NVIDIA Corporation.  All rights reserved.
+  *
+  * NOTICE TO LICENSEE:
+  *
+  * The source code and/or documentation ("Licensed Deliverables") are
+  * subject to NVIDIA intellectual property rights under U.S. and
+  * international Copyright laws.
+  *
+  * The Licensed Deliverables contained herein are PROPRIETARY and
+  * CONFIDENTIAL to NVIDIA and are being provided under the terms and
+  * conditions of a form of NVIDIA software license agreement by and
+  * between NVIDIA and Licensee ("License Agreement") or electronically
+  * accepted by Licensee.  Notwithstanding any terms or conditions to
+  * the contrary in the License Agreement, reproduction or disclosure
+  * of the Licensed Deliverables to any third party without the express
+  * written consent of NVIDIA is prohibited.
+  *
+  * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+  * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
+  * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE.  THEY ARE
+  * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
+  * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
+  * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
+  * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
+  * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+  * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
+  * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
+  * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+  * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+  * OF THESE LICENSED DELIVERABLES.
+  *
+  * U.S. Government End Users.  These Licensed Deliverables are a
+  * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
+  * 1995), consisting of "commercial computer software" and "commercial
+  * computer software documentation" as such terms are used in 48
+  * C.F.R. 12.212 (SEPT 1995) and are provided to the U.S. Government
+  * only as a commercial end item.  Consistent with 48 C.F.R.12.212 and
+  * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
+  * U.S. Government End Users acquire the Licensed Deliverables with
+  * only those rights set forth herein.
+  *
+  * Any use of the Licensed Deliverables in individual and commercial
+  * software must include, in the user documentation and internal
+  * comments to the code, the above Disclaimer and U.S. Government End
+  * Users Notice.
+  */
+
+#ifndef _CG_FUNCTIONAL_H
+#define _CG_FUNCTIONAL_H
+
+#include "info.h"
+#include "helpers.h"
+
+#ifdef _CG_CPP11_FEATURES
+#ifdef _CG_USE_CUDA_STL
+# include 
+#endif
+
+_CG_BEGIN_NAMESPACE
+
+namespace details {
+#ifdef _CG_USE_CUDA_STL
+    using cuda::std::plus;
+    using cuda::std::bit_and;
+    using cuda::std::bit_xor;
+    using cuda::std::bit_or;
+#else
+    template  struct plus {__device__ __forceinline__ Ty operator()(Ty arg1, Ty arg2) const {return arg1 + arg2;}};
+    template  struct bit_and {__device__ __forceinline__ Ty operator()(Ty arg1, Ty arg2) const {return arg1 & arg2;}};
+    template  struct bit_xor {__device__ __forceinline__ Ty operator()(Ty arg1, Ty arg2) const {return arg1 ^ arg2;}};
+    template  struct bit_or {__device__ __forceinline__ Ty operator()(Ty arg1, Ty arg2) const {return arg1 | arg2;}};
+#endif // _CG_USE_PLATFORM_STL
+} // details
+
+template 
+struct plus : public details::plus {};
+
+template 
+struct less {
+    __device__ __forceinline__ Ty operator()(Ty arg1, Ty arg2) const {
+        return (arg2 < arg1) ? arg2 : arg1;
+    }
+};
+
+template 
+struct greater {
+    __device__ __forceinline__ Ty operator()(Ty arg1, Ty arg2) const {
+        return (arg1 < arg2) ? arg2 : arg1;
+    }
+};
+
+template 
+struct bit_and : public details::bit_and {};
+
+template 
+struct bit_xor : public details::bit_xor {};
+
+template 
+struct bit_or : public details::bit_or {};
+
+#if defined(_CG_HAS_STL_ATOMICS)
+namespace details {
+    template 
+    using _atomic_is_type_supported = _CG_STL_NAMESPACE::integral_constant::value && (sizeof(Ty) == 4 || sizeof(Ty) == 8)>;
+
+    template  struct _atomic_op_supported                                : public _CG_STL_NAMESPACE::false_type {};
+    template  struct _atomic_op_supported>    : public _atomic_is_type_supported {};
+    template  struct _atomic_op_supported>    : public _atomic_is_type_supported {};
+    template  struct _atomic_op_supported> : public _atomic_is_type_supported {};
+    template  struct _atomic_op_supported> : public _atomic_is_type_supported {};
+    template  struct _atomic_op_supported>  : public _atomic_is_type_supported {};
+    template  struct _atomic_op_supported> : public _atomic_is_type_supported {};
+
+    template
+    _CG_QUALIFIER remove_qual atomic_cas_fallback(TyAtomic&& atomic, TyVal&& val, TyOp&& op) {
+        auto old = atomic.load(cuda::std::memory_order_relaxed);
+        while(!atomic.compare_exchange_weak(old, op(old, val), cuda::std::memory_order_relaxed));
+        return old;
+    }
+
+    template
+    struct op_picker;
+
+    template
+    struct op_picker> {
+        template
+        _CG_STATIC_QUALIFIER TyVal atomic_update(TyAtomic& atomic, TyVal val) {
+            return atomic.fetch_add(val, cuda::std::memory_order_relaxed);
+        }
+    };
+
+    template
+    struct op_picker> {
+        template
+        _CG_STATIC_QUALIFIER TyVal atomic_update(TyAtomic& atomic, TyVal val) {
+            return atomic.fetch_min(val, cuda::std::memory_order_relaxed);
+        }
+    };
+
+    template
+    struct op_picker> {
+        template
+        _CG_STATIC_QUALIFIER TyVal atomic_update(TyAtomic& atomic, TyVal val) {
+            return atomic.fetch_max(val, cuda::std::memory_order_relaxed);
+        }
+    };
+
+    template
+    struct op_picker> {
+        template
+        _CG_STATIC_QUALIFIER TyVal atomic_update(TyAtomic& atomic, TyVal val) {
+            return atomic.fetch_and(val, cuda::std::memory_order_relaxed);
+        }
+    };
+
+    template
+    struct op_picker> {
+        template
+        _CG_STATIC_QUALIFIER TyVal atomic_update(TyAtomic& atomic, TyVal val) {
+            return atomic.fetch_xor(val, cuda::std::memory_order_relaxed);
+        }
+    };
+
+    template
+    struct op_picker> {
+        template
+        _CG_STATIC_QUALIFIER TyVal atomic_update(TyAtomic& atomic, TyVal val) {
+            return atomic.fetch_or(val, cuda::std::memory_order_relaxed);
+        }
+    };
+
+    template
+    struct atomic_update_dispatch {};
+
+    template<>
+    struct atomic_update_dispatch {
+        template
+        _CG_STATIC_QUALIFIER remove_qual atomic_update(TyAtomic& atomic, TyVal&& val, TyOp&& op) {
+            return atomic_cas_fallback(atomic, _CG_STL_NAMESPACE::forward(val), _CG_STL_NAMESPACE::forward(op));
+        }
+    };
+
+    template<>
+    struct atomic_update_dispatch {
+        template
+        _CG_STATIC_QUALIFIER TyVal atomic_update(TyAtomic& atomic, TyVal val, TyOp&& op) {
+            using dispatch = op_picker>;
+
+            return dispatch::atomic_update(atomic, val);
+        }
+    };
+
+    template
+    _CG_QUALIFIER remove_qual atomic_update(TyAtomic& atomic, TyVal&& val, TyOp&& op) {
+        using dispatch = atomic_update_dispatch<_atomic_op_supported>::value>;
+
+        return dispatch::atomic_update(atomic, _CG_STL_NAMESPACE::forward(val), _CG_STL_NAMESPACE::forward(op));
+    }
+
+    template
+    _CG_QUALIFIER void atomic_store(TyAtomic& atomic, TyVal&& val) {
+        atomic.store(val, cuda::std::memory_order_relaxed);
+    }
+}
+#endif
+
+_CG_END_NAMESPACE
+
+#endif
+#endif //_CG_FUNCTIONAL_H
diff --git a/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/helpers.h b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/helpers.h
new file mode 100644
index 0000000000000000000000000000000000000000..1485d9f503daa8d518af75775f7a7a415cb031d4
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/helpers.h
@@ -0,0 +1,693 @@
+ /* Copyright 1993-2021 NVIDIA Corporation.  All rights reserved.
+  *
+  * NOTICE TO LICENSEE:
+  *
+  * The source code and/or documentation ("Licensed Deliverables") are
+  * subject to NVIDIA intellectual property rights under U.S. and
+  * international Copyright laws.
+  *
+  * The Licensed Deliverables contained herein are PROPRIETARY and
+  * CONFIDENTIAL to NVIDIA and are being provided under the terms and
+  * conditions of a form of NVIDIA software license agreement by and
+  * between NVIDIA and Licensee ("License Agreement") or electronically
+  * accepted by Licensee.  Notwithstanding any terms or conditions to
+  * the contrary in the License Agreement, reproduction or disclosure
+  * of the Licensed Deliverables to any third party without the express
+  * written consent of NVIDIA is prohibited.
+  *
+  * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+  * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
+  * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE.  THEY ARE
+  * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
+  * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
+  * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
+  * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
+  * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+  * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
+  * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
+  * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+  * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+  * OF THESE LICENSED DELIVERABLES.
+  *
+  * U.S. Government End Users.  These Licensed Deliverables are a
+  * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
+  * 1995), consisting of "commercial computer software" and "commercial
+  * computer software documentation" as such terms are used in 48
+  * C.F.R. 12.212 (SEPT 1995) and are provided to the U.S. Government
+  * only as a commercial end item.  Consistent with 48 C.F.R.12.212 and
+  * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
+  * U.S. Government End Users acquire the Licensed Deliverables with
+  * only those rights set forth herein.
+  *
+  * Any use of the Licensed Deliverables in individual and commercial
+  * software must include, in the user documentation and internal
+  * comments to the code, the above Disclaimer and U.S. Government End
+  * Users Notice.
+  */
+
+#ifndef _COOPERATIVE_GROUPS_HELPERS_H_
+# define _COOPERATIVE_GROUPS_HELPERS_H_
+
+#include "info.h"
+#include "sync.h"
+
+_CG_BEGIN_NAMESPACE
+
+namespace details {
+#ifdef _CG_CPP11_FEATURES
+    template  struct _is_float_or_half          : public _CG_STL_NAMESPACE::is_floating_point {};
+# ifdef _CG_HAS_FP16_COLLECTIVE
+    template <>            struct _is_float_or_half<__half>  : public _CG_STL_NAMESPACE::true_type {};
+    template <>            struct _is_float_or_half<__half2> : public _CG_STL_NAMESPACE::true_type {};
+# endif
+    template 
+    using  is_float_or_half = _is_float_or_half::type>;
+
+    // Non-STL utility templates 
+    template 
+    using remove_qual = typename _CG_STL_NAMESPACE::remove_cv::type>::type;
+
+    template 
+    using is_op_type_same = _CG_STL_NAMESPACE::is_same, remove_qual
+    >;
+#endif
+
+    template 
+    _CG_STATIC_QUALIFIER TyTrunc vec3_to_linear(dim3 index, dim3 nIndex) {
+        return ((TyTrunc)index.z * nIndex.y * nIndex.x) +
+               ((TyTrunc)index.y * nIndex.x) +
+                (TyTrunc)index.x;
+    }
+
+    namespace cta {
+
+        _CG_STATIC_QUALIFIER void sync()
+        {
+            __barrier_sync(0);
+        }
+
+        _CG_STATIC_QUALIFIER unsigned int num_threads()
+        {
+            return static_cast(blockDim.x * blockDim.y * blockDim.z);
+        }
+
+        _CG_STATIC_QUALIFIER unsigned int thread_rank()
+        {
+            return vec3_to_linear(threadIdx, blockDim);
+        }
+
+        _CG_STATIC_QUALIFIER dim3 group_index()
+        {
+            return dim3(blockIdx.x, blockIdx.y, blockIdx.z);
+        }
+
+        _CG_STATIC_QUALIFIER dim3 thread_index()
+        {
+            return dim3(threadIdx.x, threadIdx.y, threadIdx.z);
+        }
+
+        _CG_STATIC_QUALIFIER dim3 dim_threads()
+        {
+            return dim3(blockDim.x, blockDim.y, blockDim.z);
+        }
+
+        // Legacy aliases
+        _CG_STATIC_QUALIFIER unsigned int size()
+        {
+            return num_threads();
+        }
+
+        _CG_STATIC_QUALIFIER dim3 block_dim()
+        {
+            return dim_threads();
+        }
+
+    };
+
+    class _coalesced_group_data_access {
+    public:
+        // Retrieve mask of coalesced groups and tiles
+        template 
+        _CG_STATIC_QUALIFIER unsigned int get_mask(const TyGroup &group) {
+            return group.get_mask();
+        }
+
+        template 
+        _CG_STATIC_QUALIFIER TyGroup construct_from_mask(unsigned int mask) {
+            return TyGroup(mask);
+        }
+
+        template 
+        _CG_STATIC_QUALIFIER void modify_meta_group(TyGroup &group, unsigned int mgRank, unsigned int mgSize) {
+            group._data.coalesced.metaGroupRank = mgRank;
+            group._data.coalesced.metaGroupSize = mgSize;
+        }
+    };
+
+    namespace tile {
+        template 
+        struct _tile_helpers{
+            _CG_STATIC_CONST_DECL unsigned int tileCount = TileCount;
+            _CG_STATIC_CONST_DECL unsigned int tileMask = TileMask;
+            _CG_STATIC_CONST_DECL unsigned int laneMask = LaneMask;
+            _CG_STATIC_CONST_DECL unsigned int shiftCount = ShiftCount;
+        };
+
+        template  struct tile_helpers;
+        template <> struct tile_helpers<32> : public _tile_helpers<1,  0xFFFFFFFF, 0x1F, 5> {};
+        template <> struct tile_helpers<16> : public _tile_helpers<2,  0x0000FFFF, 0x0F, 4> {};
+        template <> struct tile_helpers<8>  : public _tile_helpers<4,  0x000000FF, 0x07, 3> {};
+        template <> struct tile_helpers<4>  : public _tile_helpers<8,  0x0000000F, 0x03, 2> {};
+        template <> struct tile_helpers<2>  : public _tile_helpers<16, 0x00000003, 0x01, 1> {};
+        template <> struct tile_helpers<1>  : public _tile_helpers<32, 0x00000001, 0x00, 0> {};
+
+#ifdef _CG_CPP11_FEATURES
+        namespace shfl {
+            /***********************************************************************************
+             * Recursively Sliced Shuffle
+             *  Purpose:
+             *      Slices an input type a number of times into integral types so that shuffles
+             *      are well defined
+             *  Expectations:
+             *      This object *should not* be used from a reinterpret_cast pointer unless
+             *      some alignment guarantees can be met. Use a memcpy to guarantee that loads
+             *      from the integral types stored within are aligned and correct.
+             **********************************************************************************/
+            template 
+            struct recursive_sliced_shuffle_helper;
+
+            template 
+            struct recursive_sliced_shuffle_helper {
+                int val;
+
+                template 
+                _CG_QUALIFIER void invoke_shuffle(const TyFn &shfl) {
+                    val = shfl(val);
+                }
+            };
+
+            template 
+            struct recursive_sliced_shuffle_helper {
+                int val;
+                recursive_sliced_shuffle_helper next;
+
+                template 
+                _CG_QUALIFIER void invoke_shuffle(const TyFn &shfl) {
+                    val = shfl(val);
+                    next.invoke_shuffle(shfl);
+                }
+            };
+        }
+
+        struct _memory_shuffle {
+            template 
+            _CG_STATIC_QUALIFIER TyElem _shfl_internal(TyElem elem, const TyShflFn& fn) {
+                static_assert(sizeof(TyElem) <= 32, "Cooperative groups collectives are limited to types smaller than 32B");
+                return TyElem{};
+            }
+
+            template >
+            _CG_STATIC_QUALIFIER TyRet shfl(TyElem&& elem, unsigned int gMask, unsigned int srcRank, unsigned int threads) {
+                auto shfl = [=](int val) -> int {
+                    return 0;
+                };
+
+                return _shfl_internal(_CG_STL_NAMESPACE::forward(elem), shfl);
+            }
+
+            template >
+            _CG_STATIC_QUALIFIER TyRet shfl_down(TyElem&& elem, unsigned int gMask, unsigned int delta, unsigned int threads) {
+                auto shfl = [=](int val) -> int {
+                    return 0;
+                };
+
+                return _shfl_internal(_CG_STL_NAMESPACE::forward(elem), shfl);
+            }
+
+            template >
+            _CG_STATIC_QUALIFIER TyRet shfl_up(TyElem&& elem, unsigned int gMask, unsigned int delta, unsigned int threads) {
+                auto shfl = [=](int val) -> int {
+                    return 0;
+                };
+
+                return _shfl_internal(_CG_STL_NAMESPACE::forward(elem), shfl);
+            }
+
+            template >
+            _CG_STATIC_QUALIFIER TyRet shfl_xor(TyElem&& elem, unsigned int gMask, unsigned int lMask, unsigned int threads) {
+                auto shfl = [=](int val) -> int {
+                    return 0;
+                };
+
+                return _shfl_internal(_CG_STL_NAMESPACE::forward(elem), shfl);
+            }
+        };
+
+        /***********************************************************************************
+         * Intrinsic Device Function Shuffle
+         *  Purpose:
+         *      Uses a shuffle helper that has characteristics best suited for moving
+         *      elements between threads
+         *  Expectations:
+         *      Object given will be forced into an l-value type so that it can be used
+         *      with a helper structure that reinterprets the data into intrinsic compatible
+         *      types
+         *  Notes:
+         *      !! TyRet is required so that objects are returned by value and not as
+         *      dangling references depending on the value category of the passed object
+         **********************************************************************************/
+        struct _intrinsic_compat_shuffle {
+            template 
+            using shfl_helper = shfl::recursive_sliced_shuffle_helper;
+
+            template 
+            _CG_STATIC_QUALIFIER TyElem _shfl_internal(TyElem elem, const TyShflFn& fn) {
+                static_assert(__is_trivially_copyable(TyElem), "Type is not compatible with device shuffle");
+                shfl_helper helper;
+                memcpy(&helper, &elem, sizeof(TyElem));
+                helper.invoke_shuffle(fn);
+                memcpy(&elem, &helper, sizeof(TyElem));
+                return elem;
+            }
+
+            template >
+            _CG_STATIC_QUALIFIER TyRet shfl(TyElem&& elem, unsigned int gMask, unsigned int srcRank, unsigned int threads) {
+                auto shfl = [=](int val) -> int {
+                    return __shfl_sync(gMask, val, srcRank, threads);
+                };
+
+                return _shfl_internal(_CG_STL_NAMESPACE::forward(elem), shfl);
+            }
+
+            template >
+            _CG_STATIC_QUALIFIER TyRet shfl_down(TyElem&& elem, unsigned int gMask, unsigned int delta, unsigned int threads) {
+                auto shfl = [=](int val) -> int {
+                    return __shfl_down_sync(gMask, val, delta, threads);
+                };
+
+                return _shfl_internal(_CG_STL_NAMESPACE::forward(elem), shfl);
+            }
+
+            template >
+            _CG_STATIC_QUALIFIER TyRet shfl_up(TyElem&& elem, unsigned int gMask, unsigned int delta, unsigned int threads) {
+                auto shfl = [=](int val) -> int {
+                    return __shfl_up_sync(gMask, val, delta, threads);
+                };
+
+                return _shfl_internal(_CG_STL_NAMESPACE::forward(elem), shfl);
+            }
+
+            template >
+            _CG_STATIC_QUALIFIER TyRet shfl_xor(TyElem&& elem, unsigned int gMask, unsigned int lMask, unsigned int threads) {
+                auto shfl = [=](int val) -> int {
+                    return __shfl_xor_sync(gMask, val, lMask, threads);
+                };
+
+                return _shfl_internal(_CG_STL_NAMESPACE::forward(elem), shfl);
+            }
+        };
+
+        struct _native_shuffle {
+            template 
+            _CG_STATIC_QUALIFIER TyElem shfl(
+                    TyElem elem, unsigned int gMask, unsigned int srcRank, unsigned int threads) {
+                return static_cast(__shfl_sync(gMask, elem, srcRank, threads));
+            }
+
+            template 
+            _CG_STATIC_QUALIFIER TyElem shfl_down(
+                    TyElem elem, unsigned int gMask, unsigned int delta, unsigned int threads) {
+                return static_cast(__shfl_down_sync(gMask, elem, delta, threads));
+            }
+
+            template 
+            _CG_STATIC_QUALIFIER TyElem shfl_up(
+                    TyElem elem, unsigned int gMask, unsigned int delta, unsigned int threads) {
+                return static_cast(__shfl_up_sync(gMask, elem, delta, threads));
+            }
+
+            template 
+            _CG_STATIC_QUALIFIER TyElem shfl_xor(
+                    TyElem elem, unsigned int gMask, unsigned int lMask, unsigned int threads) {
+                return static_cast(__shfl_xor_sync(gMask, elem, lMask, threads));
+            }
+        };
+
+        // Almost all arithmetic types are supported by native shuffle
+        // Vector types are the exception
+        template 
+        using use_native_shuffle = _CG_STL_NAMESPACE::integral_constant<
+            bool,
+            _CG_STL_NAMESPACE::is_integral<
+                remove_qual>::value ||
+            details::is_float_or_half<
+                remove_qual>::value
+        >;
+
+        constexpr unsigned long long _MemoryShuffleCutoff = 32;
+
+        template ::value,
+                  bool InMem = (sizeof(TyElem) > _MemoryShuffleCutoff)>
+        struct shuffle_dispatch;
+
+        template 
+        struct shuffle_dispatch :  public _native_shuffle {};
+
+        template 
+        struct shuffle_dispatch : public _intrinsic_compat_shuffle {};
+
+        template 
+        struct shuffle_dispatch :  public _memory_shuffle {};
+
+#endif //_CG_CPP11_FEATURES
+    };
+
+    namespace multi_grid {
+        struct multi_grid_functions;
+    };
+
+    namespace grid {
+        _CG_STATIC_QUALIFIER unsigned int barrier_arrive(unsigned int *bar) {
+            return details::sync_grids_arrive(bar);
+        }
+
+        _CG_STATIC_QUALIFIER void barrier_wait(unsigned int token, unsigned int *bar) {
+            details::sync_grids_wait(token, bar);
+        }
+
+        _CG_STATIC_QUALIFIER void sync(unsigned int *bar) {
+            unsigned int token = details::sync_grids_arrive(bar);
+            details::sync_grids_wait(token, bar);
+        }
+
+        _CG_STATIC_QUALIFIER unsigned long long num_blocks()
+        {
+            // grid.y * grid.z -> [max(65535) * max(65535)] fits within 4b, promote after multiplication
+            // grid.x * (grid.y * grid.z) -> [max(2^31-1) * max(65535 * 65535)]  exceeds 4b, promote before multiplication
+            return (unsigned long long)gridDim.x * (gridDim.y * gridDim.z);
+        }
+
+        _CG_STATIC_QUALIFIER unsigned long long num_threads()
+        {
+            return num_blocks() * cta::num_threads();
+        }
+
+        _CG_STATIC_QUALIFIER unsigned long long block_rank()
+        {
+            return vec3_to_linear(blockIdx, gridDim);
+        }
+
+        _CG_STATIC_QUALIFIER unsigned long long thread_rank()
+        {
+            return block_rank() * cta::num_threads() + cta::thread_rank();
+        }
+
+        _CG_STATIC_QUALIFIER dim3 dim_blocks()
+        {
+            return dim3(gridDim.x, gridDim.y, gridDim.z);
+        }
+
+        _CG_STATIC_QUALIFIER dim3 block_index()
+        {
+            return dim3(blockIdx.x, blockIdx.y, blockIdx.z);
+        }
+
+        _CG_STATIC_QUALIFIER dim3 dim_threads()
+        {
+            return dim3(gridDim.x * blockDim.x, gridDim.y * blockDim.y, gridDim.z * blockDim.z);
+        }
+
+        _CG_STATIC_QUALIFIER dim3 thread_index()
+        {
+            return dim3(blockIdx.x * blockDim.x + threadIdx.x,
+                        blockIdx.y * blockDim.y + threadIdx.y,
+                        blockIdx.z * blockDim.z + threadIdx.z);
+        }
+
+#if defined(_CG_HAS_CLUSTER_GROUP)
+        _CG_STATIC_QUALIFIER dim3 dim_clusters() {
+            return __clusterGridDimInClusters();
+        }
+
+        _CG_STATIC_QUALIFIER unsigned long long num_clusters() {
+            const dim3 dimClusters = dim_clusters();
+            return dimClusters.x * dimClusters.y * dimClusters.z;
+        }
+
+        _CG_STATIC_QUALIFIER dim3 cluster_index() {
+            return __clusterIdx();
+        }
+
+        _CG_STATIC_QUALIFIER unsigned long long cluster_rank() {
+            return vec3_to_linear(cluster_index(), dim_clusters());
+        }
+#endif
+
+        // Legacy aliases
+        _CG_STATIC_QUALIFIER unsigned long long size()
+        {
+            return num_threads();
+        }
+
+        _CG_STATIC_QUALIFIER dim3 grid_dim()
+        {
+            return dim_blocks();
+        }
+    };
+
+
+#if defined(_CG_HAS_MULTI_GRID_GROUP)
+
+    namespace multi_grid {
+        _CG_STATIC_QUALIFIER unsigned long long get_intrinsic_handle()
+        {
+#if defined(__CUDACC_RDC__) || defined(__CUDACC_EWP__)
+            //this function is defined in device runtime library
+            //which requires separate compilation mode (__CUDACC_RDC__)
+            //or extended whole program mode (__CUDACC_EWP__)
+            return (cudaCGGetIntrinsicHandle(cudaCGScopeMultiGrid));
+#else   /* !(__CUDACC_RDC__ || __CUDACC_EWP__) */
+            return 0;
+#endif  /* __CUDACC_RDC__ || __CUDACC_EWP__ */
+        }
+
+        _CG_STATIC_QUALIFIER void sync(const unsigned long long handle)
+        {
+#if defined(__CUDACC_RDC__) || defined(__CUDACC_EWP__)
+            //this function is defined in device runtime library
+            //which requires separate compilation mode (__CUDACC_RDC__)
+            //or extended whole program mode (__CUDACC_EWP__)
+            cudaError_t err = cudaCGSynchronize(handle, 0);
+#endif  /* __CUDACC_RDC__ || __CUDACC_EWP__ */
+        }
+
+        _CG_STATIC_QUALIFIER unsigned int size(const unsigned long long handle)
+        {
+            unsigned int numThreads = 0;
+#if defined(__CUDACC_RDC__) || defined(__CUDACC_EWP__)
+            //this function is defined in device runtime library
+            //which requires separate compilation mode (__CUDACC_RDC__)
+            //or extended whole program mode (__CUDACC_EWP__)
+            cudaCGGetSize(&numThreads, NULL, handle);
+#endif  /* __CUDACC_RDC__ || __CUDACC_EWP__ */
+            return numThreads;
+        }
+
+        _CG_STATIC_QUALIFIER unsigned int thread_rank(const unsigned long long handle)
+        {
+            unsigned int threadRank = 0;
+#if defined(__CUDACC_RDC__) || defined(__CUDACC_EWP__)
+            //this function is defined in device runtime library
+            //which requires separate compilation mode (__CUDACC_RDC__)
+            //or extended whole program mode (__CUDACC_EWP__)
+            cudaCGGetRank(&threadRank, NULL, handle);
+#endif  /* __CUDACC_RDC__ || __CUDACC_EWP__ */
+            return threadRank;
+        }
+
+        _CG_STATIC_QUALIFIER unsigned int grid_rank(const unsigned long long handle)
+        {
+            unsigned int gridRank = 0;
+#if defined(__CUDACC_RDC__) || defined(__CUDACC_EWP__)
+            //this function is defined in device runtime library
+            //which requires separate compilation mode (__CUDACC_RDC__)
+            //or extended whole program mode (__CUDACC_EWP__)
+            cudaCGGetRank(NULL, &gridRank, handle);
+#endif  /* __CUDACC_RDC__ || __CUDACC_EWP__ */
+            return gridRank;
+        }
+
+        _CG_STATIC_QUALIFIER unsigned int num_grids(const unsigned long long handle)
+        {
+            unsigned int numGrids = 0;
+#if defined(__CUDACC_RDC__) || defined(__CUDACC_EWP__)
+            //this function is defined in device runtime library
+            //which requires separate compilation mode (__CUDACC_RDC__)
+            //or extended whole program mode (__CUDACC_EWP__)
+            cudaCGGetSize(NULL, &numGrids, handle);
+#endif  /* __CUDACC_RDC__ || __CUDACC_EWP__ */
+            return numGrids;
+        }
+
+# ifdef _CG_CPP11_FEATURES
+        struct multi_grid_functions {
+            decltype(multi_grid::get_intrinsic_handle) *get_intrinsic_handle;
+            decltype(multi_grid::sync) *sync;
+            decltype(multi_grid::size) *size;
+            decltype(multi_grid::thread_rank) *thread_rank;
+            decltype(multi_grid::grid_rank) *grid_rank;
+            decltype(multi_grid::num_grids) *num_grids;
+        };
+
+        template 
+        _CG_STATIC_QUALIFIER const multi_grid_functions* load_grid_intrinsics() {
+            __constant__ static const multi_grid_functions mgf {
+                &multi_grid::get_intrinsic_handle,
+                &multi_grid::sync,
+                &multi_grid::size,
+                &multi_grid::thread_rank,
+                &multi_grid::grid_rank,
+                &multi_grid::num_grids
+            };
+
+            return &mgf;
+        }
+# endif
+    };
+#endif
+
+#if defined(_CG_HAS_CLUSTER_GROUP)
+    namespace cluster {
+
+        _CG_STATIC_QUALIFIER bool isReal()
+        {
+            return __clusterDimIsSpecified();
+        }
+
+        _CG_STATIC_QUALIFIER void barrier_arrive()
+        {
+            __cluster_barrier_arrive();
+        }
+
+        _CG_STATIC_QUALIFIER void barrier_wait()
+        {
+            __cluster_barrier_wait();
+        }
+
+        _CG_STATIC_QUALIFIER void sync()
+        {
+            barrier_arrive();
+            barrier_wait();
+        }
+
+        _CG_STATIC_QUALIFIER unsigned int query_shared_rank(const void *addr)
+        {
+            return __cluster_query_shared_rank(addr);
+        }
+
+        template 
+        _CG_STATIC_QUALIFIER T* map_shared_rank(T *addr, int rank)
+        {
+            return static_cast(__cluster_map_shared_rank(addr, rank));
+        }
+
+        _CG_STATIC_QUALIFIER dim3 block_index()
+        {
+            return __clusterRelativeBlockIdx();
+        }
+
+        _CG_STATIC_QUALIFIER unsigned int block_rank()
+        {
+            return __clusterRelativeBlockRank();
+        }
+
+        _CG_STATIC_QUALIFIER dim3 thread_index()
+        {
+            const dim3 blockIndex = block_index();
+            return dim3(blockIndex.x * blockDim.x + threadIdx.x,
+                        blockIndex.y * blockDim.y + threadIdx.y,
+                        blockIndex.z * blockDim.z + threadIdx.z);
+        }
+
+        _CG_STATIC_QUALIFIER unsigned int thread_rank()
+        {
+            return block_rank() * cta::num_threads() + cta::thread_rank();
+        }
+
+        _CG_STATIC_QUALIFIER dim3 dim_blocks()
+        {
+            return __clusterDim();
+        }
+
+        _CG_STATIC_QUALIFIER unsigned int num_blocks()
+        {
+            return __clusterSizeInBlocks();
+        }
+
+        _CG_STATIC_QUALIFIER dim3 dim_threads()
+        {
+            const dim3 dimBlocks = dim_blocks();
+            const unsigned int x = dimBlocks.x * blockDim.x;
+            const unsigned int y = dimBlocks.y * blockDim.y;
+            const unsigned int z = dimBlocks.z * blockDim.z;
+            return dim3(x, y, z);
+        }
+
+        _CG_STATIC_QUALIFIER unsigned int num_threads()
+        {
+            return num_blocks() * cta::num_threads();
+        }
+
+    };
+#endif
+
+    _CG_STATIC_QUALIFIER unsigned int laneid()
+    {
+        unsigned int laneid;
+        asm ("mov.u32 %0, %%laneid;" : "=r"(laneid));
+        return laneid;
+    }
+
+    _CG_STATIC_QUALIFIER unsigned int lanemask32_eq()
+    {
+        unsigned int lanemask32_eq;
+        asm ("mov.u32 %0, %%lanemask_eq;" : "=r"(lanemask32_eq));
+        return (lanemask32_eq);
+    }
+
+    _CG_STATIC_QUALIFIER unsigned int lanemask32_lt()
+    {
+        unsigned int lanemask32_lt;
+        asm ("mov.u32 %0, %%lanemask_lt;" : "=r"(lanemask32_lt));
+        return (lanemask32_lt);
+    }
+
+    _CG_STATIC_QUALIFIER void abort()
+    {
+        _CG_ABORT();
+    }
+
+    template 
+    _CG_QUALIFIER void assert_if_not_arithmetic() {
+#ifdef _CG_CPP11_FEATURES
+        static_assert(
+            _CG_STL_NAMESPACE::is_integral::value ||
+            details::is_float_or_half::value,
+            "Error: Ty is neither integer or float"
+        );
+#endif //_CG_CPP11_FEATURES
+    }
+
+#ifdef _CG_CPP11_FEATURES
+    _CG_STATIC_QUALIFIER constexpr unsigned int log2(unsigned int x) {
+        return x == 1 ? 0 : 1 + log2(x / 2);
+    }
+#endif //_CG_CPP11_FEATURES
+
+}; // !Namespace internal
+
+_CG_END_NAMESPACE
+
+#endif /* !_COOPERATIVE_GROUPS_HELPERS_H_ */
diff --git a/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/info.h b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/info.h
new file mode 100644
index 0000000000000000000000000000000000000000..6abbea1e1ec5b0a92c18baabec7485929fe91c0d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/info.h
@@ -0,0 +1,345 @@
+ /* Copyright 1993-2021 NVIDIA Corporation.  All rights reserved.
+  *
+  * NOTICE TO LICENSEE:
+  *
+  * The source code and/or documentation ("Licensed Deliverables") are
+  * subject to NVIDIA intellectual property rights under U.S. and
+  * international Copyright laws.
+  *
+  * The Licensed Deliverables contained herein are PROPRIETARY and
+  * CONFIDENTIAL to NVIDIA and are being provided under the terms and
+  * conditions of a form of NVIDIA software license agreement by and
+  * between NVIDIA and Licensee ("License Agreement") or electronically
+  * accepted by Licensee.  Notwithstanding any terms or conditions to
+  * the contrary in the License Agreement, reproduction or disclosure
+  * of the Licensed Deliverables to any third party without the express
+  * written consent of NVIDIA is prohibited.
+  *
+  * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+  * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
+  * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE.  THEY ARE
+  * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
+  * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
+  * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
+  * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
+  * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+  * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
+  * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
+  * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+  * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+  * OF THESE LICENSED DELIVERABLES.
+  *
+  * U.S. Government End Users.  These Licensed Deliverables are a
+  * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
+  * 1995), consisting of "commercial computer software" and "commercial
+  * computer software documentation" as such terms are used in 48
+  * C.F.R. 12.212 (SEPT 1995) and are provided to the U.S. Government
+  * only as a commercial end item.  Consistent with 48 C.F.R.12.212 and
+  * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
+  * U.S. Government End Users acquire the Licensed Deliverables with
+  * only those rights set forth herein.
+  *
+  * Any use of the Licensed Deliverables in individual and commercial
+  * software must include, in the user documentation and internal
+  * comments to the code, the above Disclaimer and U.S. Government End
+  * Users Notice.
+  */
+
+
+#include 
+
+#ifndef _CG_INFO_H_
+#define _CG_INFO_H_
+/*
+** Define: _CG_VERSION
+*/
+#define _CG_VERSION 1000
+
+/*
+** Define: _CG_ABI_VERSION
+*/
+#ifndef _CG_ABI_VERSION
+# define _CG_ABI_VERSION 1
+#endif
+
+/*
+** Define: _CG_ABI_EXPERIMENTAL
+** Desc: If enabled, sets all features enabled (ABI-breaking or experimental)
+*/
+#if defined(_CG_ABI_EXPERIMENTAL)
+#endif
+
+#define _CG_CONCAT_INNER(x, y) x ## y
+#define _CG_CONCAT_OUTER(x, y) _CG_CONCAT_INNER(x, y)
+#define _CG_NAMESPACE _CG_CONCAT_OUTER(__v, _CG_ABI_VERSION)
+
+#define _CG_BEGIN_NAMESPACE \
+    namespace cooperative_groups { namespace _CG_NAMESPACE {
+#define _CG_END_NAMESPACE \
+    }; using namespace _CG_NAMESPACE; };
+
+#if (defined(__cplusplus) && (__cplusplus >= 201103L)) || (defined(_MSC_VER) && (_MSC_VER >= 1900))
+# define _CG_CPP11_FEATURES
+#endif
+
+#if !defined(_CG_QUALIFIER)
+# define _CG_QUALIFIER __forceinline__ __device__
+#endif
+#if !defined(_CG_STATIC_QUALIFIER)
+# define _CG_STATIC_QUALIFIER static __forceinline__ __device__
+#endif
+#if !defined(_CG_CONSTEXPR_QUALIFIER)
+# if defined(_CG_CPP11_FEATURES)
+#  define _CG_CONSTEXPR_QUALIFIER constexpr __forceinline__ __device__
+# else
+#  define _CG_CONSTEXPR_QUALIFIER _CG_QUALIFIER
+# endif
+#endif
+#if !defined(_CG_STATIC_CONSTEXPR_QUALIFIER)
+# if defined(_CG_CPP11_FEATURES)
+#  define _CG_STATIC_CONSTEXPR_QUALIFIER static constexpr __forceinline__ __device__
+# else
+#  define _CG_STATIC_CONSTEXPR_QUALIFIER _CG_STATIC_QUALIFIER
+# endif
+#endif
+
+#if defined(_MSC_VER)
+# define _CG_DEPRECATED __declspec(deprecated)
+#else
+# define _CG_DEPRECATED __attribute__((deprecated))
+#endif
+
+#if defined(__CUDA_MINIMUM_ARCH__)
+# define _CG_CUDA_ARCH __CUDA_MINIMUM_ARCH__
+#elif defined(__CUDA_ARCH__)
+# define _CG_CUDA_ARCH __CUDA_ARCH__
+#endif
+
+#if (_CG_CUDA_ARCH >= 600) || !defined(_CG_CUDA_ARCH)
+# define _CG_HAS_GRID_GROUP
+#endif
+#if (_CG_CUDA_ARCH >= 600) || !defined(_CG_CUDA_ARCH)
+# define _CG_HAS_MULTI_GRID_GROUP
+#endif
+#if (_CG_CUDA_ARCH >= 700) || !defined(_CG_CUDA_ARCH)
+# define _CG_HAS_MATCH_COLLECTIVE
+#endif
+
+#if ((_CG_CUDA_ARCH >= 800) || !defined(_CG_CUDA_ARCH)) && !defined(_CG_USER_PROVIDED_SHARED_MEMORY)
+# define _CG_HAS_RESERVED_SHARED
+#endif
+
+#if ((_CG_CUDA_ARCH >= 900) || !defined(_CG_CUDA_ARCH)) && \
+    (defined(__NVCC__) || defined(__CUDACC_RTC__) || defined(_CG_CLUSTER_INTRINSICS_AVAILABLE)) && \
+    defined(_CG_CPP11_FEATURES)
+# define _CG_HAS_CLUSTER_GROUP
+#endif
+
+#if (_CG_CUDA_ARCH >= 900) || !defined(_CG_CUDA_ARCH)
+# define _CG_HAS_INSTR_ELECT
+#endif
+
+// Has __half and __half2
+// Only usable if you include the cuda_fp16.h extension, and
+// _before_ including cooperative_groups.h
+#ifdef __CUDA_FP16_TYPES_EXIST__
+# define _CG_HAS_FP16_COLLECTIVE
+#endif
+
+// Include libcu++ where supported.
+#if defined(_CG_CPP11_FEATURES) && !defined(__ibmxl__) && (!defined(_MSC_VER) || defined(_WIN64)) && \
+    !defined(_CG_LIMIT_INCLUDED_DEPENDENCIES)
+# define _CG_USE_CUDA_STL
+#else
+# define _CG_USE_OWN_TRAITS
+#endif
+
+#if defined(_CG_USE_CUDA_STL) && !defined(__QNX__) && (!defined(__CUDA_ARCH__) || \
+    ((!defined(_MSC_VER) && __CUDA_ARCH__ >= 600) || (defined(_MSC_VER) && __CUDA_ARCH__ >= 700)))
+# define _CG_HAS_STL_ATOMICS
+#endif
+
+#ifdef _CG_CPP11_FEATURES
+// Use cuda::std:: for type_traits
+# if defined(_CG_USE_CUDA_STL)
+#  define _CG_STL_NAMESPACE cuda::std
+#  include 
+// Use CG's implementation of type traits
+# else
+#  define _CG_STL_NAMESPACE cooperative_groups::details::templates
+# endif
+#endif
+
+#ifdef _CG_CPP11_FEATURES
+# define _CG_STATIC_CONST_DECL static constexpr
+# define _CG_CONST_DECL constexpr
+#else
+# define _CG_STATIC_CONST_DECL static const
+# define _CG_CONST_DECL const
+#endif
+
+#if (defined(_MSC_VER) && !defined(_WIN64)) || defined(__arm__)
+# define _CG_ASM_PTR_CONSTRAINT "r"
+#else
+#  define _CG_ASM_PTR_CONSTRAINT "l"
+#endif
+
+/*
+** Define: CG_DEBUG
+** What: Enables various runtime safety checks
+*/
+#if defined(__CUDACC_DEBUG__) && defined(CG_DEBUG) && !defined(NDEBUG)
+# define _CG_DEBUG
+#endif
+
+#if defined(_CG_DEBUG)
+# include 
+# define _CG_ASSERT(x) assert((x));
+# define _CG_ABORT() assert(0);
+#else
+# define _CG_ASSERT(x)
+# define _CG_ABORT() __trap();
+#endif
+
+_CG_BEGIN_NAMESPACE
+
+namespace details {
+    _CG_STATIC_CONST_DECL unsigned int default_max_block_size = 1024;
+
+#if defined(_CG_CPP11_FEATURES) && !defined(_CG_USE_CUDA_STL)
+namespace templates {
+
+/**
+ * Integral constants
+ **/
+template 
+struct integral_constant {
+    static constexpr Ty value = Val;
+    typedef Ty type;
+
+    _CG_QUALIFIER constexpr operator type() const noexcept { return value; }
+    _CG_QUALIFIER constexpr type operator()() const noexcept { return value; }
+};
+
+typedef integral_constant  true_type;
+typedef integral_constant false_type;
+
+/**
+ * CV Qualifiers
+ **/
+template  struct is_lvalue_reference       : public details::templates::false_type {};
+template  struct is_lvalue_reference  : public details::templates::true_type {};
+
+template  struct remove_reference       {typedef Ty type;};
+template  struct remove_reference  {typedef Ty type;};
+template  struct remove_reference {typedef Ty type;};
+
+template 
+using remove_reference_t = typename details::templates::remove_reference::type;
+
+template  struct remove_const           {typedef Ty type;};
+template  struct remove_const {typedef Ty type;};
+
+template  struct remove_volatile              {typedef Ty type;};
+template  struct remove_volatile {typedef Ty type;};
+
+template  struct remove_cv {typedef typename details::templates::remove_volatile::type>::type type;};
+
+template 
+using remove_cv_t = typename details::templates::remove_cv::type;
+
+template 
+_CG_QUALIFIER Ty&& forward(remove_reference_t &t) noexcept {
+    return static_cast(t);
+}
+
+template 
+_CG_QUALIFIER Ty&& forward(remove_reference_t &&t) noexcept {
+    static_assert(!details::templates::is_lvalue_reference::value, "Forwarding an rvalue as an lvalue is not allowed.");
+    return static_cast(t);
+}
+
+/**
+ * is_integral
+ **/
+template  struct _is_integral                     : public details::templates::false_type {};
+template <>         struct _is_integral               : public details::templates::true_type {};
+template <>         struct _is_integral               : public details::templates::true_type {};
+template <>         struct _is_integral      : public details::templates::true_type {};
+template <>         struct _is_integral              : public details::templates::true_type {};
+template <>         struct _is_integral     : public details::templates::true_type {};
+template <>         struct _is_integral                : public details::templates::true_type {};
+template <>         struct _is_integral       : public details::templates::true_type {};
+template <>         struct _is_integral               : public details::templates::true_type {};
+template <>         struct _is_integral          : public details::templates::true_type {};
+template <>         struct _is_integral      : public details::templates::true_type {};
+template <>         struct _is_integral : public details::templates::true_type {};
+//Vector type support?
+
+template 
+struct is_integral : public details::templates::_is_integral::type> {};
+
+/**
+ * is_floating_point
+ **/
+template  struct _is_floating_point              : public details::templates::false_type {};
+template <>         struct _is_floating_point       : public details::templates::true_type {};
+template <>         struct _is_floating_point      : public details::templates::true_type {};
+template <>         struct _is_floating_point : public details::templates::true_type {};
+# ifdef __CUDA_FP16_TYPES_EXIST__
+template <>         struct _is_floating_point<__half>      : public details::templates::true_type {};
+template <>         struct _is_floating_point<__half2>     : public details::templates::true_type {};
+# endif
+//Vector type support?
+
+template 
+struct is_floating_point : public details::templates::_is_floating_point::type> {};
+
+template 
+struct is_arithmetic : details::templates::integral_constant<
+    bool,
+    details::templates::is_integral::value ||
+    details::templates::is_floating_point::value> {};
+
+template ::value>
+struct _is_unsigned : details::templates::integral_constant {};
+
+template 
+struct _is_unsigned : details::templates::false_type {};
+
+template 
+struct is_unsigned : _is_unsigned::type> {};
+
+template  struct _is_pointer      : public details::templates::false_type {};
+template  struct _is_pointer : public details::templates::true_type {};
+
+template 
+struct is_pointer : _is_pointer::type> {};
+
+/**
+ * programmatic type traits
+ **/
+template
+struct enable_if {};
+
+template
+struct enable_if { typedef Ty type; };
+
+template
+using enable_if_t = typename details::templates::enable_if::type;
+
+template
+struct is_same : details::templates::false_type {};
+
+template
+struct is_same : details::templates::true_type {};
+
+} // templates
+#endif // _CG_CPP11_FEATURES
+
+} // details
+_CG_END_NAMESPACE
+
+
+#endif // _CG_INFO_H_
diff --git a/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/invoke.h b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/invoke.h
new file mode 100644
index 0000000000000000000000000000000000000000..f00314ce140e390be90a1ab3c328fd73d73c0d46
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/invoke.h
@@ -0,0 +1,189 @@
+/*
+ * Copyright 1993-2022 NVIDIA Corporation.  All rights reserved.
+ *
+ * NOTICE TO LICENSEE:
+ *
+ * This source code and/or documentation ("Licensed Deliverables") are
+ * subject to NVIDIA intellectual property rights under U.S. and
+ * international Copyright laws.
+ *
+ * These Licensed Deliverables contained herein is PROPRIETARY and
+ * CONFIDENTIAL to NVIDIA and is being provided under the terms and
+ * conditions of a form of NVIDIA software license agreement by and
+ * between NVIDIA and Licensee ("License Agreement") or electronically
+ * accepted by Licensee.  Notwithstanding any terms or conditions to
+ * the contrary in the License Agreement, reproduction or disclosure
+ * of the Licensed Deliverables to any third party without the express
+ * written consent of NVIDIA is prohibited.
+ *
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+ * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
+ * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE.  IT IS
+ * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
+ * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
+ * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
+ * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+ * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
+ * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * OF THESE LICENSED DELIVERABLES.
+ *
+ * U.S. Government End Users.  These Licensed Deliverables are a
+ * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
+ * 1995), consisting of "commercial computer software" and "commercial
+ * computer software documentation" as such terms are used in 48
+ * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
+ * only as a commercial end item.  Consistent with 48 C.F.R.12.212 and
+ * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
+ * U.S. Government End Users acquire the Licensed Deliverables with
+ * only those rights set forth herein.
+ *
+ * Any use of the Licensed Deliverables in individual and commercial
+ * software must include, in the user documentation and internal
+ * comments to the code, the above Disclaimer and U.S. Government End
+ * Users Notice.
+ */
+
+#ifndef _CG_INVOKE_H
+#define _CG_INVOKE_H
+
+#include "info.h"
+#include "helpers.h"
+
+#if defined(_CG_CPP11_FEATURES)
+
+_CG_BEGIN_NAMESPACE
+
+namespace details {
+
+    template 
+    struct _elect_group_supported : _CG_STL_NAMESPACE::false_type {};
+#ifdef _CG_HAS_INSTR_ELECT
+    template<>
+    struct _elect_group_supported : _CG_STL_NAMESPACE::true_type {};
+    template
+    struct _elect_group_supported> :
+        _CG_STL_NAMESPACE::integral_constant {};
+#endif
+
+    template 
+    struct elect_group_supported : public _elect_group_supported> {};
+
+    template
+    _CG_STATIC_QUALIFIER bool elect_one(const Group& group, unsigned int mask, unsigned int& leader_lane) {
+        int is_leader = 0;
+#ifdef _CG_HAS_INSTR_ELECT
+        asm("{\n\t"
+          " .reg .pred p;\n\t"
+          "  elect.sync %0|p, %2;\n\t"
+          " @p mov.s32 %1, 1;\n\t"
+          "}"
+          : "+r"(leader_lane), "+r"(is_leader) : "r" (mask));
+#endif
+        return is_leader;
+    }
+
+    template
+    struct invoke_one_impl {};
+
+    template<>
+    struct invoke_one_impl {
+        template
+        _CG_STATIC_QUALIFIER void invoke_one(const Group& group, Fn&& fn, Args&&... args) {
+            auto mask = details::_coalesced_group_data_access::get_mask(group);
+            unsigned int leader_lane = 0;
+
+            if (elect_one(group, mask, leader_lane)) {
+                _CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...);
+            }
+        }
+
+        template
+        _CG_STATIC_QUALIFIER auto invoke_one_broadcast(const Group& group, Fn&& fn, Args&&... args)
+                -> typename _CG_STL_NAMESPACE::remove_reference<
+                    decltype(_CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...))>::type {
+
+            using ResultType = decltype(_CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...));
+            details::remove_qual result;
+            auto mask = details::_coalesced_group_data_access::get_mask(group);
+            unsigned int leader_lane = 0;
+
+            if (elect_one(group, mask, leader_lane)) {
+                result = _CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...);
+            }
+
+            // Need to use low level api instead of group.shfl, because elect_one returns lane id, not group rank.
+            return tile::shuffle_dispatch::shfl(result, mask, leader_lane, 32);
+        }
+    };
+
+    template<>
+    struct invoke_one_impl {
+        template
+        _CG_STATIC_QUALIFIER void invoke_one(const Group& group, Fn&& fn, Args&&... args) {
+            if (group.thread_rank() == 0) {
+                _CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...);
+            }
+        }
+
+        template
+        _CG_STATIC_QUALIFIER auto invoke_one_broadcast(const Group& group, Fn&& fn, Args&&... args)
+                -> typename _CG_STL_NAMESPACE::remove_reference<
+                    decltype(_CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...))>::type {
+
+            using ResultType = decltype(_CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...));
+            details::remove_qual result;
+
+            if (group.thread_rank() == 0) {
+                result = _CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...);
+            }
+
+            return group.shfl(result, 0);
+        }
+    };
+
+
+}; // namespace details
+
+template
+_CG_QUALIFIER void invoke_one(const Group& group, Fn&& fn, Args&&... args) {
+    using impl = details::invoke_one_impl::value>;
+    impl::invoke_one(group, _CG_STL_NAMESPACE::forward(fn), _CG_STL_NAMESPACE::forward(args)...);
+}
+
+template
+_CG_QUALIFIER auto invoke_one_broadcast(const coalesced_group& group, Fn&& fn, Args&&... args)
+        -> typename _CG_STL_NAMESPACE::remove_reference<
+            decltype(_CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...))>::type {
+
+    using ResultType = decltype(_CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...));
+    static_assert(!_CG_STL_NAMESPACE::is_same::value,
+                  "For invocables returning void invoke_one should be used instead");
+    using impl = details::invoke_one_impl::value>;
+    return impl::invoke_one_broadcast(group,
+                                      _CG_STL_NAMESPACE::forward(fn),
+                                      _CG_STL_NAMESPACE::forward(args)...);
+}
+
+template
+_CG_QUALIFIER auto invoke_one_broadcast(const thread_block_tile& group, Fn&& fn, Args&&... args)
+        -> typename _CG_STL_NAMESPACE::remove_reference<
+            decltype(_CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...))>::type {
+
+    using ResultType = decltype(_CG_STL_NAMESPACE::forward(fn)(_CG_STL_NAMESPACE::forward(args)...));
+    static_assert(!_CG_STL_NAMESPACE::is_same::value,
+                  "For invocables returning void invoke_one should be used instead");
+    using impl = details::invoke_one_impl>::value>;
+    return impl::invoke_one_broadcast(group,
+                                      _CG_STL_NAMESPACE::forward(fn),
+                                      _CG_STL_NAMESPACE::forward(args)...);
+}
+
+_CG_END_NAMESPACE
+
+#endif //_CG_CPP11_FEATURES
+
+#endif // _CG_INVOKE_H
diff --git a/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/memory.h b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/memory.h
new file mode 100644
index 0000000000000000000000000000000000000000..25fdc7646932889a4992b8d3a6249a610c76709a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/memory.h
@@ -0,0 +1,136 @@
+/* Copyright 1993-2022 NVIDIA Corporation.  All rights reserved.
+  *
+  * NOTICE TO LICENSEE:
+  *
+  * The source code and/or documentation ("Licensed Deliverables") are
+  * subject to NVIDIA intellectual property rights under U.S. and
+  * international Copyright laws.
+  *
+  * The Licensed Deliverables contained herein are PROPRIETARY and
+  * CONFIDENTIAL to NVIDIA and are being provided under the terms and
+  * conditions of a form of NVIDIA software license agreement by and
+  * between NVIDIA and Licensee ("License Agreement") or electronically
+  * accepted by Licensee.  Notwithstanding any terms or conditions to
+  * the contrary in the License Agreement, reproduction or disclosure
+  * of the Licensed Deliverables to any third party without the express
+  * written consent of NVIDIA is prohibited.
+  *
+  * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+  * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
+  * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE.  THEY ARE
+  * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
+  * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
+  * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
+  * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
+  * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+  * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
+  * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
+  * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+  * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+  * OF THESE LICENSED DELIVERABLES.
+  *
+  * U.S. Government End Users.  These Licensed Deliverables are a
+  * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
+  * 1995), consisting of "commercial computer software" and "commercial
+  * computer software documentation" as such terms are used in 48
+  * C.F.R. 12.212 (SEPT 1995) and are provided to the U.S. Government
+  * only as a commercial end item.  Consistent with 48 C.F.R.12.212 and
+  * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
+  * U.S. Government End Users acquire the Licensed Deliverables with
+  * only those rights set forth herein.
+  *
+  * Any use of the Licensed Deliverables in individual and commercial
+  * software must include, in the user documentation and internal
+  * comments to the code, the above Disclaimer and U.S. Government End
+  * Users Notice.
+  */
+
+#ifndef _COOPERATIVE_GROUPS_MEMORY_H_
+# define _COOPERATIVE_GROUPS_MEMORY_H_
+
+#include "info.h"
+
+_CG_BEGIN_NAMESPACE
+
+#if defined(_CG_CPP11_FEATURES)
+namespace details {
+    _CG_STATIC_CONST_DECL int scratch_num_reserved_bytes = 12;
+
+    // Should only be called for SM80+
+    _CG_STATIC_QUALIFIER void* reserved_shared_ptr()
+    {
+        unsigned long long ptr = 0;
+        NV_IF_TARGET(NV_PROVIDES_SM_80,
+        (asm ("{\n\t"
+             " .reg .u32 start;\n\t"
+             " .reg .u64 extended;\n\t"
+             " mov.u32 start, %%reserved_smem_offset_1;\n\t"
+             " cvt.u64.u32 extended, start;\n\t"
+             " cvta.shared.u64 %0, extended;\n\t"
+             "}"
+             : "=l"(ptr));)
+        )
+        return reinterpret_cast(ptr);
+    }
+
+    struct multi_warp_scratch {
+        // One barrier per possible size of the group.
+        _CG_STATIC_CONST_DECL unsigned int memory_barriers_count = 5;
+        _CG_STATIC_CONST_DECL size_t sync_memory_size = memory_barriers_count * sizeof(barrier_t);
+
+        using communication_type = unsigned long long;
+        _CG_STATIC_CONST_DECL size_t communication_size = sizeof(communication_type);
+
+        // Layout of the scratch space:
+        barrier_t barriers[memory_barriers_count];
+        char reserved[scratch_num_reserved_bytes]; // Reserve 12 bytes for future use
+        communication_type communication_memory[default_max_block_size / 32];
+
+        _CG_STATIC_CONSTEXPR_QUALIFIER unsigned int scratch_size_needed(unsigned int max_block_size) {
+            // One slot of collectives memory per warp.
+            return scratch_num_reserved_bytes + (unsigned int)sync_memory_size + max_block_size / 32 * (unsigned int)communication_size;
+        }
+
+        _CG_QUALIFIER void init_barriers(unsigned int thread_rank) {
+            if (thread_rank < memory_barriers_count) {
+                barriers[thread_rank] = 0;
+            }
+        }
+    };
+
+#if defined(_CG_HAS_RESERVED_SHARED)
+    // CG can expect at least 288 bytes available in reserved shared
+    static_assert(sizeof(multi_warp_scratch) <= 288, "multi-warp scratch size is too large");
+#endif
+
+    // Make sure the structure can fit into the user provided memory
+    static_assert(sizeof(multi_warp_scratch) <= multi_warp_scratch::scratch_size_needed(default_max_block_size),
+                  "multi-warp scratch size is too large");
+
+
+    _CG_QUALIFIER multi_warp_scratch* get_scratch_ptr(void* user_scratch) {
+        void *ptr;
+        NV_IF_ELSE_TARGET(NV_PROVIDES_SM_80,
+            (ptr = reserved_shared_ptr();)
+        ,
+            (ptr = user_scratch;)
+        )
+        return static_cast(ptr);
+
+    }
+
+}
+
+template 
+struct __align__(details::multi_warp_scratch::communication_size) block_tile_memory {
+private:
+#if !defined(_CG_HAS_RESERVED_SHARED)
+    char scratch[details::multi_warp_scratch::scratch_size_needed(MaxBlockSize)];
+#endif
+};
+#endif
+
+_CG_END_NAMESPACE
+
+#endif /* !_COOPERATIVE_GROUPS_MEMORY_H_ */
diff --git a/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/partitioning.h b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/partitioning.h
new file mode 100644
index 0000000000000000000000000000000000000000..fe66fb926876c045b49a2c8f0b83379dae7599fa
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/partitioning.h
@@ -0,0 +1,160 @@
+/*
+ * Copyright 1993-2016 NVIDIA Corporation.  All rights reserved.
+ *
+ * NOTICE TO LICENSEE:
+ *
+ * This source code and/or documentation ("Licensed Deliverables") are
+ * subject to NVIDIA intellectual property rights under U.S. and
+ * international Copyright laws.
+ *
+ * These Licensed Deliverables contained herein is PROPRIETARY and
+ * CONFIDENTIAL to NVIDIA and is being provided under the terms and
+ * conditions of a form of NVIDIA software license agreement by and
+ * between NVIDIA and Licensee ("License Agreement") or electronically
+ * accepted by Licensee.  Notwithstanding any terms or conditions to
+ * the contrary in the License Agreement, reproduction or disclosure
+ * of the Licensed Deliverables to any third party without the express
+ * written consent of NVIDIA is prohibited.
+ *
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+ * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
+ * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE.  IT IS
+ * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
+ * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
+ * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
+ * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+ * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
+ * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+ * OF THESE LICENSED DELIVERABLES.
+ *
+ * U.S. Government End Users.  These Licensed Deliverables are a
+ * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
+ * 1995), consisting of "commercial computer software" and "commercial
+ * computer software documentation" as such terms are used in 48
+ * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
+ * only as a commercial end item.  Consistent with 48 C.F.R.12.212 and
+ * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
+ * U.S. Government End Users acquire the Licensed Deliverables with
+ * only those rights set forth herein.
+ *
+ * Any use of the Licensed Deliverables in individual and commercial
+ * software must include, in the user documentation and internal
+ * comments to the code, the above Disclaimer and U.S. Government End
+ * Users Notice.
+ */
+
+#ifndef _CG_PARTITIONING_H
+#define _CG_PARTITIONING_H
+
+#include "info.h"
+#include "helpers.h"
+
+_CG_BEGIN_NAMESPACE
+
+namespace details {
+
+    template 
+    _CG_STATIC_QUALIFIER coalesced_group _binary_partition(const TyGroup &tile, bool pred) {
+        const unsigned int fullMask = ~0u;
+
+        unsigned int thisMask = _coalesced_group_data_access::get_mask(tile);
+        unsigned int predMask = pred ? 0 : fullMask;
+        unsigned int setMask = __ballot_sync(thisMask, pred);
+
+        if (setMask == thisMask || setMask == 0) {
+            coalesced_group subTile = _coalesced_group_data_access::construct_from_mask(thisMask);
+            _coalesced_group_data_access::modify_meta_group(subTile, 0, 1);
+            return subTile;
+        }
+        else {
+            unsigned int subMask = thisMask & (setMask ^ predMask);
+            coalesced_group subTile = _coalesced_group_data_access::construct_from_mask(subMask);
+            _coalesced_group_data_access::modify_meta_group(subTile, pred, 2);
+            return subTile;
+        }
+    }
+
+#if defined(_CG_HAS_MATCH_COLLECTIVE) && defined(_CG_CPP11_FEATURES)
+    template 
+    struct _labeled_partition_dispatch {
+        template 
+        _CG_QUALIFIER coalesced_group operator()(const TyGroup &tile, TyPredicate pred) {
+            unsigned int thisMask = _coalesced_group_data_access::get_mask(tile);
+            unsigned int subMask  = __match_any_sync(thisMask, pred);
+            unsigned int laneId   = details::laneid();
+
+            coalesced_group subTile = _coalesced_group_data_access::construct_from_mask(subMask);
+
+            int leaderLaneId = __ffs(subMask) - 1;
+            bool isLeader = leaderLaneId == laneId;
+            unsigned int leaderMask = __ballot_sync(thisMask, isLeader);
+
+            // Count leaders with lower laneid, that will be the meta rank of this tile
+            unsigned int tileRank = __popc(leaderMask & ((1 << leaderLaneId) - 1));
+
+            _coalesced_group_data_access::modify_meta_group(subTile, tileRank, __popc(leaderMask));
+
+            return subTile;
+        }
+    };
+
+    template <>
+    struct _labeled_partition_dispatch {
+        template 
+        _CG_QUALIFIER coalesced_group operator()(const TyGroup &tile, bool pred) {
+            return _binary_partition(tile, pred);
+        }
+    };
+
+    template 
+    struct _labeled_partition_dispatch {
+        template 
+        _CG_QUALIFIER coalesced_group operator()(const TyGroup &tile, TyPredicate* pred) {
+            auto impl = _labeled_partition_dispatch();
+            return impl(tile, reinterpret_cast(pred));
+        }
+    };
+#endif
+}; // namespace details
+
+_CG_STATIC_QUALIFIER coalesced_group binary_partition(const coalesced_group &tile, bool pred) {
+    return details::_binary_partition(tile, pred);
+}
+
+template 
+_CG_STATIC_QUALIFIER coalesced_group binary_partition(const thread_block_tile &tile, bool pred) {
+#ifdef _CG_CPP11_FEATURES
+    static_assert(Size <= 32, "Binary partition is available only for tiles of size smaller or equal to 32");
+#endif
+    return details::_binary_partition(tile, pred);
+}
+
+
+#if defined(_CG_HAS_MATCH_COLLECTIVE) && defined(_CG_CPP11_FEATURES)
+template 
+_CG_STATIC_QUALIFIER coalesced_group labeled_partition(const coalesced_group &tile, TyPredicate pred) {
+    static_assert(_CG_STL_NAMESPACE::is_integral::value ||
+                  _CG_STL_NAMESPACE::is_pointer::value,
+                  "labeled_partition predicate must be an integral or pointer type");
+    auto dispatch = details::_labeled_partition_dispatch>();
+    return dispatch(tile, pred);
+}
+
+template 
+_CG_STATIC_QUALIFIER coalesced_group labeled_partition(const thread_block_tile &tile, TyPredicate pred) {
+    static_assert(_CG_STL_NAMESPACE::is_integral::value ||
+                  _CG_STL_NAMESPACE::is_pointer::value,
+                  "labeled_partition predicate must be an integral or pointer type");
+    static_assert(Size <= 32, "Labeled partition is available only for tiles of size smaller or equal to 32");
+    auto dispatch = details::_labeled_partition_dispatch>();
+    return dispatch(tile, pred);
+}
+#endif
+
+_CG_END_NAMESPACE
+
+#endif // _CG_PARTITIONING_H
diff --git a/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/reduce.h b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/reduce.h
new file mode 100644
index 0000000000000000000000000000000000000000..b89d7fbaf340c1febd6c8a7de13f346daa1a1371
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/triton/backends/nvidia/include/cooperative_groups/details/reduce.h
@@ -0,0 +1,424 @@
+ /* Copyright 1993-2016 NVIDIA Corporation.  All rights reserved.
+  *
+  * NOTICE TO LICENSEE:
+  *
+  * The source code and/or documentation ("Licensed Deliverables") are
+  * subject to NVIDIA intellectual property rights under U.S. and
+  * international Copyright laws.
+  *
+  * The Licensed Deliverables contained herein are PROPRIETARY and
+  * CONFIDENTIAL to NVIDIA and are being provided under the terms and
+  * conditions of a form of NVIDIA software license agreement by and
+  * between NVIDIA and Licensee ("License Agreement") or electronically
+  * accepted by Licensee.  Notwithstanding any terms or conditions to
+  * the contrary in the License Agreement, reproduction or disclosure
+  * of the Licensed Deliverables to any third party without the express
+  * written consent of NVIDIA is prohibited.
+  *
+  * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+  * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
+  * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE.  THEY ARE
+  * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
+  * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
+  * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
+  * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
+  * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
+  * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
+  * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
+  * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+  * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
+  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+  * OF THESE LICENSED DELIVERABLES.
+  *
+  * U.S. Government End Users.  These Licensed Deliverables are a
+  * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
+  * 1995), consisting of "commercial computer software" and "commercial
+  * computer software documentation" as such terms are used in 48
+  * C.F.R. 12.212 (SEPT 1995) and are provided to the U.S. Government
+  * only as a commercial end item.  Consistent with 48 C.F.R.12.212 and
+  * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
+  * U.S. Government End Users acquire the Licensed Deliverables with
+  * only those rights set forth herein.
+  *
+  * Any use of the Licensed Deliverables in individual and commercial
+  * software must include, in the user documentation and internal
+  * comments to the code, the above Disclaimer and U.S. Government End
+  * Users Notice.
+  */
+
+#ifndef _CG_REDUCE_H_
+#define _CG_REDUCE_H_
+
+#include "info.h"
+#include "helpers.h"
+#include "coalesced_reduce.h"
+#include "functional.h"
+#include "cooperative_groups.h"
+
+_CG_BEGIN_NAMESPACE
+
+namespace details {
+
+    template 
+    using _redux_is_add_supported = _CG_STL_NAMESPACE::integral_constant<
+            bool,
+            _CG_STL_NAMESPACE::is_integral::value && (sizeof(Ty) <= 4)>;
+
+    template 
+    using redux_is_add_supported = _redux_is_add_supported;
+
+    // A specialization for 64 bit logical operations is possible
+    // but for now only accelerate 32 bit bitwise ops
+    template 
+    using redux_is_logical_supported = redux_is_add_supported;
+
+    // Base operator support case
+    template  struct _redux_op_supported                 : public _CG_STL_NAMESPACE::false_type {};
+    template  struct _redux_op_supported,    Ty> : public redux_is_add_supported {};
+    template  struct _redux_op_supported,    Ty> : public redux_is_add_supported {};
+    template  struct _redux_op_supported, Ty> : public redux_is_add_supported {};
+    template  struct _redux_op_supported, Ty> : public redux_is_logical_supported {};
+    template  struct _redux_op_supported,  Ty> : public redux_is_logical_supported {};
+    template  struct _redux_op_supported, Ty> : public redux_is_logical_supported {};
+
+    template  class TyOp>
+    using redux_op_supported = _redux_op_supported<
+            typename details::remove_qual>,
+            Ty>;
+
+    // Groups smaller than 16 actually have worse performance characteristics when used with redux
+    // tiles of size 16 and 32 perform the same or better and have better code generation profiles
+    template  struct _redux_group_optimized : public _CG_STL_NAMESPACE::false_type {};
+
+    template 
+    struct _redux_group_optimized> : public _CG_STL_NAMESPACE::integral_constant<
+                                                                                            bool,
+                                                                                            (Sz >= 16)> {};
+    template 
+    struct _redux_group_optimized>            : public _CG_STL_NAMESPACE::integral_constant<
+                                                                                            bool,
+                                                                                            (Sz >= 16)> {};
+    template <>
+    struct _redux_group_optimized              : public _CG_STL_NAMESPACE::true_type  {};
+
+    template 
+    using redux_group_optimized = _redux_group_optimized>;
+
+    template