diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/absl_py-2.4.0.dist-info/licenses/AUTHORS b/data/conda_envs/evalclaw/lib/python3.11/site-packages/absl_py-2.4.0.dist-info/licenses/AUTHORS
new file mode 100644
index 0000000000000000000000000000000000000000..23b11ada16bb8e69695cf52e5994784d98054e0d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/absl_py-2.4.0.dist-info/licenses/AUTHORS
@@ -0,0 +1,7 @@
+# This is the list of Abseil authors for copyright purposes.
+#
+# This does not necessarily list everyone who has contributed code, since in
+# some cases, their employer may be the copyright holder. To see the full list
+# of contributors, see the revision history in source control.
+
+Google Inc.
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/absl_py-2.4.0.dist-info/licenses/LICENSE b/data/conda_envs/evalclaw/lib/python3.11/site-packages/absl_py-2.4.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/absl_py-2.4.0.dist-info/licenses/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/aiohttp-3.13.3.dist-info/licenses/LICENSE.txt b/data/conda_envs/evalclaw/lib/python3.11/site-packages/aiohttp-3.13.3.dist-info/licenses/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..e497a322f2091d022983b9c5c043082ab61d1a8c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/aiohttp-3.13.3.dist-info/licenses/LICENSE.txt
@@ -0,0 +1,13 @@
+ Copyright aio-libs contributors.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/aiohttp-3.13.3.dist-info/licenses/vendor/llhttp/LICENSE b/data/conda_envs/evalclaw/lib/python3.11/site-packages/aiohttp-3.13.3.dist-info/licenses/vendor/llhttp/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..6c1512dd6bcd6de314673f8c2c7ff3fd6139f28e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/aiohttp-3.13.3.dist-info/licenses/vendor/llhttp/LICENSE
@@ -0,0 +1,22 @@
+This software is licensed under the MIT License.
+
+Copyright Fedor Indutny, 2018.
+
+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/data/conda_envs/evalclaw/lib/python3.11/site-packages/annotated_doc-0.0.4.dist-info/licenses/LICENSE b/data/conda_envs/evalclaw/lib/python3.11/site-packages/annotated_doc-0.0.4.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..7a254464cc78ccea32b3ded00513c44c4e4da412
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/annotated_doc-0.0.4.dist-info/licenses/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2025 Sebastián RamÃrez
+
+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/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0ba4d699d3f33814887253e1b20b732b7ad97549
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/_deprecation.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/_deprecation.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..84f3e1f8cdf280195baf469315b3c0cee41bf545
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/_deprecation.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/_typing.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/_typing.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8fa5b40d49f44092c52848d0a6639ee4d7150fa8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/_typing.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/_warnings.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/_warnings.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fe8f8b94be4c71f78c0b65d7b0eb580b191c72b5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/_warnings.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/css.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/css.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fb8f38f35665c5282627099b4f09dfc1b6a8b5e4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/css.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/dammit.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/dammit.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eee57a520efc67b2f7106a9f15010d3a0d8b43d7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/dammit.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/diagnose.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/diagnose.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f06acf25e2e9dd51fece0a1fb1a292dc427b05f4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/diagnose.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/exceptions.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/exceptions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..18fc016471eff41f17d485fa286df2d4708f907e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/exceptions.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/filter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/filter.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e4d6ae49692a3c48d0be08183ff3d0dd5d98e50c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/filter.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/formatter.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/formatter.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..42291f7fda78e32caf5b6dee16223105533ba637
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/__pycache__/formatter.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4aae4d330789cf01057918d25eea372f739d6e56
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/__init__.py
@@ -0,0 +1,848 @@
+from __future__ import annotations
+
+# Use of this source code is governed by the MIT license.
+__license__ = "MIT"
+
+from collections import defaultdict
+import re
+from types import ModuleType
+from typing import (
+ Any,
+ cast,
+ Dict,
+ Iterable,
+ List,
+ Optional,
+ Pattern,
+ Set,
+ Tuple,
+ Type,
+ TYPE_CHECKING,
+)
+import warnings
+import sys
+from bs4.element import (
+ AttributeDict,
+ AttributeValueList,
+ CharsetMetaAttributeValue,
+ ContentMetaAttributeValue,
+ RubyParenthesisString,
+ RubyTextString,
+ Stylesheet,
+ Script,
+ TemplateString,
+ nonwhitespace_re,
+)
+
+# Exceptions were moved to their own module in 4.13. Import here for
+# backwards compatibility.
+from bs4.exceptions import ParserRejectedMarkup
+
+from bs4._typing import (
+ _AttributeValues,
+ _RawAttributeValue,
+)
+
+from bs4._warnings import XMLParsedAsHTMLWarning
+
+if TYPE_CHECKING:
+ from bs4 import BeautifulSoup
+ from bs4.element import (
+ NavigableString,
+ Tag,
+ )
+ from bs4._typing import (
+ _AttributeValue,
+ _Encoding,
+ _Encodings,
+ _RawOrProcessedAttributeValues,
+ _RawMarkup,
+ )
+
+__all__ = [
+ "HTMLTreeBuilder",
+ "SAXTreeBuilder",
+ "TreeBuilder",
+ "TreeBuilderRegistry",
+]
+
+# Some useful features for a TreeBuilder to have.
+FAST = "fast"
+PERMISSIVE = "permissive"
+STRICT = "strict"
+XML = "xml"
+HTML = "html"
+HTML_5 = "html5"
+
+__all__ = [
+ "TreeBuilderRegistry",
+ "TreeBuilder",
+ "HTMLTreeBuilder",
+ "DetectsXMLParsedAsHTML",
+
+ "ParserRejectedMarkup", # backwards compatibility only as of 4.13.0
+]
+
+class TreeBuilderRegistry(object):
+ """A way of looking up TreeBuilder subclasses by their name or by desired
+ features.
+ """
+
+ builders_for_feature: Dict[str, List[Type[TreeBuilder]]]
+ builders: List[Type[TreeBuilder]]
+
+ def __init__(self) -> None:
+ self.builders_for_feature = defaultdict(list)
+ self.builders = []
+
+ def register(self, treebuilder_class: type[TreeBuilder]) -> None:
+ """Register a treebuilder based on its advertised features.
+
+ :param treebuilder_class: A subclass of `TreeBuilder`. its
+ `TreeBuilder.features` attribute should list its features.
+ """
+ for feature in treebuilder_class.features:
+ self.builders_for_feature[feature].insert(0, treebuilder_class)
+ self.builders.insert(0, treebuilder_class)
+
+ def lookup(self, *features: str) -> Optional[Type[TreeBuilder]]:
+ """Look up a TreeBuilder subclass with the desired features.
+
+ :param features: A list of features to look for. If none are
+ provided, the most recently registered TreeBuilder subclass
+ will be used.
+ :return: A TreeBuilder subclass, or None if there's no
+ registered subclass with all the requested features.
+ """
+ if len(self.builders) == 0:
+ # There are no builders at all.
+ return None
+
+ if len(features) == 0:
+ # They didn't ask for any features. Give them the most
+ # recently registered builder.
+ return self.builders[0]
+
+ # Go down the list of features in order, and eliminate any builders
+ # that don't match every feature.
+ feature_list = list(features)
+ feature_list.reverse()
+ candidates = None
+ candidate_set = None
+ while len(feature_list) > 0:
+ feature = feature_list.pop()
+ we_have_the_feature = self.builders_for_feature.get(feature, [])
+ if len(we_have_the_feature) > 0:
+ if candidates is None:
+ candidates = we_have_the_feature
+ candidate_set = set(candidates)
+ elif candidate_set is not None:
+ # Eliminate any candidates that don't have this feature.
+ candidate_set = candidate_set.intersection(set(we_have_the_feature))
+
+ # The only valid candidates are the ones in candidate_set.
+ # Go through the original list of candidates and pick the first one
+ # that's in candidate_set.
+ if candidate_set is None or candidates is None:
+ return None
+ for candidate in candidates:
+ if candidate in candidate_set:
+ return candidate
+ return None
+
+
+#: The `BeautifulSoup` constructor will take a list of features
+#: and use it to look up `TreeBuilder` classes in this registry.
+builder_registry: TreeBuilderRegistry = TreeBuilderRegistry()
+
+
+class TreeBuilder(object):
+ """Turn a textual document into a Beautiful Soup object tree.
+
+ This is an abstract superclass which smooths out the behavior of
+ different parser libraries into a single, unified interface.
+
+ :param multi_valued_attributes: If this is set to None, the
+ TreeBuilder will not turn any values for attributes like
+ 'class' into lists. Setting this to a dictionary will
+ customize this behavior; look at :py:attr:`bs4.builder.HTMLTreeBuilder.DEFAULT_CDATA_LIST_ATTRIBUTES`
+ for an example.
+
+ Internally, these are called "CDATA list attributes", but that
+ probably doesn't make sense to an end-user, so the argument name
+ is ``multi_valued_attributes``.
+
+ :param preserve_whitespace_tags: A set of tags to treat
+ the way
tags are treated in HTML. Tags in this set
+ are immune from pretty-printing; their contents will always be
+ output as-is.
+
+ :param string_containers: A dictionary mapping tag names to
+ the classes that should be instantiated to contain the textual
+ contents of those tags. The default is to use NavigableString
+ for every tag, no matter what the name. You can override the
+ default by changing :py:attr:`DEFAULT_STRING_CONTAINERS`.
+
+ :param store_line_numbers: If the parser keeps track of the line
+ numbers and positions of the original markup, that information
+ will, by default, be stored in each corresponding
+ :py:class:`bs4.element.Tag` object. You can turn this off by
+ passing store_line_numbers=False; then Tag.sourcepos and
+ Tag.sourceline will always be None. If the parser you're using
+ doesn't keep track of this information, then store_line_numbers
+ is irrelevant.
+
+ :param attribute_dict_class: The value of a multi-valued attribute
+ (such as HTML's 'class') willl be stored in an instance of this
+ class. The default is Beautiful Soup's built-in
+ `AttributeValueList`, which is a normal Python list, and you
+ will probably never need to change it.
+ """
+
+ USE_DEFAULT: Any = object() #: :meta private:
+
+ def __init__(
+ self,
+ multi_valued_attributes: Dict[str, Set[str]] = USE_DEFAULT,
+ preserve_whitespace_tags: Set[str] = USE_DEFAULT,
+ store_line_numbers: bool = USE_DEFAULT,
+ string_containers: Dict[str, Type[NavigableString]] = USE_DEFAULT,
+ empty_element_tags: Set[str] = USE_DEFAULT,
+ attribute_dict_class: Type[AttributeDict] = AttributeDict,
+ attribute_value_list_class: Type[AttributeValueList] = AttributeValueList,
+ ):
+ self.soup = None
+ if multi_valued_attributes is self.USE_DEFAULT:
+ multi_valued_attributes = self.DEFAULT_CDATA_LIST_ATTRIBUTES
+ self.cdata_list_attributes = multi_valued_attributes
+ if preserve_whitespace_tags is self.USE_DEFAULT:
+ preserve_whitespace_tags = self.DEFAULT_PRESERVE_WHITESPACE_TAGS
+ self.preserve_whitespace_tags = preserve_whitespace_tags
+ if empty_element_tags is self.USE_DEFAULT:
+ self.empty_element_tags = self.DEFAULT_EMPTY_ELEMENT_TAGS
+ else:
+ self.empty_element_tags = empty_element_tags
+ # TODO: store_line_numbers is probably irrelevant now that
+ # the behavior of sourceline and sourcepos has been made consistent
+ # everywhere.
+ if store_line_numbers == self.USE_DEFAULT:
+ store_line_numbers = self.TRACKS_LINE_NUMBERS
+ self.store_line_numbers = store_line_numbers
+ if string_containers == self.USE_DEFAULT:
+ string_containers = self.DEFAULT_STRING_CONTAINERS
+ self.string_containers = string_containers
+ self.attribute_dict_class = attribute_dict_class
+ self.attribute_value_list_class = attribute_value_list_class
+
+ NAME: str = "[Unknown tree builder]"
+ ALTERNATE_NAMES: Iterable[str] = []
+ features: Iterable[str] = []
+
+ is_xml: bool = False
+ picklable: bool = False
+
+ soup: Optional[BeautifulSoup] #: :meta private:
+
+ #: A tag will be considered an empty-element
+ #: tag when and only when it has no contents.
+ empty_element_tags: Optional[Set[str]] = None #: :meta private:
+ cdata_list_attributes: Dict[str, Set[str]] #: :meta private:
+ preserve_whitespace_tags: Set[str] #: :meta private:
+ string_containers: Dict[str, Type[NavigableString]] #: :meta private:
+ tracks_line_numbers: bool #: :meta private:
+
+ #: A value for these tag/attribute combinations is a space- or
+ #: comma-separated list of CDATA, rather than a single CDATA.
+ DEFAULT_CDATA_LIST_ATTRIBUTES: Dict[str, Set[str]] = defaultdict(set)
+
+ #: Whitespace should be preserved inside these tags.
+ DEFAULT_PRESERVE_WHITESPACE_TAGS: Set[str] = set()
+
+ #: The textual contents of tags with these names should be
+ #: instantiated with some class other than `bs4.element.NavigableString`.
+ DEFAULT_STRING_CONTAINERS: Dict[str, Type[bs4.element.NavigableString]] = {} # type:ignore
+
+ #: By default, tags are treated as empty-element tags if they have
+ #: no contents--that is, using XML rules. HTMLTreeBuilder
+ #: defines a different set of DEFAULT_EMPTY_ELEMENT_TAGS based on the
+ #: HTML 4 and HTML5 standards.
+ DEFAULT_EMPTY_ELEMENT_TAGS: Optional[Set[str]] = None
+
+ #: Most parsers don't keep track of line numbers.
+ TRACKS_LINE_NUMBERS: bool = False
+
+ def initialize_soup(self, soup: BeautifulSoup) -> None:
+ """The BeautifulSoup object has been initialized and is now
+ being associated with the TreeBuilder.
+
+ :param soup: A BeautifulSoup object.
+ """
+ self.soup = soup
+
+ def reset(self) -> None:
+ """Do any work necessary to reset the underlying parser
+ for a new document.
+
+ By default, this does nothing.
+ """
+ pass
+
+ def can_be_empty_element(self, tag_name: str) -> bool:
+ """Might a tag with this name be an empty-element tag?
+
+ The final markup may or may not actually present this tag as
+ self-closing.
+
+ For instance: an HTMLBuilder does not consider a tag to be
+ an empty-element tag (it's not in
+ HTMLBuilder.empty_element_tags). This means an empty
tag
+ will be presented as "
", not "
" or "".
+
+ The default implementation has no opinion about which tags are
+ empty-element tags, so a tag will be presented as an
+ empty-element tag if and only if it has no children.
+ " " will become " ", and "bar " will
+ be left alone.
+
+ :param tag_name: The name of a markup tag.
+ """
+ if self.empty_element_tags is None:
+ return True
+ return tag_name in self.empty_element_tags
+
+ def feed(self, markup: _RawMarkup) -> None:
+ """Run incoming markup through some parsing process."""
+ raise NotImplementedError()
+
+ def prepare_markup(
+ self,
+ markup: _RawMarkup,
+ user_specified_encoding: Optional[_Encoding] = None,
+ document_declared_encoding: Optional[_Encoding] = None,
+ exclude_encodings: Optional[_Encodings] = None,
+ ) -> Iterable[Tuple[_RawMarkup, Optional[_Encoding], Optional[_Encoding], bool]]:
+ """Run any preliminary steps necessary to make incoming markup
+ acceptable to the parser.
+
+ :param markup: The markup that's about to be parsed.
+ :param user_specified_encoding: The user asked to try this encoding
+ to convert the markup into a Unicode string.
+ :param document_declared_encoding: The markup itself claims to be
+ in this encoding. NOTE: This argument is not used by the
+ calling code and can probably be removed.
+ :param exclude_encodings: The user asked *not* to try any of
+ these encodings.
+
+ :yield: A series of 4-tuples: (markup, encoding, declared encoding,
+ has undergone character replacement)
+
+ Each 4-tuple represents a strategy that the parser can try
+ to convert the document to Unicode and parse it. Each
+ strategy will be tried in turn.
+
+ By default, the only strategy is to parse the markup
+ as-is. See `LXMLTreeBuilderForXML` and
+ `HTMLParserTreeBuilder` for implementations that take into
+ account the quirks of particular parsers.
+
+ :meta private:
+
+ """
+ yield markup, None, None, False
+
+ def test_fragment_to_document(self, fragment: str) -> str:
+ """Wrap an HTML fragment to make it look like a document.
+
+ Different parsers do this differently. For instance, lxml
+ introduces an empty
tag, and html5lib
+ doesn't. Abstracting this away lets us write simple tests
+ which run HTML fragments through the parser and compare the
+ results against other HTML fragments.
+
+ This method should not be used outside of unit tests.
+
+ :param fragment: A fragment of HTML.
+ :return: A full HTML document.
+ :meta private:
+ """
+ return fragment
+
+ def set_up_substitutions(self, tag: Tag) -> bool:
+ """Set up any substitutions that will need to be performed on
+ a `Tag` when it's output as a string.
+
+ By default, this does nothing. See `HTMLTreeBuilder` for a
+ case where this is used.
+
+ :return: Whether or not a substitution was performed.
+ :meta private:
+ """
+ return False
+
+ def _replace_cdata_list_attribute_values(
+ self, tag_name: str, attrs: _RawOrProcessedAttributeValues
+ ) -> _AttributeValues:
+ """When an attribute value is associated with a tag that can
+ have multiple values for that attribute, convert the string
+ value to a list of strings.
+
+ Basically, replaces class="foo bar" with class=["foo", "bar"]
+
+ NOTE: This method modifies its input in place.
+
+ :param tag_name: The name of a tag.
+ :param attrs: A dictionary containing the tag's attributes.
+ Any appropriate attribute values will be modified in place.
+ :return: The modified dictionary that was originally passed in.
+ """
+
+ # First, cast the attrs dict to _AttributeValues. This might
+ # not be accurate yet, but it will be by the time this method
+ # returns.
+ modified_attrs = cast(_AttributeValues, attrs)
+ if not modified_attrs or not self.cdata_list_attributes:
+ # Nothing to do.
+ return modified_attrs
+
+ # There is at least a possibility that we need to modify one of
+ # the attribute values.
+ universal: Set[str] = self.cdata_list_attributes.get("*", set())
+ tag_specific = self.cdata_list_attributes.get(tag_name.lower(), None)
+ for attr in list(modified_attrs.keys()):
+ modified_value: _AttributeValue
+ if attr in universal or (tag_specific and attr in tag_specific):
+ # We have a "class"-type attribute whose string
+ # value is a whitespace-separated list of
+ # values. Split it into a list.
+ original_value: _AttributeValue = modified_attrs[attr]
+ if isinstance(original_value, _RawAttributeValue):
+ # This is a _RawAttributeValue (a string) that
+ # needs to be split and converted to a
+ # AttributeValueList so it can be an
+ # _AttributeValue.
+ modified_value = self.attribute_value_list_class(
+ nonwhitespace_re.findall(original_value)
+ )
+ else:
+ # html5lib calls setAttributes twice for the
+ # same tag when rearranging the parse tree. On
+ # the second call the attribute value here is
+ # already a list. This can also happen when a
+ # Tag object is cloned. If this happens, leave
+ # the value alone rather than trying to split
+ # it again.
+ modified_value = original_value
+ modified_attrs[attr] = modified_value
+ return modified_attrs
+
+
+class SAXTreeBuilder(TreeBuilder):
+ """A Beautiful Soup treebuilder that listens for SAX events.
+
+ This is not currently used for anything, and it will be removed
+ soon. It was a good idea, but it wasn't properly integrated into the
+ rest of Beautiful Soup, so there have been long stretches where it
+ hasn't worked properly.
+ """
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ warnings.warn(
+ "The SAXTreeBuilder class was deprecated in 4.13.0 and will be removed soon thereafter. It is completely untested and probably doesn't work; do not use it.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ super(SAXTreeBuilder, self).__init__(*args, **kwargs)
+
+ def feed(self, markup: _RawMarkup) -> None:
+ raise NotImplementedError()
+
+ def close(self) -> None:
+ pass
+
+ def startElement(self, name: str, attrs: Dict[str, str]) -> None:
+ attrs = AttributeDict((key[1], value) for key, value in list(attrs.items()))
+ # print("Start %s, %r" % (name, attrs))
+ assert self.soup is not None
+ self.soup.handle_starttag(name, None, None, attrs)
+
+ def endElement(self, name: str) -> None:
+ # print("End %s" % name)
+ assert self.soup is not None
+ self.soup.handle_endtag(name)
+
+ def startElementNS(
+ self, nsTuple: Tuple[str, str], nodeName: str, attrs: Dict[str, str]
+ ) -> None:
+ # Throw away (ns, nodeName) for now.
+ self.startElement(nodeName, attrs)
+
+ def endElementNS(self, nsTuple: Tuple[str, str], nodeName: str) -> None:
+ # Throw away (ns, nodeName) for now.
+ self.endElement(nodeName)
+ # handler.endElementNS((ns, node.nodeName), node.nodeName)
+
+ def startPrefixMapping(self, prefix: str, nodeValue: str) -> None:
+ # Ignore the prefix for now.
+ pass
+
+ def endPrefixMapping(self, prefix: str) -> None:
+ # Ignore the prefix for now.
+ # handler.endPrefixMapping(prefix)
+ pass
+
+ def characters(self, content: str) -> None:
+ assert self.soup is not None
+ self.soup.handle_data(content)
+
+ def startDocument(self) -> None:
+ pass
+
+ def endDocument(self) -> None:
+ pass
+
+
+class HTMLTreeBuilder(TreeBuilder):
+ """This TreeBuilder knows facts about HTML, such as which tags are treated
+ specially by the HTML standard.
+ """
+
+ #: Some HTML tags are defined as having no contents. Beautiful Soup
+ #: treats these specially.
+ DEFAULT_EMPTY_ELEMENT_TAGS: Optional[Set[str]] = set(
+ [
+ # These are from HTML5.
+ "area",
+ "base",
+ "br",
+ "col",
+ "embed",
+ "hr",
+ "img",
+ "input",
+ "keygen",
+ "link",
+ "menuitem",
+ "meta",
+ "param",
+ "source",
+ "track",
+ "wbr",
+ # These are from earlier versions of HTML and are removed in HTML5.
+ "basefont",
+ "bgsound",
+ "command",
+ "frame",
+ "image",
+ "isindex",
+ "nextid",
+ "spacer",
+ ]
+ )
+
+ #: The HTML standard defines these tags as block-level elements. Beautiful
+ #: Soup does not treat these elements differently from other elements,
+ #: but it may do so eventually, and this information is available if
+ #: you need to use it.
+ DEFAULT_BLOCK_ELEMENTS: Set[str] = set(
+ [
+ "address",
+ "article",
+ "aside",
+ "blockquote",
+ "canvas",
+ "dd",
+ "div",
+ "dl",
+ "dt",
+ "fieldset",
+ "figcaption",
+ "figure",
+ "footer",
+ "form",
+ "h1",
+ "h2",
+ "h3",
+ "h4",
+ "h5",
+ "h6",
+ "header",
+ "hr",
+ "li",
+ "main",
+ "nav",
+ "noscript",
+ "ol",
+ "output",
+ "p",
+ "pre",
+ "section",
+ "table",
+ "tfoot",
+ "ul",
+ "video",
+ ]
+ )
+
+ #: These HTML tags need special treatment so they can be
+ #: represented by a string class other than `bs4.element.NavigableString`.
+ #:
+ #: For some of these tags, it's because the HTML standard defines
+ #: an unusual content model for them. I made this list by going
+ #: through the HTML spec
+ #: (https://html.spec.whatwg.org/#metadata-content) and looking for
+ #: "metadata content" elements that can contain strings.
+ #:
+ #: The Ruby tags ( and ) are here despite being normal
+ #: "phrasing content" tags, because the content they contain is
+ #: qualitatively different from other text in the document, and it
+ #: can be useful to be able to distinguish it.
+ #:
+ #: TODO: Arguably could go here but it seems
+ #: qualitatively different from the other tags.
+ DEFAULT_STRING_CONTAINERS: Dict[str, Type[bs4.element.NavigableString]] = { # type:ignore
+ "rt": RubyTextString,
+ "rp": RubyParenthesisString,
+ "style": Stylesheet,
+ "script": Script,
+ "template": TemplateString,
+ }
+
+ #: The HTML standard defines these attributes as containing a
+ #: space-separated list of values, not a single value. That is,
+ #: class="foo bar" means that the 'class' attribute has two values,
+ #: 'foo' and 'bar', not the single value 'foo bar'. When we
+ #: encounter one of these attributes, we will parse its value into
+ #: a list of values if possible. Upon output, the list will be
+ #: converted back into a string.
+ DEFAULT_CDATA_LIST_ATTRIBUTES: Dict[str, Set[str]] = {
+ "*": {"class", "accesskey", "dropzone"},
+ "a": {"rel", "rev"},
+ "link": {"rel", "rev"},
+ "td": {"headers"},
+ "th": {"headers"},
+ "form": {"accept-charset"},
+ "object": {"archive"},
+ # These are HTML5 specific, as are *.accesskey and *.dropzone above.
+ "area": {"rel"},
+ "icon": {"sizes"},
+ "iframe": {"sandbox"},
+ "output": {"for"},
+ }
+
+ #: By default, whitespace inside these HTML tags will be
+ #: preserved rather than being collapsed.
+ DEFAULT_PRESERVE_WHITESPACE_TAGS: set[str] = set(["pre", "textarea"])
+
+ def set_up_substitutions(self, tag: Tag) -> bool:
+ """Replace the declared encoding in a tag with a placeholder,
+ to be substituted when the tag is output to a string.
+
+ An HTML document may come in to Beautiful Soup as one
+ encoding, but exit in a different encoding, and the tag
+ needs to be changed to reflect this.
+
+ :return: Whether or not a substitution was performed.
+
+ :meta private:
+ """
+ # We are only interested in tags
+ if tag.name != "meta":
+ return False
+
+ # TODO: This cast will fail in the (very unlikely) scenario
+ # that the programmer who instantiates the TreeBuilder
+ # specifies meta['content'] or meta['charset'] as
+ # cdata_list_attributes.
+ content: Optional[str] = cast(Optional[str], tag.get("content"))
+ charset: Optional[str] = cast(Optional[str], tag.get("charset"))
+
+ # But we can accommodate meta['http-equiv'] being made a
+ # cdata_list_attribute (again, very unlikely) without much
+ # trouble.
+ http_equiv: List[str] = tag.get_attribute_list("http-equiv")
+
+ # We are interested in tags that say what encoding the
+ # document was originally in. This means HTML 5-style
+ # tags that provide the "charset" attribute. It also means
+ # HTML 4-style tags that provide the "content"
+ # attribute and have "http-equiv" set to "content-type".
+ #
+ # In both cases we will replace the value of the appropriate
+ # attribute with a standin object that can take on any
+ # encoding.
+ substituted = False
+ if charset is not None:
+ # HTML 5 style:
+ #
+ tag["charset"] = CharsetMetaAttributeValue(charset)
+ substituted = True
+
+ elif content is not None and any(
+ x.lower() == "content-type" for x in http_equiv
+ ):
+ # HTML 4 style:
+ #
+ tag["content"] = ContentMetaAttributeValue(content)
+ substituted = True
+
+ return substituted
+
+
+class DetectsXMLParsedAsHTML(object):
+ """A mixin class for any class (a TreeBuilder, or some class used by a
+ TreeBuilder) that's in a position to detect whether an XML
+ document is being incorrectly parsed as HTML, and issue an
+ appropriate warning.
+
+ This requires being able to observe an incoming processing
+ instruction that might be an XML declaration, and also able to
+ observe tags as they're opened. If you can't do that for a given
+ `TreeBuilder`, there's a less reliable implementation based on
+ examining the raw markup.
+ """
+
+ #: Regular expression for seeing if string markup has an tag.
+ LOOKS_LIKE_HTML: Pattern[str] = re.compile("<[^ +]html", re.I)
+
+ #: Regular expression for seeing if byte markup has an tag.
+ LOOKS_LIKE_HTML_B: Pattern[bytes] = re.compile(b"<[^ +]html", re.I)
+
+ #: The start of an XML document string.
+ XML_PREFIX: str = " bool:
+ """Perform a check on some markup to see if it looks like XML
+ that's not XHTML. If so, issue a warning.
+
+ This is much less reliable than doing the check while parsing,
+ but some of the tree builders can't do that.
+
+ :param stacklevel: The stacklevel of the code calling this\
+ function.
+
+ :return: True if the markup looks like non-XHTML XML, False
+ otherwise.
+ """
+ if markup is None:
+ return False
+ markup = markup[:500]
+ if isinstance(markup, bytes):
+ markup_b: bytes = markup
+ looks_like_xml = markup_b.startswith(
+ cls.XML_PREFIX_B
+ ) and not cls.LOOKS_LIKE_HTML_B.search(markup)
+ else:
+ markup_s: str = markup
+ looks_like_xml = markup_s.startswith(
+ cls.XML_PREFIX
+ ) and not cls.LOOKS_LIKE_HTML.search(markup)
+
+ if looks_like_xml:
+ cls._warn(stacklevel=stacklevel + 2)
+ return True
+ return False
+
+ @classmethod
+ def _warn(cls, stacklevel: int = 5) -> None:
+ """Issue a warning about XML being parsed as HTML."""
+ warnings.warn(
+ XMLParsedAsHTMLWarning.MESSAGE,
+ XMLParsedAsHTMLWarning,
+ stacklevel=stacklevel,
+ )
+
+ def _initialize_xml_detector(self) -> None:
+ """Call this method before parsing a document."""
+ self._first_processing_instruction = None
+ self._root_tag_name = None
+
+ def _document_might_be_xml(self, processing_instruction: str) -> None:
+ """Call this method when encountering an XML declaration, or a
+ "processing instruction" that might be an XML declaration.
+
+ This helps Beautiful Soup detect potential issues later, if
+ the XML document turns out to be a non-XHTML document that's
+ being parsed as XML.
+ """
+ if (
+ self._first_processing_instruction is not None
+ or self._root_tag_name is not None
+ ):
+ # The document has already started. Don't bother checking
+ # anymore.
+ return
+
+ self._first_processing_instruction = processing_instruction
+
+ # We won't know until we encounter the first tag whether or
+ # not this is actually a problem.
+
+ def _root_tag_encountered(self, name: str) -> None:
+ """Call this when you encounter the document's root tag.
+
+ This is where we actually check whether an XML document is
+ being incorrectly parsed as HTML, and issue the warning.
+ """
+ if self._root_tag_name is not None:
+ # This method was incorrectly called multiple times. Do
+ # nothing.
+ return
+
+ self._root_tag_name = name
+
+ if (
+ name != "html"
+ and self._first_processing_instruction is not None
+ and self._first_processing_instruction.lower().startswith("xml ")
+ ):
+ # We encountered an XML declaration and then a tag other
+ # than 'html'. This is a reliable indicator that a
+ # non-XHTML document is being parsed as XML.
+ self._warn(stacklevel=10)
+
+
+def register_treebuilders_from(module: ModuleType) -> None:
+ """Copy TreeBuilders from the given module into this module."""
+ this_module = sys.modules[__name__]
+ for name in module.__all__:
+ obj = getattr(module, name)
+
+ if issubclass(obj, TreeBuilder):
+ setattr(this_module, name, obj)
+ this_module.__all__.append(name)
+ # Register the builder while we're at it.
+ this_module.builder_registry.register(obj)
+
+
+# Builders are registered in reverse order of priority, so that custom
+# builder registrations will take precedence. In general, we want lxml
+# to take precedence over html5lib, because it's faster. And we only
+# want to use HTMLParser as a last resort.
+from . import _htmlparser # noqa: E402
+
+register_treebuilders_from(_htmlparser)
+try:
+ from . import _html5lib
+
+ register_treebuilders_from(_html5lib)
+except ImportError:
+ # They don't have html5lib installed.
+ pass
+try:
+ from . import _lxml
+
+ register_treebuilders_from(_lxml)
+except ImportError:
+ # They don't have lxml installed.
+ pass
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8b2c979adbe77fd5a817b75ffeca75de8f15ebe3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/__pycache__/_html5lib.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/__pycache__/_html5lib.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..33cf460e067e66a846a65212df42569a324ede17
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/__pycache__/_html5lib.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/__pycache__/_htmlparser.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/__pycache__/_htmlparser.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..12a94335ca411acc1a18b3acddfcb5fd54027f7e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/__pycache__/_htmlparser.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/__pycache__/_lxml.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/__pycache__/_lxml.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e4a2fe612415e341d13b44c76f10b6e3bbe47d88
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/__pycache__/_lxml.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/_html5lib.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/_html5lib.py
new file mode 100644
index 0000000000000000000000000000000000000000..c90231f6c2014bbed02f320df8c970e9eedbe46a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/_html5lib.py
@@ -0,0 +1,611 @@
+# Use of this source code is governed by the MIT license.
+__license__ = "MIT"
+
+__all__ = [
+ "HTML5TreeBuilder",
+]
+
+from typing import (
+ Any,
+ cast,
+ Dict,
+ Iterable,
+ Optional,
+ Sequence,
+ TYPE_CHECKING,
+ Tuple,
+ Union,
+)
+from typing_extensions import TypeAlias
+from bs4._typing import (
+ _AttributeValue,
+ _AttributeValues,
+ _Encoding,
+ _Encodings,
+ _NamespaceURL,
+ _RawMarkup,
+)
+
+import warnings
+from bs4.builder import (
+ DetectsXMLParsedAsHTML,
+ PERMISSIVE,
+ HTML,
+ HTML_5,
+ HTMLTreeBuilder,
+)
+from bs4.element import (
+ NamespacedAttribute,
+ PageElement,
+ nonwhitespace_re,
+)
+import html5lib
+from html5lib.constants import (
+ namespaces,
+)
+from bs4.element import (
+ Comment,
+ Doctype,
+ NavigableString,
+ Tag,
+)
+
+if TYPE_CHECKING:
+ from bs4 import BeautifulSoup
+
+from html5lib.treebuilders import base as treebuilder_base
+
+
+class HTML5TreeBuilder(HTMLTreeBuilder):
+ """Use `html5lib `_ to
+ build a tree.
+
+ Note that `HTML5TreeBuilder` does not support some common HTML
+ `TreeBuilder` features. Some of these features could theoretically
+ be implemented, but at the very least it's quite difficult,
+ because html5lib moves the parse tree around as it's being built.
+
+ Specifically:
+
+ * This `TreeBuilder` doesn't use different subclasses of
+ `NavigableString` (e.g. `Script`) based on the name of the tag
+ in which the string was found.
+ * You can't use a `SoupStrainer` to parse only part of a document.
+ """
+
+ NAME: str = "html5lib"
+
+ features: Iterable[str] = [NAME, PERMISSIVE, HTML_5, HTML]
+
+ #: html5lib can tell us which line number and position in the
+ #: original file is the source of an element.
+ TRACKS_LINE_NUMBERS: bool = True
+
+ underlying_builder: "TreeBuilderForHtml5lib" #: :meta private:
+ user_specified_encoding: Optional[_Encoding]
+
+ def prepare_markup(
+ self,
+ markup: _RawMarkup,
+ user_specified_encoding: Optional[_Encoding] = None,
+ document_declared_encoding: Optional[_Encoding] = None,
+ exclude_encodings: Optional[_Encodings] = None,
+ ) -> Iterable[Tuple[_RawMarkup, Optional[_Encoding], Optional[_Encoding], bool]]:
+ # Store the user-specified encoding for use later on.
+ self.user_specified_encoding = user_specified_encoding
+
+ # document_declared_encoding and exclude_encodings aren't used
+ # ATM because the html5lib TreeBuilder doesn't use
+ # UnicodeDammit.
+ for variable, name in (
+ (document_declared_encoding, "document_declared_encoding"),
+ (exclude_encodings, "exclude_encodings"),
+ ):
+ if variable:
+ warnings.warn(
+ f"You provided a value for {name}, but the html5lib tree builder doesn't support {name}.",
+ stacklevel=3,
+ )
+
+ # html5lib only parses HTML, so if it's given XML that's worth
+ # noting.
+ DetectsXMLParsedAsHTML.warn_if_markup_looks_like_xml(markup, stacklevel=3)
+
+ yield (markup, None, None, False)
+
+ # These methods are defined by Beautiful Soup.
+ def feed(self, markup: _RawMarkup) -> None:
+ """Run some incoming markup through some parsing process,
+ populating the `BeautifulSoup` object in `HTML5TreeBuilder.soup`.
+ """
+ if self.soup is not None and self.soup.parse_only is not None:
+ warnings.warn(
+ "You provided a value for parse_only, but the html5lib tree builder doesn't support parse_only. The entire document will be parsed.",
+ stacklevel=4,
+ )
+
+ # self.underlying_builder is probably None now, but it'll be set
+ # when html5lib calls self.create_treebuilder().
+ parser = html5lib.HTMLParser(tree=self.create_treebuilder)
+ assert self.underlying_builder is not None
+ self.underlying_builder.parser = parser
+ extra_kwargs = dict()
+ if not isinstance(markup, str):
+ # kwargs, specifically override_encoding, will eventually
+ # be passed in to html5lib's
+ # HTMLBinaryInputStream.__init__.
+ extra_kwargs["override_encoding"] = self.user_specified_encoding
+
+ doc = parser.parse(markup, **extra_kwargs) # type:ignore
+
+ # Set the character encoding detected by the tokenizer.
+ if isinstance(markup, str):
+ # We need to special-case this because html5lib sets
+ # charEncoding to UTF-8 if it gets Unicode input.
+ doc.original_encoding = None
+ else:
+ original_encoding = parser.tokenizer.stream.charEncoding[0] # type:ignore
+ # The encoding is an html5lib Encoding object. We want to
+ # use a string for compatibility with other tree builders.
+ original_encoding = original_encoding.name
+ doc.original_encoding = original_encoding
+ self.underlying_builder.parser = None
+
+ def create_treebuilder(
+ self, namespaceHTMLElements: bool
+ ) -> "TreeBuilderForHtml5lib":
+ """Called by html5lib to instantiate the kind of class it
+ calls a 'TreeBuilder'.
+
+ :param namespaceHTMLElements: Whether or not to namespace HTML elements.
+
+ :meta private:
+ """
+ self.underlying_builder = TreeBuilderForHtml5lib(
+ namespaceHTMLElements, self.soup, store_line_numbers=self.store_line_numbers
+ )
+ return self.underlying_builder
+
+ def test_fragment_to_document(self, fragment: str) -> str:
+ """See `TreeBuilder`."""
+ return "%s" % fragment
+
+
+class TreeBuilderForHtml5lib(treebuilder_base.TreeBuilder):
+ soup: "BeautifulSoup" #: :meta private:
+ parser: Optional[html5lib.HTMLParser] #: :meta private:
+
+ def __init__(
+ self,
+ namespaceHTMLElements: bool,
+ soup: Optional["BeautifulSoup"] = None,
+ store_line_numbers: bool = True,
+ **kwargs: Any,
+ ):
+ if soup:
+ self.soup = soup
+ else:
+ warnings.warn(
+ "The optionality of the 'soup' argument to the TreeBuilderForHtml5lib constructor is deprecated as of Beautiful Soup 4.13.0: 'soup' is now required. If you can't pass in a BeautifulSoup object here, or you get this warning and it seems mysterious to you, please contact the Beautiful Soup developer team for possible un-deprecation.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ from bs4 import BeautifulSoup
+
+ # TODO: Why is the parser 'html.parser' here? Using
+ # html5lib doesn't cause an infinite loop and is more
+ # accurate. Best to get rid of this entire section, I think.
+ self.soup = BeautifulSoup(
+ "", "html.parser", store_line_numbers=store_line_numbers, **kwargs
+ )
+ # TODO: What are **kwargs exactly? Should they be passed in
+ # here in addition to/instead of being passed to the BeautifulSoup
+ # constructor?
+ super(TreeBuilderForHtml5lib, self).__init__(namespaceHTMLElements)
+
+ # This will be set later to a real html5lib HTMLParser object,
+ # which we can use to track the current line number.
+ self.parser = None
+ self.store_line_numbers = store_line_numbers
+
+ def documentClass(self) -> "Element":
+ self.soup.reset()
+ return Element(self.soup, self.soup, None)
+
+ def insertDoctype(self, token: Dict[str, Any]) -> None:
+ name: str = cast(str, token["name"])
+ publicId: Optional[str] = cast(Optional[str], token["publicId"])
+ systemId: Optional[str] = cast(Optional[str], token["systemId"])
+
+ doctype = Doctype.for_name_and_ids(name, publicId, systemId)
+ self.soup.object_was_parsed(doctype)
+
+ def elementClass(self, name: str, namespace: str) -> "Element":
+ sourceline: Optional[int] = None
+ sourcepos: Optional[int] = None
+ if self.parser is not None and self.store_line_numbers:
+ # This represents the point immediately after the end of the
+ # tag. We don't know when the tag started, but we do know
+ # where it ended -- the character just before this one.
+ sourceline, sourcepos = self.parser.tokenizer.stream.position() # type:ignore
+ assert sourcepos is not None
+ sourcepos = sourcepos - 1
+ tag = self.soup.new_tag(
+ name, namespace, sourceline=sourceline, sourcepos=sourcepos
+ )
+
+ return Element(tag, self.soup, namespace)
+
+ def commentClass(self, data: str) -> "TextNode":
+ return TextNode(Comment(data), self.soup)
+
+ def fragmentClass(self) -> "Element":
+ """This is only used by html5lib HTMLParser.parseFragment(),
+ which is never used by Beautiful Soup, only by the html5lib
+ unit tests. Since we don't currently hook into those tests,
+ the implementation is left blank.
+ """
+ raise NotImplementedError()
+
+ def getFragment(self) -> "Element":
+ """This is only used by the html5lib unit tests. Since we
+ don't currently hook into those tests, the implementation is
+ left blank.
+ """
+ raise NotImplementedError()
+
+ def appendChild(self, node: "Element") -> None:
+ # TODO: This code is not covered by the BS4 tests, and
+ # apparently not triggered by the html5lib test suite either.
+ # But it doesn't seem test-specific and there are calls to it
+ # (or a method with the same name) all over html5lib, so I'm
+ # leaving the implementation in place rather than replacing it
+ # with NotImplementedError()
+ self.soup.append(node.element)
+
+ def getDocument(self) -> "BeautifulSoup":
+ return self.soup
+
+ def testSerializer(self, node: "Element") -> None:
+ """This is only used by the html5lib unit tests. Since we
+ don't currently hook into those tests, the implementation is
+ left blank.
+ """
+ raise NotImplementedError()
+
+
+class AttrList(object):
+ """Represents a Tag's attributes in a way compatible with html5lib."""
+
+ element: Tag
+ attrs: _AttributeValues
+
+ def __init__(self, element: Tag):
+ self.element = element
+ self.attrs = dict(self.element.attrs)
+
+ def __iter__(self) -> Iterable[Tuple[str, _AttributeValue]]:
+ return list(self.attrs.items()).__iter__()
+
+ def __setitem__(self, name: str, value: _AttributeValue) -> None:
+ # If this attribute is a multi-valued attribute for this element,
+ # turn its value into a list.
+ list_attr = self.element.cdata_list_attributes or {}
+ if name in list_attr.get("*", []) or (
+ self.element.name in list_attr
+ and name in list_attr.get(self.element.name, [])
+ ):
+ # A node that is being cloned may have already undergone
+ # this procedure. Check for this and skip it.
+ if not isinstance(value, list):
+ assert isinstance(value, str)
+ value = self.element.attribute_value_list_class(
+ nonwhitespace_re.findall(value)
+ )
+ self.element[name] = value
+
+ def items(self) -> Iterable[Tuple[str, _AttributeValue]]:
+ return list(self.attrs.items())
+
+ def keys(self) -> Iterable[str]:
+ return list(self.attrs.keys())
+
+ def __len__(self) -> int:
+ return len(self.attrs)
+
+ def __getitem__(self, name: str) -> _AttributeValue:
+ return self.attrs[name]
+
+ def __contains__(self, name: str) -> bool:
+ return name in list(self.attrs.keys())
+
+
+class BeautifulSoupNode(treebuilder_base.Node):
+ # A node can correspond to _either_ a Tag _or_ a NavigableString.
+ tag: Optional[Tag]
+ string: Optional[NavigableString]
+ soup: "BeautifulSoup"
+ namespace: Optional[_NamespaceURL]
+
+ @property
+ def element(self) -> PageElement:
+ assert self.tag is not None or self.string is not None
+ if self.tag is not None:
+ return self.tag
+ else:
+ assert self.string is not None
+ return self.string
+
+ @property
+ def nodeType(self) -> int:
+ """Return the html5lib constant corresponding to the type of
+ the underlying DOM object.
+
+ NOTE: This property is only accessed by the html5lib test
+ suite, not by Beautiful Soup proper.
+ """
+ raise NotImplementedError()
+
+ # TODO-TYPING: typeshed stubs are incorrect about this;
+ # cloneNode returns a new Node, not None.
+ def cloneNode(self) -> treebuilder_base.Node: # type:ignore
+ raise NotImplementedError()
+
+
+class Element(BeautifulSoupNode):
+ namespace: Optional[_NamespaceURL]
+
+ def __init__(
+ self, element: Tag, soup: "BeautifulSoup", namespace: Optional[_NamespaceURL]
+ ):
+ self.tag = element
+ self.string = None
+ self.soup = soup
+ self.namespace = namespace
+ treebuilder_base.Node.__init__(self, element.name)
+
+ def appendChild(self, node: "BeautifulSoupNode") -> None:
+ string_child: Optional[NavigableString] = None
+ child: PageElement
+ if type(node.string) is NavigableString:
+ # We check for NavigableString *only* because we want to avoid
+ # joining PreformattedStrings, such as Comments, with nearby strings.
+ string_child = child = node.string
+ else:
+ child = node.element
+ node.parent = self
+
+ if (
+ child is not None
+ and child.parent is not None
+ and not isinstance(child, str)
+ ):
+ node.element.extract()
+
+ if (
+ string_child is not None
+ and self.tag is not None and self.tag.contents
+ and type(self.tag.contents[-1]) is NavigableString
+ ):
+ # We are appending a string onto another string.
+ # TODO This has O(n^2) performance, for input like
+ # "aaa..."
+ old_element = self.tag.contents[-1]
+ new_element = self.soup.new_string(old_element + string_child)
+ old_element.replace_with(new_element)
+ self.soup._most_recent_element = new_element
+ else:
+ if isinstance(node, str):
+ # Create a brand new NavigableString from this string.
+ child = self.soup.new_string(node)
+
+ # Tell Beautiful Soup to act as if it parsed this element
+ # immediately after the parent's last descendant. (Or
+ # immediately after the parent, if it has no children.)
+ if self.tag is not None and self.tag.contents:
+ most_recent_element = self.tag._last_descendant(False)
+ elif self.element.next_element is not None:
+ # Something from further ahead in the parse tree is
+ # being inserted into this earlier element. This is
+ # very annoying because it means an expensive search
+ # for the last element in the tree.
+ most_recent_element = self.soup._last_descendant()
+ else:
+ most_recent_element = self.element
+
+ self.soup.object_was_parsed(
+ child, parent=self.tag, most_recent_element=most_recent_element
+ )
+
+ def getAttributes(self) -> AttrList:
+ assert self.tag is not None
+ return AttrList(self.tag)
+
+ # An HTML5lib attribute name may either be a single string,
+ # or a tuple (namespace, name).
+ _Html5libAttributeName: TypeAlias = Union[str, Tuple[str, str]]
+ # Now we can define the type this method accepts as a dictionary
+ # mapping those attribute names to single string values.
+ _Html5libAttributes: TypeAlias = Dict[_Html5libAttributeName, str]
+
+ def setAttributes(self, attributes: Optional[_Html5libAttributes]) -> None:
+ assert self.tag is not None
+ if attributes is not None and len(attributes) > 0:
+ # Replace any namespaced attributes with
+ # NamespacedAttribute objects.
+ for name, value in list(attributes.items()):
+ if isinstance(name, tuple):
+ new_name = NamespacedAttribute(*name)
+ del attributes[name]
+ attributes[new_name] = value
+
+ # We can now cast attributes to the type of Dict
+ # used by Beautiful Soup.
+ normalized_attributes = cast(_AttributeValues, attributes)
+
+ # Values for tags like 'class' came in as single strings;
+ # replace them with lists of strings as appropriate.
+ self.soup.builder._replace_cdata_list_attribute_values(
+ self.name, normalized_attributes
+ )
+
+ # Then set the attributes on the Tag associated with this
+ # BeautifulSoupNode.
+ for name, value_or_values in list(normalized_attributes.items()):
+ self.tag[name] = value_or_values
+
+ # The attributes may contain variables that need substitution.
+ # Call set_up_substitutions manually.
+ #
+ # The Tag constructor called this method when the Tag was created,
+ # but we just set/changed the attributes, so call it again.
+ self.soup.builder.set_up_substitutions(self.tag)
+
+ attributes = property(getAttributes, setAttributes)
+
+ def insertText(
+ self, data: str, insertBefore: Optional["BeautifulSoupNode"] = None
+ ) -> None:
+ text = TextNode(self.soup.new_string(data), self.soup)
+ if insertBefore:
+ self.insertBefore(text, insertBefore)
+ else:
+ self.appendChild(text)
+
+ def insertBefore(
+ self, node: "BeautifulSoupNode", refNode: "BeautifulSoupNode"
+ ) -> None:
+ assert self.tag is not None
+ index = self.tag.index(refNode.element)
+ if (
+ type(node.element) is NavigableString
+ and self.tag.contents
+ and type(self.tag.contents[index - 1]) is NavigableString
+ ):
+ # (See comments in appendChild)
+ old_node = self.tag.contents[index - 1]
+ assert type(old_node) is NavigableString
+ new_str = self.soup.new_string(old_node + node.element)
+ old_node.replace_with(new_str)
+ else:
+ self.tag.insert(index, node.element)
+ node.parent = self
+
+ def removeChild(self, node: "Element") -> None:
+ node.element.extract()
+
+ def reparentChildren(self, newParent: "Element") -> None:
+ """Move all of this tag's children into another tag."""
+ # print("MOVE", self.element.contents)
+ # print("FROM", self.element)
+ # print("TO", new_parent.element)
+
+ element = self.tag
+ assert element is not None
+ new_parent_element = newParent.tag
+ assert new_parent_element is not None
+ # Determine what this tag's next_element will be once all the children
+ # are removed.
+ final_next_element = element.next_sibling
+
+ new_parents_last_descendant = new_parent_element._last_descendant(False, False)
+ if len(new_parent_element.contents) > 0:
+ # The new parent already contains children. We will be
+ # appending this tag's children to the end.
+
+ # We can make this assertion since we know new_parent has
+ # children.
+ assert new_parents_last_descendant is not None
+ new_parents_last_child = new_parent_element.contents[-1]
+ new_parents_last_descendant_next_element = (
+ new_parents_last_descendant.next_element
+ )
+ else:
+ # The new parent contains no children.
+ new_parents_last_child = None
+ new_parents_last_descendant_next_element = new_parent_element.next_element
+
+ to_append = element.contents
+ if len(to_append) > 0:
+ # Set the first child's previous_element and previous_sibling
+ # to elements within the new parent
+ first_child = to_append[0]
+ if new_parents_last_descendant is not None:
+ first_child.previous_element = new_parents_last_descendant
+ else:
+ first_child.previous_element = new_parent_element
+ first_child.previous_sibling = new_parents_last_child
+ if new_parents_last_descendant is not None:
+ new_parents_last_descendant.next_element = first_child
+ else:
+ new_parent_element.next_element = first_child
+ if new_parents_last_child is not None:
+ new_parents_last_child.next_sibling = first_child
+
+ # Find the very last element being moved. It is now the
+ # parent's last descendant. It has no .next_sibling and
+ # its .next_element is whatever the previous last
+ # descendant had.
+ last_childs_last_descendant = to_append[-1]._last_descendant(
+ is_initialized=False, accept_self=True
+ )
+
+ # Since we passed accept_self=True into _last_descendant,
+ # there's no possibility that the result is None.
+ assert last_childs_last_descendant is not None
+ last_childs_last_descendant.next_element = (
+ new_parents_last_descendant_next_element
+ )
+ if new_parents_last_descendant_next_element is not None:
+ # TODO-COVERAGE: This code has no test coverage and
+ # I'm not sure how to get html5lib to go through this
+ # path, but it's just the other side of the previous
+ # line.
+ new_parents_last_descendant_next_element.previous_element = (
+ last_childs_last_descendant
+ )
+ last_childs_last_descendant.next_sibling = None
+
+ for child in to_append:
+ child.parent = new_parent_element
+ new_parent_element.contents.append(child)
+
+ # Now that this element has no children, change its .next_element.
+ element.contents = []
+ element.next_element = final_next_element
+
+ # print("DONE WITH MOVE")
+ # print("FROM", self.element)
+ # print("TO", new_parent_element)
+
+ # TODO-TYPING: typeshed stubs are incorrect about this;
+ # hasContent returns a boolean, not None.
+ def hasContent(self) -> bool: # type:ignore
+ return self.tag is None or len(self.tag.contents) > 0
+
+ # TODO-TYPING: typeshed stubs are incorrect about this;
+ # cloneNode returns a new Node, not None.
+ def cloneNode(self) -> treebuilder_base.Node: # type:ignore
+ assert self.tag is not None
+ tag = self.soup.new_tag(self.tag.name, self.namespace)
+ node = Element(tag, self.soup, self.namespace)
+ for key, value in self.attributes:
+ node.attributes[key] = value
+ return node
+
+ def getNameTuple(self) -> Tuple[Optional[_NamespaceURL], str]:
+ if self.namespace is None:
+ return namespaces["html"], self.name
+ else:
+ return self.namespace, self.name
+
+ nameTuple = property(getNameTuple)
+
+
+class TextNode(BeautifulSoupNode):
+
+ def __init__(self, element: NavigableString, soup: "BeautifulSoup"):
+ treebuilder_base.Node.__init__(self, None)
+ self.tag = None
+ self.string = element
+ self.soup = soup
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/_htmlparser.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/_htmlparser.py
new file mode 100644
index 0000000000000000000000000000000000000000..165a3d89cfcbd2207380999dcbf4e55ff47acb79
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/_htmlparser.py
@@ -0,0 +1,462 @@
+# encoding: utf-8
+"""Use the HTMLParser library to parse HTML files that aren't too bad."""
+from __future__ import annotations
+
+# Use of this source code is governed by the MIT license.
+__license__ = "MIT"
+
+__all__ = [
+ "HTMLParserTreeBuilder",
+]
+
+from html.parser import HTMLParser
+
+from typing import (
+ Any,
+ Callable,
+ cast,
+ Dict,
+ Iterable,
+ List,
+ Optional,
+ TYPE_CHECKING,
+ Tuple,
+ Type,
+ Union,
+)
+
+from bs4.element import (
+ AttributeDict,
+ CData,
+ Comment,
+ Declaration,
+ Doctype,
+ ProcessingInstruction,
+)
+from bs4.dammit import EntitySubstitution, UnicodeDammit
+
+from bs4.builder import (
+ DetectsXMLParsedAsHTML,
+ HTML,
+ HTMLTreeBuilder,
+ STRICT,
+)
+
+from bs4.exceptions import ParserRejectedMarkup
+
+if TYPE_CHECKING:
+ from bs4 import BeautifulSoup
+ from bs4.element import NavigableString
+ from bs4._typing import (
+ _Encoding,
+ _Encodings,
+ _RawMarkup,
+ )
+
+HTMLPARSER = "html.parser"
+
+_DuplicateAttributeHandler = Callable[[Dict[str, str], str, str], None]
+
+
+class BeautifulSoupHTMLParser(HTMLParser, DetectsXMLParsedAsHTML):
+ #: Constant to handle duplicate attributes by ignoring later values
+ #: and keeping the earlier ones.
+ REPLACE: str = "replace"
+
+ #: Constant to handle duplicate attributes by replacing earlier values
+ #: with later ones.
+ IGNORE: str = "ignore"
+
+ """A subclass of the Python standard library's HTMLParser class, which
+ listens for HTMLParser events and translates them into calls
+ to Beautiful Soup's tree construction API.
+
+ :param on_duplicate_attribute: A strategy for what to do if a
+ tag includes the same attribute more than once. Accepted
+ values are: REPLACE (replace earlier values with later
+ ones, the default), IGNORE (keep the earliest value
+ encountered), or a callable. A callable must take three
+ arguments: the dictionary of attributes already processed,
+ the name of the duplicate attribute, and the most recent value
+ encountered.
+ """
+
+ def __init__(
+ self,
+ soup: BeautifulSoup,
+ *args: Any,
+ on_duplicate_attribute: Union[str, _DuplicateAttributeHandler] = REPLACE,
+ **kwargs: Any,
+ ):
+ self.soup = soup
+ self.on_duplicate_attribute = on_duplicate_attribute
+ self.attribute_dict_class = soup.builder.attribute_dict_class
+ HTMLParser.__init__(self, *args, **kwargs)
+
+ # Keep a list of empty-element tags that were encountered
+ # without an explicit closing tag. If we encounter a closing tag
+ # of this type, we'll associate it with one of those entries.
+ #
+ # This isn't a stack because we don't care about the
+ # order. It's a list of closing tags we've already handled and
+ # will ignore, assuming they ever show up.
+ self.already_closed_empty_element = []
+
+ self._initialize_xml_detector()
+
+ on_duplicate_attribute: Union[str, _DuplicateAttributeHandler]
+ already_closed_empty_element: List[str]
+ soup: BeautifulSoup
+
+ def error(self, message: str) -> None:
+ # NOTE: This method is required so long as Python 3.9 is
+ # supported. The corresponding code is removed from HTMLParser
+ # in 3.5, but not removed from ParserBase until 3.10.
+ # https://github.com/python/cpython/issues/76025
+ #
+ # The original implementation turned the error into a warning,
+ # but in every case I discovered, this made HTMLParser
+ # immediately crash with an error message that was less
+ # helpful than the warning. The new implementation makes it
+ # more clear that html.parser just can't parse this
+ # markup. The 3.10 implementation does the same, though it
+ # raises AssertionError rather than calling a method. (We
+ # catch this error and wrap it in a ParserRejectedMarkup.)
+ raise ParserRejectedMarkup(message)
+
+ def handle_startendtag(
+ self, tag: str, attrs: List[Tuple[str, Optional[str]]]
+ ) -> None:
+ """Handle an incoming empty-element tag.
+
+ html.parser only calls this method when the markup looks like
+ .
+ """
+ # `handle_empty_element` tells handle_starttag not to close the tag
+ # just because its name matches a known empty-element tag. We
+ # know that this is an empty-element tag, and we want to call
+ # handle_endtag ourselves.
+ self.handle_starttag(tag, attrs, handle_empty_element=False)
+ self.handle_endtag(tag)
+
+ def handle_starttag(
+ self,
+ tag: str,
+ attrs: List[Tuple[str, Optional[str]]],
+ handle_empty_element: bool = True,
+ ) -> None:
+ """Handle an opening tag, e.g. ''
+
+ :param handle_empty_element: True if this tag is known to be
+ an empty-element tag (i.e. there is not expected to be any
+ closing tag).
+ """
+ # TODO: handle namespaces here?
+ attr_dict: AttributeDict = self.attribute_dict_class()
+ for key, value in attrs:
+ # Change None attribute values to the empty string
+ # for consistency with the other tree builders.
+ if value is None:
+ value = ""
+ if key in attr_dict:
+ # A single attribute shows up multiple times in this
+ # tag. How to handle it depends on the
+ # on_duplicate_attribute setting.
+ on_dupe = self.on_duplicate_attribute
+ if on_dupe == self.IGNORE:
+ pass
+ elif on_dupe in (None, self.REPLACE):
+ attr_dict[key] = value
+ else:
+ on_dupe = cast(_DuplicateAttributeHandler, on_dupe)
+ on_dupe(attr_dict, key, value)
+ else:
+ attr_dict[key] = value
+ # print("START", tag)
+ sourceline: Optional[int]
+ sourcepos: Optional[int]
+ if self.soup.builder.store_line_numbers:
+ sourceline, sourcepos = self.getpos()
+ else:
+ sourceline = sourcepos = None
+ tagObj = self.soup.handle_starttag(
+ tag, None, None, attr_dict, sourceline=sourceline, sourcepos=sourcepos
+ )
+ if tagObj is not None and tagObj.is_empty_element and handle_empty_element:
+ # Unlike other parsers, html.parser doesn't send separate end tag
+ # events for empty-element tags. (It's handled in
+ # handle_startendtag, but only if the original markup looked like
+ # .)
+ #
+ # So we need to call handle_endtag() ourselves. Since we
+ # know the start event is identical to the end event, we
+ # don't want handle_endtag() to cross off any previous end
+ # events for tags of this name.
+ self.handle_endtag(tag, check_already_closed=False)
+
+ # But we might encounter an explicit closing tag for this tag
+ # later on. If so, we want to ignore it.
+ self.already_closed_empty_element.append(tag)
+
+ if self._root_tag_name is None:
+ self._root_tag_encountered(tag)
+
+ def handle_endtag(self, tag: str, check_already_closed: bool = True) -> None:
+ """Handle a closing tag, e.g. ' '
+
+ :param tag: A tag name.
+ :param check_already_closed: True if this tag is expected to
+ be the closing portion of an empty-element tag,
+ e.g. ' '.
+ """
+ # print("END", tag)
+ if check_already_closed and tag in self.already_closed_empty_element:
+ # This is a redundant end tag for an empty-element tag.
+ # We've already called handle_endtag() for it, so just
+ # check it off the list.
+ # print("ALREADY CLOSED", tag)
+ self.already_closed_empty_element.remove(tag)
+ else:
+ self.soup.handle_endtag(tag)
+
+ def handle_data(self, data: str) -> None:
+ """Handle some textual data that shows up between tags."""
+ self.soup.handle_data(data)
+
+ def handle_charref(self, name: str) -> None:
+ """Handle a numeric character reference by converting it to the
+ corresponding Unicode character and treating it as textual
+ data.
+
+ :param name: Character number, possibly in hexadecimal.
+ """
+ # TODO: This was originally a workaround for a bug in
+ # HTMLParser. (http://bugs.python.org/issue13633) The bug has
+ # been fixed, but removing this code still makes some
+ # Beautiful Soup tests fail. This needs investigation.
+ real_name:int
+ if name.startswith("x"):
+ real_name = int(name.lstrip("x"), 16)
+ elif name.startswith("X"):
+ real_name = int(name.lstrip("X"), 16)
+ else:
+ real_name = int(name)
+
+ data, replacement_added = UnicodeDammit.numeric_character_reference(real_name)
+ if replacement_added:
+ self.soup.contains_replacement_characters = True
+ self.handle_data(data)
+
+ def handle_entityref(self, name: str) -> None:
+ """Handle a named entity reference by converting it to the
+ corresponding Unicode character(s) and treating it as textual
+ data.
+
+ :param name: Name of the entity reference.
+ """
+ character = EntitySubstitution.HTML_ENTITY_TO_CHARACTER.get(name)
+ if character is not None:
+ data = character
+ else:
+ # If this were XML, it would be ambiguous whether "&foo"
+ # was an character entity reference with a missing
+ # semicolon or the literal string "&foo". Since this is
+ # HTML, we have a complete list of all character entity references,
+ # and this one wasn't found, so assume it's the literal string "&foo".
+ data = "&%s" % name
+ self.handle_data(data)
+
+ def handle_comment(self, data: str) -> None:
+ """Handle an HTML comment.
+
+ :param data: The text of the comment.
+ """
+ self.soup.endData()
+ self.soup.handle_data(data)
+ self.soup.endData(Comment)
+
+ def handle_decl(self, decl: str) -> None:
+ """Handle a DOCTYPE declaration.
+
+ :param data: The text of the declaration.
+ """
+ self.soup.endData()
+ decl = decl[len("DOCTYPE ") :]
+ self.soup.handle_data(decl)
+ self.soup.endData(Doctype)
+
+ def unknown_decl(self, data: str) -> None:
+ """Handle a declaration of unknown type -- probably a CDATA block.
+
+ :param data: The text of the declaration.
+ """
+ cls: Type[NavigableString]
+ if data.upper().startswith("CDATA["):
+ cls = CData
+ data = data[len("CDATA[") :]
+ else:
+ cls = Declaration
+ self.soup.endData()
+ self.soup.handle_data(data)
+ self.soup.endData(cls)
+
+ def handle_pi(self, data: str) -> None:
+ """Handle a processing instruction.
+
+ :param data: The text of the instruction.
+ """
+ self.soup.endData()
+ self.soup.handle_data(data)
+ self._document_might_be_xml(data)
+ self.soup.endData(ProcessingInstruction)
+
+
+class HTMLParserTreeBuilder(HTMLTreeBuilder):
+ """A Beautiful soup `bs4.builder.TreeBuilder` that uses the
+ :py:class:`html.parser.HTMLParser` parser, found in the Python
+ standard library.
+
+ """
+
+ is_xml: bool = False
+ picklable: bool = True
+ NAME: str = HTMLPARSER
+ features: Iterable[str] = [NAME, HTML, STRICT]
+ parser_args: Tuple[Iterable[Any], Dict[str, Any]]
+
+ #: The html.parser knows which line number and position in the
+ #: original file is the source of an element.
+ TRACKS_LINE_NUMBERS: bool = True
+
+ def __init__(
+ self,
+ parser_args: Optional[Iterable[Any]] = None,
+ parser_kwargs: Optional[Dict[str, Any]] = None,
+ **kwargs: Any,
+ ):
+ """Constructor.
+
+ :param parser_args: Positional arguments to pass into
+ the BeautifulSoupHTMLParser constructor, once it's
+ invoked.
+ :param parser_kwargs: Keyword arguments to pass into
+ the BeautifulSoupHTMLParser constructor, once it's
+ invoked.
+ :param kwargs: Keyword arguments for the superclass constructor.
+ """
+ # Some keyword arguments will be pulled out of kwargs and placed
+ # into parser_kwargs.
+ extra_parser_kwargs = dict()
+ for arg in ("on_duplicate_attribute",):
+ if arg in kwargs:
+ value = kwargs.pop(arg)
+ extra_parser_kwargs[arg] = value
+ super(HTMLParserTreeBuilder, self).__init__(**kwargs)
+ parser_args = parser_args or []
+ parser_kwargs = parser_kwargs or {}
+ parser_kwargs.update(extra_parser_kwargs)
+ parser_kwargs["convert_charrefs"] = False
+ self.parser_args = (parser_args, parser_kwargs)
+
+ def prepare_markup(
+ self,
+ markup: _RawMarkup,
+ user_specified_encoding: Optional[_Encoding] = None,
+ document_declared_encoding: Optional[_Encoding] = None,
+ exclude_encodings: Optional[_Encodings] = None,
+ ) -> Iterable[Tuple[str, Optional[_Encoding], Optional[_Encoding], bool]]:
+ """Run any preliminary steps necessary to make incoming markup
+ acceptable to the parser.
+
+ :param markup: Some markup -- probably a bytestring.
+ :param user_specified_encoding: The user asked to try this encoding.
+ :param document_declared_encoding: The markup itself claims to be
+ in this encoding.
+ :param exclude_encodings: The user asked _not_ to try any of
+ these encodings.
+
+ :yield: A series of 4-tuples: (markup, encoding, declared encoding,
+ has undergone character replacement)
+
+ Each 4-tuple represents a strategy for parsing the document.
+ This TreeBuilder uses Unicode, Dammit to convert the markup
+ into Unicode, so the ``markup`` element of the tuple will
+ always be a string.
+ """
+ if isinstance(markup, str):
+ # Parse Unicode as-is.
+ yield (markup, None, None, False)
+ return
+
+ # Ask UnicodeDammit to sniff the most likely encoding.
+
+ known_definite_encodings: List[_Encoding] = []
+ if user_specified_encoding:
+ # This was provided by the end-user; treat it as a known
+ # definite encoding per the algorithm laid out in the
+ # HTML5 spec. (See the EncodingDetector class for
+ # details.)
+ known_definite_encodings.append(user_specified_encoding)
+
+ user_encodings: List[_Encoding] = []
+ if document_declared_encoding:
+ # This was found in the document; treat it as a slightly
+ # lower-priority user encoding.
+ user_encodings.append(document_declared_encoding)
+
+ dammit = UnicodeDammit(
+ markup,
+ known_definite_encodings=known_definite_encodings,
+ user_encodings=user_encodings,
+ is_html=True,
+ exclude_encodings=exclude_encodings,
+ )
+
+ if dammit.unicode_markup is None:
+ # In every case I've seen, Unicode, Dammit is able to
+ # convert the markup into Unicode, even if it needs to use
+ # REPLACEMENT CHARACTER. But there is a code path that
+ # could result in unicode_markup being None, and
+ # HTMLParser can only parse Unicode, so here we handle
+ # that code path.
+ raise ParserRejectedMarkup(
+ "Could not convert input to Unicode, and html.parser will not accept bytestrings."
+ )
+ else:
+ yield (
+ dammit.unicode_markup,
+ dammit.original_encoding,
+ dammit.declared_html_encoding,
+ dammit.contains_replacement_characters,
+ )
+
+ def feed(self, markup: _RawMarkup, _parser_class:type[BeautifulSoupHTMLParser] =BeautifulSoupHTMLParser) -> None:
+ """
+ :param markup: The markup to feed into the parser.
+ :param _parser_class: An HTMLParser subclass to use. This is only intended for use in unit tests.
+ """
+ args, kwargs = self.parser_args
+
+ # HTMLParser.feed will only handle str, but
+ # BeautifulSoup.markup is allowed to be _RawMarkup, because
+ # it's set by the yield value of
+ # TreeBuilder.prepare_markup. Fortunately,
+ # HTMLParserTreeBuilder.prepare_markup always yields a str
+ # (UnicodeDammit.unicode_markup).
+ assert isinstance(markup, str)
+
+ # We know BeautifulSoup calls TreeBuilder.initialize_soup
+ # before calling feed(), so we can assume self.soup
+ # is set.
+ assert self.soup is not None
+ parser = _parser_class(self.soup, *args, **kwargs)
+
+ try:
+ parser.feed(markup)
+ parser.close()
+ except AssertionError as e:
+ # html.parser raises AssertionError in rare cases to
+ # indicate a fatal problem with the markup, especially
+ # when there's an error in the doctype declaration.
+ raise ParserRejectedMarkup(e)
+ parser.already_closed_empty_element = []
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/_lxml.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/_lxml.py
new file mode 100644
index 0000000000000000000000000000000000000000..264d86147840ed583e3f6816fab3d47b58d814cc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/bs4/builder/_lxml.py
@@ -0,0 +1,501 @@
+# encoding: utf-8
+from __future__ import annotations
+
+# Use of this source code is governed by the MIT license.
+__license__ = "MIT"
+
+__all__ = [
+ "LXMLTreeBuilderForXML",
+ "LXMLTreeBuilder",
+]
+
+
+from typing import (
+ Any,
+ Dict,
+ Iterable,
+ List,
+ Optional,
+ Set,
+ Tuple,
+ Type,
+ TYPE_CHECKING,
+ Union,
+)
+
+from io import BytesIO
+from io import StringIO
+
+from typing_extensions import TypeAlias
+
+from lxml import etree # type:ignore
+from bs4.element import (
+ AttributeDict,
+ XMLAttributeDict,
+ Comment,
+ Doctype,
+ NamespacedAttribute,
+ ProcessingInstruction,
+ XMLProcessingInstruction,
+)
+from bs4.builder import (
+ DetectsXMLParsedAsHTML,
+ FAST,
+ HTML,
+ HTMLTreeBuilder,
+ PERMISSIVE,
+ TreeBuilder,
+ XML,
+)
+from bs4.dammit import EncodingDetector
+from bs4.exceptions import ParserRejectedMarkup
+
+if TYPE_CHECKING:
+ from bs4._typing import (
+ _Encoding,
+ _Encodings,
+ _NamespacePrefix,
+ _NamespaceURL,
+ _NamespaceMapping,
+ _InvertedNamespaceMapping,
+ _RawMarkup,
+ )
+ from bs4 import BeautifulSoup
+
+LXML: str = "lxml"
+
+
+def _invert(d: dict[Any, Any]) -> dict[Any, Any]:
+ "Invert a dictionary."
+ return dict((v, k) for k, v in list(d.items()))
+
+
+_LXMLParser: TypeAlias = Union[etree.XMLParser, etree.HTMLParser]
+_ParserOrParserClass: TypeAlias = Union[
+ _LXMLParser, Type[etree.XMLParser], Type[etree.HTMLParser]
+]
+
+
+class LXMLTreeBuilderForXML(TreeBuilder):
+ DEFAULT_PARSER_CLASS: Type[etree.XMLParser] = etree.XMLParser
+
+ is_xml: bool = True
+
+ #: Set this to true (probably by passing huge_tree=True into the :
+ #: BeautifulSoup constructor) to enable the lxml feature "disable security
+ #: restrictions and support very deep trees and very long text
+ #: content".
+ huge_tree: bool
+
+ processing_instruction_class: Type[ProcessingInstruction]
+
+ NAME: str = "lxml-xml"
+ ALTERNATE_NAMES: Iterable[str] = ["xml"]
+
+ # Well, it's permissive by XML parser standards.
+ features: Iterable[str] = [NAME, LXML, XML, FAST, PERMISSIVE]
+
+ CHUNK_SIZE: int = 512
+
+ # This namespace mapping is specified in the XML Namespace
+ # standard.
+ DEFAULT_NSMAPS: _NamespaceMapping = dict(xml="http://www.w3.org/XML/1998/namespace")
+
+ DEFAULT_NSMAPS_INVERTED: _InvertedNamespaceMapping = _invert(DEFAULT_NSMAPS)
+
+ nsmaps: List[Optional[_InvertedNamespaceMapping]]
+ empty_element_tags: Optional[Set[str]]
+ parser: Any
+ _default_parser: Optional[etree.XMLParser]
+
+ # NOTE: If we parsed Element objects and looked at .sourceline,
+ # we'd be able to see the line numbers from the original document.
+ # But instead we build an XMLParser or HTMLParser object to serve
+ # as the target of parse messages, and those messages don't include
+ # line numbers.
+ # See: https://bugs.launchpad.net/lxml/+bug/1846906
+
+ def initialize_soup(self, soup: BeautifulSoup) -> None:
+ """Let the BeautifulSoup object know about the standard namespace
+ mapping.
+
+ :param soup: A `BeautifulSoup`.
+ """
+ # Beyond this point, self.soup is set, so we can assume (and
+ # assert) it's not None whenever necessary.
+ super(LXMLTreeBuilderForXML, self).initialize_soup(soup)
+ self._register_namespaces(self.DEFAULT_NSMAPS)
+
+ def _register_namespaces(self, mapping: Dict[str, str]) -> None:
+ """Let the BeautifulSoup object know about namespaces encountered
+ while parsing the document.
+
+ This might be useful later on when creating CSS selectors.
+
+ This will track (almost) all namespaces, even ones that were
+ only in scope for part of the document. If two namespaces have
+ the same prefix, only the first one encountered will be
+ tracked. Un-prefixed namespaces are not tracked.
+
+ :param mapping: A dictionary mapping namespace prefixes to URIs.
+ """
+ assert self.soup is not None
+ for key, value in list(mapping.items()):
+ # This is 'if key' and not 'if key is not None' because we
+ # don't track un-prefixed namespaces. Soupselect will
+ # treat an un-prefixed namespace as the default, which
+ # causes confusion in some cases.
+ if key and key not in self.soup._namespaces:
+ # Let the BeautifulSoup object know about a new namespace.
+ # If there are multiple namespaces defined with the same
+ # prefix, the first one in the document takes precedence.
+ self.soup._namespaces[key] = value
+
+ def default_parser(self, encoding: Optional[_Encoding]) -> _ParserOrParserClass:
+ """Find the default parser for the given encoding.
+
+ :return: Either a parser object or a class, which
+ will be instantiated with default arguments.
+ """
+ if self._default_parser is not None:
+ return self._default_parser
+ return self.DEFAULT_PARSER_CLASS(target=self, recover=True, huge_tree=self.huge_tree, encoding=encoding)
+
+ def parser_for(self, encoding: Optional[_Encoding]) -> _LXMLParser:
+ """Instantiate an appropriate parser for the given encoding.
+
+ :param encoding: A string.
+ :return: A parser object such as an `etree.XMLParser`.
+ """
+ # Use the default parser.
+ parser = self.default_parser(encoding)
+
+ if callable(parser):
+ # Instantiate the parser with default arguments
+ parser = parser(target=self, recover=True, huge_tree=self.huge_tree, encoding=encoding)
+ return parser
+
+ def __init__(
+ self,
+ parser: Optional[etree.XMLParser] = None,
+ empty_element_tags: Optional[Set[str]] = None,
+ huge_tree: bool = False,
+ **kwargs: Any,
+ ):
+ # TODO: Issue a warning if parser is present but not a
+ # callable, since that means there's no way to create new
+ # parsers for different encodings.
+ self._default_parser = parser
+ self.soup = None
+ self.nsmaps = [self.DEFAULT_NSMAPS_INVERTED]
+ self.active_namespace_prefixes = [dict(self.DEFAULT_NSMAPS)]
+ if self.is_xml:
+ self.processing_instruction_class = XMLProcessingInstruction
+ else:
+ self.processing_instruction_class = ProcessingInstruction
+
+ if "attribute_dict_class" not in kwargs:
+ kwargs["attribute_dict_class"] = XMLAttributeDict
+ self.huge_tree = huge_tree
+
+ super(LXMLTreeBuilderForXML, self).__init__(**kwargs)
+
+ def _getNsTag(self, tag: str) -> Tuple[Optional[str], str]:
+ # Split the namespace URL out of a fully-qualified lxml tag
+ # name. Copied from lxml's src/lxml/sax.py.
+ if tag[0] == "{" and "}" in tag:
+ namespace, name = tag[1:].split("}", 1)
+ return (namespace, name)
+ return (None, tag)
+
+ def prepare_markup(
+ self,
+ markup: _RawMarkup,
+ user_specified_encoding: Optional[_Encoding] = None,
+ document_declared_encoding: Optional[_Encoding] = None,
+ exclude_encodings: Optional[_Encodings] = None,
+ ) -> Iterable[
+ Tuple[Union[str, bytes], Optional[_Encoding], Optional[_Encoding], bool]
+ ]:
+ """Run any preliminary steps necessary to make incoming markup
+ acceptable to the parser.
+
+ lxml really wants to get a bytestring and convert it to
+ Unicode itself. So instead of using UnicodeDammit to convert
+ the bytestring to Unicode using different encodings, this
+ implementation uses EncodingDetector to iterate over the
+ encodings, and tell lxml to try to parse the document as each
+ one in turn.
+
+ :param markup: Some markup -- hopefully a bytestring.
+ :param user_specified_encoding: The user asked to try this encoding.
+ :param document_declared_encoding: The markup itself claims to be
+ in this encoding.
+ :param exclude_encodings: The user asked _not_ to try any of
+ these encodings.
+
+ :yield: A series of 4-tuples: (markup, encoding, declared encoding,
+ has undergone character replacement)
+
+ Each 4-tuple represents a strategy for converting the
+ document to Unicode and parsing it. Each strategy will be tried
+ in turn.
+ """
+ if not self.is_xml:
+ # We're in HTML mode, so if we're given XML, that's worth
+ # noting.
+ DetectsXMLParsedAsHTML.warn_if_markup_looks_like_xml(markup, stacklevel=3)
+
+ if isinstance(markup, str):
+ # We were given Unicode. Maybe lxml can parse Unicode on
+ # this system?
+
+ # TODO: This is a workaround for
+ # https://bugs.launchpad.net/lxml/+bug/1948551.
+ # We can remove it once the upstream issue is fixed.
+ if len(markup) > 0 and markup[0] == "\N{BYTE ORDER MARK}":
+ markup = markup[1:]
+ yield markup, None, document_declared_encoding, False
+
+ if isinstance(markup, str):
+ # No, apparently not. Convert the Unicode to UTF-8 and
+ # tell lxml to parse it as UTF-8.
+ yield (markup.encode("utf8"), "utf8", document_declared_encoding, False)
+
+ # Since the document was Unicode in the first place, there
+ # is no need to try any more strategies; we know this will
+ # work.
+ return
+
+ known_definite_encodings: List[_Encoding] = []
+ if user_specified_encoding:
+ # This was provided by the end-user; treat it as a known
+ # definite encoding per the algorithm laid out in the
+ # HTML5 spec. (See the EncodingDetector class for
+ # details.)
+ known_definite_encodings.append(user_specified_encoding)
+
+ user_encodings: List[_Encoding] = []
+ if document_declared_encoding:
+ # This was found in the document; treat it as a slightly
+ # lower-priority user encoding.
+ user_encodings.append(document_declared_encoding)
+
+ detector = EncodingDetector(
+ markup,
+ known_definite_encodings=known_definite_encodings,
+ user_encodings=user_encodings,
+ is_html=not self.is_xml,
+ exclude_encodings=exclude_encodings,
+ )
+ for encoding in detector.encodings:
+ yield (detector.markup, encoding, document_declared_encoding, False)
+
+ def feed(self, markup: _RawMarkup) -> None:
+ io: Union[BytesIO, StringIO]
+ if isinstance(markup, bytes):
+ io = BytesIO(markup)
+ elif isinstance(markup, str):
+ io = StringIO(markup)
+
+ # initialize_soup is called before feed, so we know this
+ # is not None.
+ assert self.soup is not None
+
+ # Call feed() at least once, even if the markup is empty,
+ # or the parser won't be initialized.
+ data = io.read(self.CHUNK_SIZE)
+ try:
+ self.parser = self.parser_for(self.soup.original_encoding)
+ self.parser.feed(data)
+ while len(data) != 0:
+ # Now call feed() on the rest of the data, chunk by chunk.
+ data = io.read(self.CHUNK_SIZE)
+ if len(data) != 0:
+ self.parser.feed(data)
+ self.parser.close()
+ except (UnicodeDecodeError, LookupError, etree.ParserError) as e:
+ raise ParserRejectedMarkup(e)
+
+ def close(self) -> None:
+ self.nsmaps = [self.DEFAULT_NSMAPS_INVERTED]
+
+ def start(
+ self,
+ tag: str | bytes,
+ attrib: Dict[str | bytes, str | bytes],
+ nsmap: _NamespaceMapping = {},
+ ) -> None:
+ # This is called by lxml code as a result of calling
+ # BeautifulSoup.feed(), and we know self.soup is set by the time feed()
+ # is called.
+ assert self.soup is not None
+ assert isinstance(tag, str)
+
+ # We need to recreate the attribute dict for three
+ # reasons. First, for type checking, so we can assert there
+ # are no bytestrings in the keys or values. Second, because we
+ # need a mutable dict--lxml might send us an immutable
+ # dictproxy. Third, so we can handle namespaced attribute
+ # names by converting the keys to NamespacedAttributes.
+ new_attrib: Dict[Union[str, NamespacedAttribute], str] = (
+ self.attribute_dict_class()
+ )
+ for k, v in attrib.items():
+ assert isinstance(k, str)
+ assert isinstance(v, str)
+ new_attrib[k] = v
+
+ nsprefix: Optional[_NamespacePrefix] = None
+ namespace: Optional[_NamespaceURL] = None
+ # Invert each namespace map as it comes in.
+ if len(nsmap) == 0 and len(self.nsmaps) > 1:
+ # There are no new namespaces for this tag, but
+ # non-default namespaces are in play, so we need a
+ # separate tag stack to know when they end.
+ self.nsmaps.append(None)
+ elif len(nsmap) > 0:
+ # A new namespace mapping has come into play.
+
+ # First, Let the BeautifulSoup object know about it.
+ self._register_namespaces(nsmap)
+
+ # Then, add it to our running list of inverted namespace
+ # mappings.
+ self.nsmaps.append(_invert(nsmap))
+
+ # The currently active namespace prefixes have
+ # changed. Calculate the new mapping so it can be stored
+ # with all Tag objects created while these prefixes are in
+ # scope.
+ current_mapping = dict(self.active_namespace_prefixes[-1])
+ current_mapping.update(nsmap)
+
+ # We should not track un-prefixed namespaces as we can only hold one
+ # and it will be recognized as the default namespace by soupsieve,
+ # which may be confusing in some situations.
+ if "" in current_mapping:
+ del current_mapping[""]
+ self.active_namespace_prefixes.append(current_mapping)
+
+ # Also treat the namespace mapping as a set of attributes on the
+ # tag, so we can recreate it later.
+ for prefix, namespace in list(nsmap.items()):
+ attribute = NamespacedAttribute(
+ "xmlns", prefix, "http://www.w3.org/2000/xmlns/"
+ )
+ new_attrib[attribute] = namespace
+
+ # Namespaces are in play. Find any attributes that came in
+ # from lxml with namespaces attached to their names, and
+ # turn then into NamespacedAttribute objects.
+ final_attrib: AttributeDict = self.attribute_dict_class()
+ for attr, value in list(new_attrib.items()):
+ namespace, attr = self._getNsTag(attr)
+ if namespace is None:
+ final_attrib[attr] = value
+ else:
+ nsprefix = self._prefix_for_namespace(namespace)
+ attr = NamespacedAttribute(nsprefix, attr, namespace)
+ final_attrib[attr] = value
+
+ namespace, tag = self._getNsTag(tag)
+ nsprefix = self._prefix_for_namespace(namespace)
+ self.soup.handle_starttag(
+ tag,
+ namespace,
+ nsprefix,
+ final_attrib,
+ namespaces=self.active_namespace_prefixes[-1],
+ )
+
+ def _prefix_for_namespace(
+ self, namespace: Optional[_NamespaceURL]
+ ) -> Optional[_NamespacePrefix]:
+ """Find the currently active prefix for the given namespace."""
+ if namespace is None:
+ return None
+ for inverted_nsmap in reversed(self.nsmaps):
+ if inverted_nsmap is not None and namespace in inverted_nsmap:
+ return inverted_nsmap[namespace]
+ return None
+
+ def end(self, tag: str | bytes) -> None:
+ assert self.soup is not None
+ assert isinstance(tag, str)
+ self.soup.endData()
+ namespace, tag = self._getNsTag(tag)
+ nsprefix = None
+ if namespace is not None:
+ for inverted_nsmap in reversed(self.nsmaps):
+ if inverted_nsmap is not None and namespace in inverted_nsmap:
+ nsprefix = inverted_nsmap[namespace]
+ break
+ self.soup.handle_endtag(tag, nsprefix)
+ if len(self.nsmaps) > 1:
+ # This tag, or one of its parents, introduced a namespace
+ # mapping, so pop it off the stack.
+ out_of_scope_nsmap = self.nsmaps.pop()
+
+ if out_of_scope_nsmap is not None:
+ # This tag introduced a namespace mapping which is no
+ # longer in scope. Recalculate the currently active
+ # namespace prefixes.
+ self.active_namespace_prefixes.pop()
+
+ def pi(self, target: str, data: str) -> None:
+ assert self.soup is not None
+ self.soup.endData()
+ data = target + " " + data
+ self.soup.handle_data(data)
+ self.soup.endData(self.processing_instruction_class)
+
+ def data(self, data: str | bytes) -> None:
+ assert self.soup is not None
+ assert isinstance(data, str)
+ self.soup.handle_data(data)
+
+ def doctype(self, name: str, pubid: str, system: str) -> None:
+ assert self.soup is not None
+ self.soup.endData()
+ doctype_string = Doctype._string_for_name_and_ids(name, pubid, system)
+ self.soup.handle_data(doctype_string)
+ self.soup.endData(containerClass=Doctype)
+
+ def comment(self, text: str | bytes) -> None:
+ "Handle comments as Comment objects."
+ assert self.soup is not None
+ assert isinstance(text, str)
+ self.soup.endData()
+ self.soup.handle_data(text)
+ self.soup.endData(Comment)
+
+ def test_fragment_to_document(self, fragment: str) -> str:
+ """See `TreeBuilder`."""
+ return '\n%s' % fragment
+
+
+class LXMLTreeBuilder(HTMLTreeBuilder, LXMLTreeBuilderForXML):
+ NAME: str = LXML
+ ALTERNATE_NAMES: Iterable[str] = ["lxml-html"]
+
+ features: Iterable[str] = list(ALTERNATE_NAMES) + [NAME, HTML, FAST, PERMISSIVE]
+ is_xml: bool = False
+
+ def default_parser(self, encoding: Optional[_Encoding]) -> _ParserOrParserClass:
+ return etree.HTMLParser
+
+ def feed(self, markup: _RawMarkup) -> None:
+ # We know self.soup is set by the time feed() is called.
+ assert self.soup is not None
+ encoding = self.soup.original_encoding
+ try:
+ self.parser = self.parser_for(encoding)
+ self.parser.feed(markup)
+ self.parser.close()
+ except (UnicodeDecodeError, LookupError, etree.ParserError) as e:
+ raise ParserRejectedMarkup(e)
+
+ def test_fragment_to_document(self, fragment: str) -> str:
+ """See `TreeBuilder`."""
+ return "%s" % fragment
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..06ba84f5e38e568cd09cee49a799441e7f346c84
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_api.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1a3ff74885f0f5c8f51a43ce481a302f2574e27c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_api.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_async_read_write.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_async_read_write.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8da2ba7b8797b2c9942bc6f7fa2203441130378a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_async_read_write.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_error.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_error.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..87d6b681145ee3786064257eee1484f710cf7348
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_error.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_read_write.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_read_write.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..87fb89010ad82eb957115eee493d96753eb0085b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_read_write.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_soft.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_soft.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b73b14fb892be613e652c14c741fe9f994aed60d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_soft.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_unix.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_unix.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..da4c0e143aff0db6cde1fa2e091125ae1ef3bc12
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_unix.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_util.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_util.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cb1987a2f972a1f1a66f1c599cdc33b76a9b1307
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_util.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_windows.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_windows.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bb5b39c0376d8c8d4a8e43ea08202f6056e0e9bd
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/_windows.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/asyncio.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/asyncio.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f799159ae888b913f763db93a21152b07d6f1761
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/asyncio.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/version.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/version.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2f8029a3d49abc595b61469528fd34446c7f9172
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/filelock/__pycache__/version.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e31cdf8bfd8e9fca59dca969205679316b408a6b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9fc5eec4149faada70e00322a9a943461a23cc08
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/aot_autograd/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/aot_autograd/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..94f258df84ba8730208768fc44222bee4b3ebc33
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/aot_autograd/__init__.py
@@ -0,0 +1,8 @@
+# This file has moved to under torch/_functorch. It is not public API.
+# If you are not a PyTorch developer and you are relying on the following
+# imports, please file an issue.
+from torch._functorch.aot_autograd import (
+ aot_autograd_decompositions,
+ KNOWN_TYPES,
+ PytreeThunk,
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/aot_autograd/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/aot_autograd/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..28055e2a1b8a857ccb1163a7e791997dc565dd8c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/aot_autograd/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/eager_transforms/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/eager_transforms/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6052b5548f4af3dbc6d9d45b0ffe72a8d5013d41
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/eager_transforms/__init__.py
@@ -0,0 +1,7 @@
+# This file has moved to under torch/_functorch. It is not public API.
+# If you are not a PyTorch developer and you are relying on the following
+# imports, please file an issue.
+from torch._functorch.eager_transforms import (
+ _assert_wrapped_functional,
+ _unwrap_functional_tensor,
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/eager_transforms/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/eager_transforms/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7467708ba0ee914a5af1dbe6837c866e7cbc2454
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/eager_transforms/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/make_functional/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/make_functional/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3de7787df0c3304207b42b51e9fb62da9d33c7d0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/make_functional/__init__.py
@@ -0,0 +1,4 @@
+# This file has moved to under torch/_functorch. It is not public API.
+# If you are not a PyTorch developer and you are relying on the following
+# imports, please file an issue.
+from torch._functorch.make_functional import _swap_state
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/make_functional/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/make_functional/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..26124fe572e154316418b21cfa85b4bf4d73491a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/make_functional/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/vmap/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/vmap/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc90517753e50f92362ba954248e31f69f7cfcd5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/vmap/__init__.py
@@ -0,0 +1,16 @@
+# This file has moved to under torch/_functorch. It is not public API.
+# If you are not a PyTorch developer and you are relying on the following
+# imports, please file an issue.
+from torch._functorch.vmap import (
+ _add_batch_dim,
+ _broadcast_to_and_flatten,
+ _create_batched_inputs,
+ _get_name,
+ _process_batched_inputs,
+ _remove_batch_dim,
+ _unwrap_batched,
+ _validate_and_get_batch_size,
+ Tensor,
+ tree_flatten,
+ tree_unflatten,
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/vmap/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/vmap/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bc55fcb8f0c5b370a48f595d73066e91d80c4a57
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/_src/vmap/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/compile/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/compile/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7548a5ff6b91bae4fa561f0de7ad5d3492eda05
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/compile/__init__.py
@@ -0,0 +1,30 @@
+from torch._functorch import config
+from torch._functorch.aot_autograd import (
+ aot_function,
+ aot_module,
+ aot_module_simplified,
+ compiled_function,
+ compiled_module,
+ get_aot_compilation_context,
+ get_aot_graph_name,
+ get_graph_being_compiled,
+ make_boxed_compiler,
+ make_boxed_func,
+)
+from torch._functorch.compilers import (
+ debug_compile,
+ default_decompositions,
+ draw_graph_compile,
+ memory_efficient_fusion,
+ nnc_jit,
+ nop,
+ print_compile,
+ ts_compile,
+)
+from torch._functorch.fx_minifier import minifier
+from torch._functorch.partitioners import (
+ default_partition,
+ draw_graph,
+ min_cut_rematerialization_partition,
+)
+from torch._functorch.python_key import pythonkey_decompose
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/compile/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/compile/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c8efbb9fd87203adc227385fd05a26198efe650a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/compile/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6de6ad59e9501b13cf5ba934c810e53ad61f6a3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__init__.py
@@ -0,0 +1,181 @@
+import dis
+import inspect
+from typing import Sequence, Union
+
+import functorch._C
+import torch
+from functorch._C import dim as _C
+
+from .tree_map import tree_flatten, tree_map
+from .wrap_type import wrap_type
+
+
+_C._patch_tensor_class()
+dims, DimList, dimlists = _C.dims, _C.DimList, _C.dimlists
+
+
+class DimensionMismatchError(Exception):
+ pass
+
+
+class DimensionBindError(Exception):
+ pass
+
+
+from . import op_properties
+
+
+# use dict to avoid writing C++ bindings for set
+pointwise = dict.fromkeys(op_properties.pointwise, True)
+
+use_c = True
+if not use_c:
+ from . import reference
+
+
+class _Tensor:
+ # fast path around slow wrapping/unwrapping logic for simply queries used
+ # by the implementation...
+
+ @property
+ def dims(self):
+ return tuple(d for d in self._levels if isinstance(d, Dim))
+
+ def dim(self):
+ return self.ndim
+
+ if use_c:
+ __torch_function__ = classmethod(_C.__torch_function__)
+ expand = _C._instancemethod(_C.expand)
+ else:
+ __torch_function__ = reference.__torch_function__
+ expand = reference.expand
+
+ index = _C._instancemethod(_C.index)
+
+ def __repr__(self):
+ tensor, levels, ndim = self._tensor, self._levels, self.ndim
+ return f"{tensor}\nwith dims={tuple(l + ndim if isinstance(l, int) else l for l in levels)} sizes={tuple(tensor.size())}"
+
+
+TensorLike = (_Tensor, torch.Tensor)
+
+
+class Dim(_C.Dim, _Tensor):
+ # note that _C.Dim comes before tensor because we want the Dim API for things like size to take precendence.
+ # Tensor defines format, but we want to print Dims with special formatting
+ __format__ = object.__format__
+
+
+class Tensor(_Tensor, _C.Tensor):
+ if not use_c:
+ from_batched = staticmethod(_C.Tensor_from_batched)
+ from_positional = staticmethod(_C.Tensor_from_positional)
+ sum = _C._instancemethod(_C.Tensor_sum)
+
+
+def cat(tensors, dim, new_dim):
+ n = dims()
+ return stack(tensors, n, dim).index([n, dim], new_dim)
+
+
+if use_c:
+ _wrap = _C._wrap
+
+ def _def(name, *args, **kwargs):
+ orig = getattr(torch.Tensor, name)
+ setattr(_Tensor, name, _C._instancemethod(_wrap(orig, *args, **kwargs)))
+
+ t__getitem__ = _C._instancemethod(_C.__getitem__)
+ stack = _C.stack
+ split = _C._instancemethod(_C.split)
+else:
+ _wrap, _def = reference._wrap, reference._def
+ t__getitem__ = reference.t__getitem__
+ stack = reference.stack
+ split = reference.split
+
+# note: there is no python reference
+t__setitem__ = _C._instancemethod(_C.__setitem__)
+# this is patched in the C API because otherwise torch.Tensor will
+# no longer be considered a sequence and things will break
+# torch.Tensor.__getitem__ = t__getitem__
+
+_Tensor.__getitem__ = t__getitem__
+# torch.Tensor.__setitem__ = t__setitem__
+_Tensor.__setitem__ = t__setitem__
+
+torch.Tensor.split = split
+_Tensor.split = split
+torch.Tensor.expand = _C._instancemethod(_C.expand)
+torch.Tensor.index = _C._instancemethod(_C.index)
+wrap_type(use_c, _Tensor, torch.Tensor, _Tensor.__torch_function__)
+del _Tensor.ndim
+
+if use_c:
+ _Tensor.order = _C._instancemethod(_C.order)
+else:
+ _Tensor.order = reference.positional
+
+_def("mean")
+_def("sum")
+_def("all")
+_def("amax")
+_def("amin")
+_def("aminmax")
+_def("any")
+_def("count_nonzero")
+_def("logsumexp")
+_def("nanmean")
+_def("nansum")
+_def("prod")
+_def("std", keepdim_offset=2)
+_def("var", keepdim_offset=2)
+_def("max", single_dim=True)
+_def("min", single_dim=True)
+_def("argmax", single_dim=True)
+_def("argmin", single_dim=True)
+_def("kthvalue", single_dim=True)
+_def("median", single_dim=True)
+_def("nanmedian", single_dim=True)
+_def("mode", single_dim=True)
+_def("sort", reduce=False)
+_def("argsort", reduce=False)
+_def("unbind", single_dim=True)
+_def("chunk", dim_offset=1, reduce=False)
+_def("cummax", single_dim=True, reduce=False)
+_def("cummin", single_dim=True, reduce=False)
+_def("cumprod", single_dim=True, reduce=False)
+_def("cumprod_", single_dim=True, reduce=False)
+_def("cumsum", single_dim=True, reduce=False)
+_def("cumsum_", single_dim=True, reduce=False)
+_def("logcumsumexp", single_dim=True, reduce=False)
+_def("renorm", dim_offset=1, single_dim=True, reduce=False)
+_def("softmax", single_dim=True, reduce=False)
+softmax = _wrap(torch.nn.functional.softmax, single_dim=True, reduce=False)
+
+# stuff to handle in the future, because they require special
+# binding logic for dims
+# cross
+# diag_embed
+# diagonal
+# diagonal_scatter
+# diff
+# nanquantile
+# quantile
+# roll
+# rot90
+# topk (new dimes on output)
+# should these all be subsumed by inplace indexing?
+# index_add_
+# index_add
+# index_copy
+# index_copy_
+# index_fill
+# index_fill_
+# index_select
+# scatter
+# scatter_
+# scatter_add
+# scatter_add_
+# scatter_reduce
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9f43dec390d596d3bcd6e570788489d956ea5ea3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/batch_tensor.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/batch_tensor.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a550bbfc7b6bcf4fbd2733a9af46b00a177656ae
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/batch_tensor.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/delayed_mul_tensor.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/delayed_mul_tensor.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1da6a0d212c8eea8b554ee4d2a0b6183e901358b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/delayed_mul_tensor.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/dim.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/dim.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bb3b6d83f7cac7bfc5776d72de2414f5a932f580
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/dim.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/magic_trace.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/magic_trace.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..467bcb30da46e28100546184c00fb867388be85b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/magic_trace.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/op_properties.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/op_properties.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a5f1a0b6ca9210695805c4647f5618fd823977bf
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/op_properties.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/reference.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/reference.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bc2a04cf6aa0fa48a894e88d4903a13e6c7bf108
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/reference.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/tree_map.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/tree_map.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ab399cef871d0009e57b7c8cccfcbcc17ee28e0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/tree_map.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/wrap_type.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/wrap_type.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..61ea7040d5dc75804d8d216eecddeb7fbb04694d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/__pycache__/wrap_type.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/batch_tensor.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/batch_tensor.py
new file mode 100644
index 0000000000000000000000000000000000000000..dae9b270896e988151741409b666a82ba1aba5a4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/batch_tensor.py
@@ -0,0 +1,26 @@
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+from contextlib import contextmanager
+
+from torch._C._functorch import _vmap_add_layers, _vmap_remove_layers
+
+
+_enabled = False
+
+
+@contextmanager
+def _enable_layers(dims):
+ global _enabled
+ assert not _enabled
+ input = sorted((d._level, d.size) for d in dims if not isinstance(d, int))
+ n = len(input)
+ try:
+ _vmap_add_layers(input)
+ _enabled = True
+ yield
+ finally:
+ _enabled = False
+ _vmap_remove_layers(n)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/delayed_mul_tensor.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/delayed_mul_tensor.py
new file mode 100644
index 0000000000000000000000000000000000000000..3984a063885907141b56bdd2c6e8cc730c592cbb
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/delayed_mul_tensor.py
@@ -0,0 +1,77 @@
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+import torch
+
+from . import _Tensor, Tensor
+from .reference import _dims, _enable_layers, llist, ltuple
+
+
+class DelayedMulTensor(_Tensor):
+ def __init__(self, lhs, rhs):
+ self._lhs, self._rhs = lhs, rhs
+ self._data = None
+ self._levels_data = None
+ self._has_device = lhs._has_device or rhs._has_device
+ self._batchtensor_data = None
+ self._tensor_data = None
+
+ @property
+ def _levels(self):
+ if self._levels_data is None:
+ levels = llist(self._lhs._levels)
+ for l in self._rhs._levels:
+ if l not in levels:
+ levels.append(l)
+ self._levels_data = ltuple(levels)
+ return self._levels_data
+
+ @property
+ def _batchtensor(self):
+ if self._batchtensor_data is None:
+ with _enable_layers(self._levels):
+ print("bt multiply fallback")
+ self._batchtensor_data = self._lhs._batchtensor * self._rhs._batchtensor
+ return self._batchtensor_data
+
+ @property
+ def _tensor(self):
+ if self._tensor_data is None:
+ self._tensor_data = Tensor.from_batched(
+ self._batchtensor, self._has_device
+ )._tensor
+ return self._tensor_data
+
+ @property
+ def ndim(self):
+ return self._batchtensor.ndim
+
+ @property
+ def dims(self):
+ return ltuple(super().dims)
+
+ def sum(self, dim):
+ dims = _dims(dim, 0, False, False)
+ n = ord("a")
+ all_levels = self._levels
+
+ def to_char(d):
+ return chr(n + all_levels.index(d))
+
+ plhs, levelslhs = self._lhs._tensor, self._lhs._levels
+ prhs, levelsrhs = self._rhs._tensor, self._rhs._levels
+ new_dims = tuple(d for d in self.dims if d not in dims)
+ new_levels = [l for l in self._levels if l not in dims]
+ fmt = "".join(
+ [
+ *(to_char(d) for d in levelslhs),
+ ",",
+ *(to_char(d) for d in levelsrhs),
+ "->",
+ *(to_char(d) for d in new_levels),
+ ]
+ )
+ result_data = torch.einsum(fmt, (plhs, prhs))
+ return Tensor.from_positional(result_data, new_levels, True)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/dim.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/dim.py
new file mode 100644
index 0000000000000000000000000000000000000000..cbafce2f0ee0c433d82c880a81a1e34eba519a96
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/dim.py
@@ -0,0 +1,121 @@
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+import dis
+import inspect
+from dataclasses import dataclass
+from typing import Union
+
+from . import DimList
+
+
+_vmap_levels = []
+
+
+@dataclass
+class LevelInfo:
+ level: int
+ alive: bool = True
+
+
+class Dim:
+ def __init__(self, name: str, size: Union[None, int] = None):
+ self.name = name
+ self._size = None
+ self._vmap_level = None
+ if size is not None:
+ self.size = size
+
+ def __del__(self):
+ if self._vmap_level is not None:
+ _vmap_active_levels[self._vmap_stack].alive = False # noqa: F821
+ while (
+ not _vmap_levels[-1].alive
+ and current_level() == _vmap_levels[-1].level # noqa: F821
+ ):
+ _vmap_decrement_nesting() # noqa: F821
+ _vmap_levels.pop()
+
+ @property
+ def size(self):
+ assert self.is_bound
+ return self._size
+
+ @size.setter
+ def size(self, size: int):
+ from . import DimensionBindError
+
+ if self._size is None:
+ self._size = size
+ self._vmap_level = _vmap_increment_nesting(size, "same") # noqa: F821
+ self._vmap_stack = len(_vmap_levels)
+ _vmap_levels.append(LevelInfo(self._vmap_level))
+
+ elif self._size != size:
+ raise DimensionBindError(
+ f"Dim '{self}' previously bound to a dimension of size {self._size} cannot bind to a dimension of size {size}"
+ )
+
+ @property
+ def is_bound(self):
+ return self._size is not None
+
+ def __repr__(self):
+ return self.name
+
+
+def extract_name(inst):
+ assert inst.opname == "STORE_FAST" or inst.opname == "STORE_NAME"
+ return inst.argval
+
+
+_cache = {}
+
+
+def dims(lists=0):
+ frame = inspect.currentframe()
+ assert frame is not None
+ calling_frame = frame.f_back
+ assert calling_frame is not None
+ code, lasti = calling_frame.f_code, calling_frame.f_lasti
+ key = (code, lasti)
+ if key not in _cache:
+ first = lasti // 2 + 1
+ instructions = list(dis.get_instructions(calling_frame.f_code))
+ unpack = instructions[first]
+
+ if unpack.opname == "STORE_FAST" or unpack.opname == "STORE_NAME":
+ # just a single dim, not a list
+ name = unpack.argval
+ ctor = Dim if lists == 0 else DimList
+ _cache[key] = lambda: ctor(name=name)
+ else:
+ assert unpack.opname == "UNPACK_SEQUENCE"
+ ndims = unpack.argval
+ names = tuple(
+ extract_name(instructions[first + 1 + i]) for i in range(ndims)
+ )
+ first_list = len(names) - lists
+ _cache[key] = lambda: tuple(
+ Dim(n) if i < first_list else DimList(name=n)
+ for i, n in enumerate(names)
+ )
+ return _cache[key]()
+
+
+def _dim_set(positional, arg):
+ def convert(a):
+ if isinstance(a, Dim):
+ return a
+ else:
+ assert isinstance(a, int)
+ return positional[a]
+
+ if arg is None:
+ return positional
+ elif not isinstance(arg, (Dim, int)):
+ return tuple(convert(a) for a in arg)
+ else:
+ return (convert(arg),)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/magic_trace.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/magic_trace.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c962a898ca79cfe3d8af7432aacc3802d4f4ade
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/magic_trace.py
@@ -0,0 +1,42 @@
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+import os
+import signal
+import subprocess
+from contextlib import contextmanager
+
+
+@contextmanager
+def magic_trace(output="trace.fxt", magic_trace_cache="/tmp/magic-trace"):
+ pid = os.getpid()
+ if not os.path.exists(magic_trace_cache):
+ print(f"Downloading magic_trace to: {magic_trace_cache}")
+ subprocess.run(
+ [
+ "wget",
+ "-O",
+ magic_trace_cache,
+ "-q",
+ "https://github.com/janestreet/magic-trace/releases/download/v1.0.2/magic-trace",
+ ]
+ )
+ subprocess.run(["chmod", "+x", magic_trace_cache])
+ args = [magic_trace_cache, "attach", "-pid", str(pid), "-o", output]
+ p = subprocess.Popen(args, stderr=subprocess.PIPE, encoding="utf-8")
+ while True:
+ x = p.stderr.readline()
+ print(x)
+ if "Attached" in x:
+ break
+ try:
+ yield
+ finally:
+ p.send_signal(signal.SIGINT)
+ r = p.wait()
+ print(p.stderr.read())
+ p.stderr.close()
+ if r != 0:
+ raise ValueError(f"magic_trace exited abnormally: {r}")
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/op_properties.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/op_properties.py
new file mode 100644
index 0000000000000000000000000000000000000000..01313f71f030d58ce76c15c7f8516c4a0bdcf48a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/op_properties.py
@@ -0,0 +1,312 @@
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+import torch
+
+
+# pointwise operators can go through a faster pathway
+
+tensor_magic_methods = ["add", ""]
+pointwise_magic_methods_with_reverse = (
+ "add",
+ "sub",
+ "mul",
+ "floordiv",
+ "div",
+ "truediv",
+ "mod",
+ "pow",
+ "lshift",
+ "rshift",
+ "and",
+ "or",
+ "xor",
+)
+pointwise_magic_methods = (
+ *(x for m in pointwise_magic_methods_with_reverse for x in (m, "r" + m)),
+ "eq",
+ "gt",
+ "le",
+ "lt",
+ "ge",
+ "gt",
+ "ne",
+ "neg",
+ "pos",
+ "abs",
+ "invert",
+ "iadd",
+ "isub",
+ "imul",
+ "ifloordiv",
+ "idiv",
+ "itruediv",
+ "imod",
+ "ipow",
+ "ilshift",
+ "irshift",
+ "iand",
+ "ior",
+ "ixor",
+ "int",
+ "long",
+ "float",
+ "complex",
+)
+
+pointwise_methods = (*(f"__{m}__" for m in pointwise_magic_methods),)
+
+pointwise = (
+ *(getattr(torch.Tensor, m) for m in pointwise_methods),
+ torch.nn.functional.dropout,
+ torch.where,
+ torch.Tensor.abs,
+ torch.abs,
+ torch.Tensor.acos,
+ torch.acos,
+ torch.Tensor.acosh,
+ torch.acosh,
+ torch.Tensor.add,
+ torch.add,
+ torch.Tensor.addcdiv,
+ torch.addcdiv,
+ torch.Tensor.addcmul,
+ torch.addcmul,
+ torch.Tensor.addr,
+ torch.addr,
+ torch.Tensor.angle,
+ torch.angle,
+ torch.Tensor.asin,
+ torch.asin,
+ torch.Tensor.asinh,
+ torch.asinh,
+ torch.Tensor.atan,
+ torch.atan,
+ torch.Tensor.atan2,
+ torch.atan2,
+ torch.Tensor.atanh,
+ torch.atanh,
+ torch.Tensor.bitwise_and,
+ torch.bitwise_and,
+ torch.Tensor.bitwise_left_shift,
+ torch.bitwise_left_shift,
+ torch.Tensor.bitwise_not,
+ torch.bitwise_not,
+ torch.Tensor.bitwise_or,
+ torch.bitwise_or,
+ torch.Tensor.bitwise_right_shift,
+ torch.bitwise_right_shift,
+ torch.Tensor.bitwise_xor,
+ torch.bitwise_xor,
+ torch.Tensor.ceil,
+ torch.ceil,
+ torch.celu,
+ torch.nn.functional.celu,
+ torch.Tensor.clamp,
+ torch.clamp,
+ torch.Tensor.clamp_max,
+ torch.clamp_max,
+ torch.Tensor.clamp_min,
+ torch.clamp_min,
+ torch.Tensor.copysign,
+ torch.copysign,
+ torch.Tensor.cos,
+ torch.cos,
+ torch.Tensor.cosh,
+ torch.cosh,
+ torch.Tensor.deg2rad,
+ torch.deg2rad,
+ torch.Tensor.digamma,
+ torch.digamma,
+ torch.Tensor.div,
+ torch.div,
+ torch.dropout,
+ torch.nn.functional.dropout,
+ torch.nn.functional.elu,
+ torch.Tensor.eq,
+ torch.eq,
+ torch.Tensor.erf,
+ torch.erf,
+ torch.Tensor.erfc,
+ torch.erfc,
+ torch.Tensor.erfinv,
+ torch.erfinv,
+ torch.Tensor.exp,
+ torch.exp,
+ torch.Tensor.exp2,
+ torch.exp2,
+ torch.Tensor.expm1,
+ torch.expm1,
+ torch.feature_dropout,
+ torch.Tensor.float_power,
+ torch.float_power,
+ torch.Tensor.floor,
+ torch.floor,
+ torch.Tensor.floor_divide,
+ torch.floor_divide,
+ torch.Tensor.fmod,
+ torch.fmod,
+ torch.Tensor.frac,
+ torch.frac,
+ torch.Tensor.frexp,
+ torch.frexp,
+ torch.Tensor.gcd,
+ torch.gcd,
+ torch.Tensor.ge,
+ torch.ge,
+ torch.nn.functional.gelu,
+ torch.nn.functional.glu,
+ torch.Tensor.gt,
+ torch.gt,
+ torch.Tensor.hardshrink,
+ torch.hardshrink,
+ torch.nn.functional.hardshrink,
+ torch.nn.functional.hardsigmoid,
+ torch.nn.functional.hardswish,
+ torch.nn.functional.hardtanh,
+ torch.Tensor.heaviside,
+ torch.heaviside,
+ torch.Tensor.hypot,
+ torch.hypot,
+ torch.Tensor.i0,
+ torch.i0,
+ torch.Tensor.igamma,
+ torch.igamma,
+ torch.Tensor.igammac,
+ torch.igammac,
+ torch.Tensor.isclose,
+ torch.isclose,
+ torch.Tensor.isfinite,
+ torch.isfinite,
+ torch.Tensor.isinf,
+ torch.isinf,
+ torch.Tensor.isnan,
+ torch.isnan,
+ torch.Tensor.isneginf,
+ torch.isneginf,
+ torch.Tensor.isposinf,
+ torch.isposinf,
+ torch.Tensor.isreal,
+ torch.isreal,
+ torch.Tensor.kron,
+ torch.kron,
+ torch.Tensor.lcm,
+ torch.lcm,
+ torch.Tensor.ldexp,
+ torch.ldexp,
+ torch.Tensor.le,
+ torch.le,
+ torch.nn.functional.leaky_relu,
+ torch.Tensor.lerp,
+ torch.lerp,
+ torch.Tensor.lgamma,
+ torch.lgamma,
+ torch.Tensor.log,
+ torch.log,
+ torch.Tensor.log10,
+ torch.log10,
+ torch.Tensor.log1p,
+ torch.log1p,
+ torch.Tensor.log2,
+ torch.log2,
+ torch.nn.functional.logsigmoid,
+ torch.Tensor.logical_and,
+ torch.logical_and,
+ torch.Tensor.logical_not,
+ torch.logical_not,
+ torch.Tensor.logical_or,
+ torch.logical_or,
+ torch.Tensor.logical_xor,
+ torch.logical_xor,
+ torch.Tensor.logit,
+ torch.logit,
+ torch.Tensor.lt,
+ torch.lt,
+ torch.Tensor.maximum,
+ torch.maximum,
+ torch.Tensor.minimum,
+ torch.minimum,
+ torch.nn.functional.mish,
+ torch.Tensor.mvlgamma,
+ torch.mvlgamma,
+ torch.Tensor.nan_to_num,
+ torch.nan_to_num,
+ torch.Tensor.ne,
+ torch.ne,
+ torch.Tensor.neg,
+ torch.neg,
+ torch.Tensor.nextafter,
+ torch.nextafter,
+ torch.Tensor.outer,
+ torch.outer,
+ torch.polar,
+ torch.Tensor.polygamma,
+ torch.polygamma,
+ torch.Tensor.positive,
+ torch.positive,
+ torch.Tensor.pow,
+ torch.pow,
+ torch.Tensor.prelu,
+ torch.prelu,
+ torch.nn.functional.prelu,
+ torch.Tensor.rad2deg,
+ torch.rad2deg,
+ torch.Tensor.reciprocal,
+ torch.reciprocal,
+ torch.Tensor.relu,
+ torch.relu,
+ torch.nn.functional.relu,
+ torch.nn.functional.relu6,
+ torch.Tensor.remainder,
+ torch.remainder,
+ torch.Tensor.round,
+ torch.round,
+ torch.rrelu,
+ torch.nn.functional.rrelu,
+ torch.Tensor.rsqrt,
+ torch.rsqrt,
+ torch.rsub,
+ torch.selu,
+ torch.nn.functional.selu,
+ torch.Tensor.sgn,
+ torch.sgn,
+ torch.Tensor.sigmoid,
+ torch.sigmoid,
+ torch.nn.functional.sigmoid,
+ torch.Tensor.sign,
+ torch.sign,
+ torch.Tensor.signbit,
+ torch.signbit,
+ torch.nn.functional.silu,
+ torch.Tensor.sin,
+ torch.sin,
+ torch.Tensor.sinc,
+ torch.sinc,
+ torch.Tensor.sinh,
+ torch.sinh,
+ torch.nn.functional.softplus,
+ torch.nn.functional.softshrink,
+ torch.Tensor.sqrt,
+ torch.sqrt,
+ torch.Tensor.square,
+ torch.square,
+ torch.Tensor.sub,
+ torch.sub,
+ torch.Tensor.tan,
+ torch.tan,
+ torch.Tensor.tanh,
+ torch.tanh,
+ torch.nn.functional.tanh,
+ torch.threshold,
+ torch.nn.functional.threshold,
+ torch.trapz,
+ torch.Tensor.true_divide,
+ torch.true_divide,
+ torch.Tensor.trunc,
+ torch.trunc,
+ torch.Tensor.xlogy,
+ torch.xlogy,
+ torch.rand_like,
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/reference.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/reference.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed7275bf666addb09bb8f4ae498df6de91d91273
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/reference.py
@@ -0,0 +1,645 @@
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# reference python implementations for C ops
+import torch
+from functorch._C import dim as _C
+
+from . import op_properties
+from .batch_tensor import _enable_layers
+from .tree_map import tree_flatten, tree_map
+
+
+DimList = _C.DimList
+import operator
+from functools import reduce
+
+
+# use dict to avoid writing C++ bindings for set
+pointwise = set(op_properties.pointwise)
+
+
+def prod(x):
+ return reduce(operator.mul, x, 1)
+
+
+def _wrap_dim(d, N, keepdim):
+ from . import Dim
+
+ if isinstance(d, Dim):
+ assert not keepdim, "cannot preserve first-class dimensions with keepdim=True"
+ return d
+ elif d >= 0:
+ return d - N
+ else:
+ return d
+
+
+def _dims(d, N, keepdim, single_dim):
+ from . import Dim
+
+ if isinstance(d, (Dim, int)):
+ return ltuple((_wrap_dim(d, N, keepdim),))
+ assert not single_dim, f"expected a single dimension or int but found: {d}"
+ return ltuple(_wrap_dim(x, N, keepdim) for x in d)
+
+
+def _bind_dims_to_size(lhs_size, rhs, lhs_debug):
+ from . import DimensionMismatchError
+
+ not_bound = tuple((i, r) for i, r in enumerate(rhs) if not r.is_bound)
+ if len(not_bound) == 1:
+ idx, d = not_bound[0]
+ rhs_so_far = prod(r.size for r in rhs if r.is_bound)
+ if lhs_size % rhs_so_far != 0:
+ rhs_s = tuple("?" if not r.is_bound else str(r.size) for r in rhs)
+ raise DimensionMismatchError(
+ f"inferred dimension does not evenly fit into larger dimension: {lhs_size} vs {rhs_s}"
+ )
+ new_size = lhs_size // rhs_so_far
+ d.size = new_size
+ elif len(not_bound) > 1:
+ rhs_s = tuple("?" if not r.is_bound else str(r.size) for r in rhs)
+ raise DimensionMismatchError(
+ f"cannot infer the size of two dimensions at once: {rhs} with sizes {rhs_s}"
+ )
+ else:
+ rhs_size = prod(r.size for r in rhs)
+ if lhs_size != rhs_size:
+ raise DimensionMismatchError(
+ f"Dimension sizes to do not match ({lhs_size} != {rhs_size}) when matching {lhs_debug} to {rhs}"
+ )
+
+
+def _tensor_levels(inp):
+ from . import _Tensor
+
+ if isinstance(inp, _Tensor):
+ return inp._tensor, llist(inp._levels), inp._has_device
+ else:
+ return inp, llist(range(-inp.ndim, 0)), True
+
+
+def _match_levels(v, from_levels, to_levels):
+ view = []
+ permute = []
+ requires_view = False
+ size = v.size()
+ for t in to_levels:
+ try:
+ idx = from_levels.index(t)
+ permute.append(idx)
+ view.append(size[idx])
+ except ValueError:
+ view.append(1)
+ requires_view = True
+ if permute != list(range(len(permute))):
+ v = v.permute(*permute)
+ if requires_view:
+ v = v.view(*view)
+ return v
+
+
+# make a single dimension positional but do not permute it,
+# used to do multi-tensor operators where the dim being acted on
+# should not physically move if possible
+def _positional_no_permute(self, dim, expand_dim=False):
+ from . import Tensor
+
+ ptensor, levels = self._tensor, llist(self._levels)
+ try:
+ idx = levels.index(dim)
+ except ValueError:
+ if not expand_dim:
+ raise
+ idx = 0
+ ptensor = ptensor.expand(dim.size, *ptensor.size())
+ levels.insert(0, 0)
+ idx_batched = 0
+ for i in range(idx):
+ if isinstance(levels[i], int):
+ levels[i] -= 1
+ idx_batched += 1
+ levels[idx] = -idx_batched - 1
+ return Tensor.from_positional(ptensor, levels, self._has_device), idx_batched
+
+
+def seq(a, b):
+ from . import Dim
+
+ if isinstance(a, Dim) != isinstance(b, Dim):
+ return False
+ if isinstance(a, Dim):
+ return a is b
+ else:
+ return a == b
+
+
+class isin:
+ def __contains__(self, item):
+ for x in self:
+ if seq(item, x):
+ return True
+ return False
+
+ def index(self, item):
+ for i, x in enumerate(self):
+ if seq(item, x):
+ return i
+ raise ValueError
+
+
+class llist(isin, list):
+ pass
+
+
+class ltuple(isin, tuple):
+ pass
+
+
+empty_dict = {}
+
+
+@classmethod
+def __torch_function__(self, orig, cls, args, kwargs=empty_dict):
+ from . import _Tensor, Tensor, TensorLike
+ from .delayed_mul_tensor import DelayedMulTensor
+
+ if orig is torch.Tensor.__mul__:
+ lhs, rhs = args
+ if (
+ isinstance(lhs, _Tensor)
+ and isinstance(rhs, _Tensor)
+ and lhs.ndim == 0
+ and rhs.ndim == 0
+ ):
+ return DelayedMulTensor(lhs, rhs)
+ all_dims = llist()
+ flat_args, unflatten = tree_flatten((args, kwargs))
+ device_holding_tensor = None
+ for f in flat_args:
+ if isinstance(f, _Tensor):
+ if f._has_device:
+ device_holding_tensor = f._batchtensor
+ for d in f.dims:
+ if d not in all_dims:
+ all_dims.append(d)
+
+ def unwrap(t):
+ if isinstance(t, _Tensor):
+ r = t._batchtensor
+ if device_holding_tensor is not None and not t._has_device:
+ r = r.to(device=device_holding_tensor.device)
+ return r
+ return t
+
+ if orig in pointwise:
+ result_levels = llist()
+ arg_levels = llist()
+ to_expand = []
+ for i, f in enumerate(flat_args):
+ if isinstance(f, TensorLike):
+ ptensor, levels, _ = _tensor_levels(f)
+ if (
+ isinstance(f, _Tensor)
+ and not f._has_device
+ and device_holding_tensor is not None
+ ):
+ ptensor = ptensor.to(device=device_holding_tensor.device)
+ flat_args[i] = ptensor
+ for l in levels:
+ if l not in result_levels:
+ result_levels.append(l)
+ to_expand.append((i, levels))
+
+ for i, levels in to_expand:
+ flat_args[i] = _match_levels(flat_args[i], levels, result_levels)
+ args, kwargs = unflatten(flat_args)
+ result = orig(*args, **kwargs)
+
+ def wrap(t):
+ if isinstance(t, TensorLike):
+ return Tensor.from_positional(
+ t, result_levels, device_holding_tensor is not None
+ )
+ return t
+
+ return tree_map(wrap, result)
+ else:
+
+ def wrap(t):
+ if isinstance(t, TensorLike):
+ return Tensor.from_batched(t, device_holding_tensor is not None)
+ return t
+
+ with _enable_layers(all_dims):
+ print(f"batch_tensor for {orig}")
+ args, kwargs = unflatten(unwrap(f) for f in flat_args)
+ result = orig(*args, **kwargs)
+ # print("END", orig)
+ return tree_map(wrap, result)
+
+
+def positional(self, *dims):
+ from . import Dim, DimensionBindError, Tensor
+
+ ptensor, levels = self._tensor, llist(self._levels)
+ flat_dims = llist()
+ view = []
+ needs_view = False
+ ndim = self.ndim
+ for d in dims:
+ if isinstance(d, DimList):
+ flat_dims.extend(d)
+ view.extend(e.size for e in d)
+ elif isinstance(d, Dim):
+ flat_dims.append(d)
+ view.append(d.size)
+ elif isinstance(d, int):
+ d = _wrap_dim(d, ndim, False)
+ flat_dims.append(d)
+ view.append(ptensor.size(d))
+ else:
+ flat_dims.extend(d)
+ view.append(prod(e.size for e in d))
+ needs_view = True
+
+ permute = list(range(len(levels)))
+ nflat = len(flat_dims)
+ for i, d in enumerate(flat_dims):
+ try:
+ idx = levels.index(d)
+ except ValueError as e:
+ raise DimensionBindError(
+ f"tensor of dimensions {self.dims} does not contain dim {d}"
+ ) from e
+ p = permute[idx]
+ del levels[idx]
+ del permute[idx]
+ levels.insert(i, 0)
+ permute.insert(i, p)
+ ptensor = ptensor.permute(*permute)
+ seen = 0
+ for i in range(len(levels) - 1, -1, -1):
+ if isinstance(levels[i], int):
+ seen += 1
+ levels[i] = -seen
+ result = Tensor.from_positional(ptensor, levels, self._has_device)
+ if needs_view:
+ result = result.reshape(*view, *result.size()[len(flat_dims) :])
+ return result
+
+
+def _contains_dim(input):
+ from . import Dim
+
+ for i in input:
+ if isinstance(i, Dim):
+ return True
+
+
+def expand(self, *sizes):
+ if not _contains_dim(sizes):
+ return self.__torch_function__(torch.Tensor.expand, None, (self, *sizes))
+ dims = sizes
+ sizes = [d.size for d in dims] + [-1] * self.ndim
+ self = self.expand(*sizes)
+ return self[dims]
+
+
+_not_present = object()
+
+
+def _getarg(name, offset, args, kwargs, default):
+ if len(args) > offset:
+ return args[offset]
+ return kwargs.get(name, default)
+
+
+def _patcharg(name, offset, args, kwargs, value):
+ if len(args) > offset:
+ args[offset] = value
+ else:
+ kwargs[name] = value
+
+
+def _wrap(
+ orig, dim_offset=0, keepdim_offset=1, dim_name="dim", single_dim=False, reduce=True
+):
+ from . import Dim, Tensor, TensorLike
+
+ def fn(self, *args, **kwargs):
+ dim = _getarg(dim_name, dim_offset, args, kwargs, _not_present)
+ if dim is _not_present or (single_dim and not isinstance(dim, Dim)):
+ with _enable_layers(self.dims):
+ print(f"dim fallback batch_tensor for {orig}")
+ return Tensor.from_batched(
+ orig(self._batchtensor, *args, **kwargs), self._has_device
+ )
+ keepdim = (
+ _getarg("keepdim", keepdim_offset, args, kwargs, False) if reduce else False
+ )
+ t, levels = self._tensor, llist(self._levels)
+ dims = _dims(dim, self._batchtensor.ndim, keepdim, single_dim)
+ dim_indices = tuple(levels.index(d) for d in dims)
+ if reduce and not keepdim:
+ new_levels = [l for i, l in enumerate(levels) if i not in dim_indices]
+ else:
+ new_levels = levels
+
+ if len(dim_indices) == 1:
+ dim_indices = dim_indices[
+ 0
+ ] # so that dims that really only take a single argument work...
+ args = list(args)
+ _patcharg(dim_name, dim_offset, args, kwargs, dim_indices)
+
+ def wrap(t):
+ if isinstance(t, TensorLike):
+ return Tensor.from_positional(t, new_levels, self._has_device)
+ return t
+
+ with _enable_layers(new_levels):
+ print(f"dim used batch_tensor for {orig}")
+ r = orig(t, *args, **kwargs)
+ return tree_map(wrap, r)
+
+ return fn
+
+
+def _def(name, *args, **kwargs):
+ from . import _Tensor
+
+ orig = getattr(torch.Tensor, name)
+ setattr(_Tensor, name, _wrap(orig, *args, **kwargs))
+
+
+no_slice = slice(None)
+
+_orig_getitem = torch.Tensor.__getitem__
+
+
+class dim_tracker:
+ def __init__(self) -> None:
+ self.dims = llist()
+ self.count = []
+
+ def record(self, d):
+ if d not in self.dims:
+ self.dims.append(d)
+ self.count.append(1)
+
+ def __getitem__(self, d):
+ return self.count[self.dims.index(d)]
+
+
+def t__getitem__(self, input):
+ from . import _Tensor, Dim, DimensionBindError, DimList, Tensor, TensorLike
+
+ # * bail to original example if we have a single non-Dim tensor, or a non-tensor
+ # * locate ... or an unbound tensor list, and determine its size, bind dim list
+ # (remember that None does not count to the total dim count)
+ # * bind simple dims and dim-packs to their sizes, count the number of uses of each dim,
+ # produce the re-view if needed
+ # * for each single-use dim index, replace with no_slice and mark that it will be added
+ # (keep track of whether we have to call super)
+ # * call super if needed
+ # * if we have dims to bind, bind them (it will help if we eliminated ... and None before)
+ # this handles bool indexing handling, as well as some other simple cases.
+
+ is_simple = (
+ not isinstance(input, Dim)
+ and not isinstance(input, (tuple, list))
+ and
+ # WAR for functorch bug where zero time tensors in getitem are not handled correctly.
+ not (isinstance(input, TensorLike) and input.ndim == 0)
+ )
+
+ if is_simple:
+ if isinstance(self, _Tensor):
+ return _Tensor.__torch_function__(_orig_getitem, None, (self, input))
+ else:
+ return _orig_getitem(self, input)
+
+ # can further optimize this case
+ if not isinstance(input, tuple):
+ input = [input]
+ else:
+ input = list(input)
+
+ dims_indexed = 0
+ expanding_object = None
+ dimlists = []
+ for i, s in enumerate(input):
+ if s is ... or isinstance(s, DimList) and not s.is_bound:
+ if expanding_object is not None:
+ msg = (
+ "at most one ... or unbound dimension list can exist in indexing list but"
+ f" found 2 at offsets {i} and {expanding_object}"
+ )
+ raise DimensionBindError(msg)
+ expanding_object = i
+
+ if isinstance(s, DimList):
+ dims_indexed += len(s) if s.is_bound else 0
+ dimlists.append(i)
+ elif s is not None and s is not ...:
+ dims_indexed += 1
+
+ ndim = self.ndim
+ if dims_indexed > ndim:
+ raise IndexError(
+ f"at least {dims_indexed} indices were supplied but the tensor only has {ndim} dimensions."
+ )
+ if expanding_object is not None:
+ expanding_ndims = ndim - dims_indexed
+ obj = input[expanding_object]
+ if obj is ...:
+ input[expanding_object : expanding_object + 1] = [
+ no_slice
+ ] * expanding_ndims
+ else:
+ obj.bind_len(expanding_ndims)
+ # flatten the dimslists into the indexing
+ for i in reversed(dimlists):
+ input[i : i + 1] = input[i]
+ dims_indexed = 0
+ requires_view = False
+ size = self.size()
+ view_sizes = []
+ dims_seen = dim_tracker()
+
+ def add_dims(t):
+ if not isinstance(t, _Tensor):
+ return
+ for d in t.dims:
+ dims_seen.record(d)
+
+ add_dims(self)
+ dim_packs = []
+ for i, idx in enumerate(input):
+ if idx is None:
+ input[i] = no_slice
+ view_sizes.append(1)
+ requires_view = True
+ else:
+ sz = size[dims_indexed]
+ if isinstance(idx, Dim):
+ idx.size = sz
+ dims_seen.record(idx)
+ view_sizes.append(sz)
+ elif isinstance(idx, (tuple, list)) and idx and isinstance(idx[0], Dim):
+ for d in idx:
+ dims_seen.record(idx)
+ _bind_dims_to_size(sz, idx, f"offset {i}")
+ view_sizes.extend(d.size for d in idx)
+ requires_view = True
+ dim_packs.append(i)
+ else:
+ add_dims(idx)
+ view_sizes.append(sz)
+ dims_indexed += 1
+ if requires_view:
+ self = self.view(*view_sizes)
+ for i in reversed(dim_packs):
+ input[i : i + 1] = input[i]
+
+ # currenty:
+ # input is flat, containing either Dim, or Tensor, or something valid for standard indexing
+ # self may have first-class dims as well.
+
+ # to index:
+ # drop the first class dims from self, they just become direct indices of their positions
+
+ # figure out the dimensions of the indexing tensors: union of all the dims in the tensors in the index.
+ # these dimensions will appear and need to be bound at the first place tensor occures
+
+ if isinstance(self, _Tensor):
+ ptensor_self, levels = self._tensor, list(self._levels)
+ # indices to ptensor rather than self which has first-class dimensions
+ input_it = iter(input)
+ flat_inputs = [next(input_it) if isinstance(l, int) else l for l in levels]
+ has_device = self._has_device
+ to_pad = 0
+ else:
+ ptensor_self, flat_inputs = self, input
+ to_pad = ptensor_self.ndim - len(flat_inputs)
+ has_device = True
+
+ result_levels = []
+ index_levels = []
+ tensor_insert_point = None
+ to_expand = {}
+ requires_getindex = False
+ for i, inp in enumerate(flat_inputs):
+ if isinstance(inp, Dim) and dims_seen[inp] == 1:
+ flat_inputs[i] = no_slice
+ result_levels.append(inp)
+ elif isinstance(inp, TensorLike):
+ requires_getindex = True
+ if tensor_insert_point is None:
+ tensor_insert_point = len(result_levels)
+ ptensor, levels, _ = _tensor_levels(inp)
+ to_expand[i] = levels
+ flat_inputs[i] = ptensor
+ for l in levels:
+ if l not in index_levels:
+ index_levels.append(l)
+ else:
+ requires_getindex = True
+ result_levels.append(0)
+
+ if tensor_insert_point is not None:
+ result_levels[tensor_insert_point:tensor_insert_point] = index_levels
+
+ for i, levels in to_expand.items():
+ flat_inputs[i] = _match_levels(flat_inputs[i], levels, index_levels)
+
+ if requires_getindex:
+ result = _orig_getitem(ptensor_self, flat_inputs)
+ else:
+ result = ptensor_self
+
+ next_positional = -1
+ if to_pad > 0:
+ result_levels.extend([0] * to_pad)
+ for i, r in enumerate(reversed(result_levels)):
+ if isinstance(r, int):
+ result_levels[-1 - i] = next_positional
+ next_positional -= 1
+
+ return Tensor.from_positional(result, result_levels, has_device)
+
+
+# XXX - dim is optional and can be the outer-most dimension...
+def stack(tensors, new_dim, dim=0, out=None):
+ if isinstance(dim, int):
+ return torch.stack(tensors, dim, out).index(dim, new_dim)
+ index = None
+ if out is not None:
+ out, index = _positional_no_permute(out, dim, expand_dim=True)
+ ptensors = []
+ for t in tensors:
+ pt, pi = _positional_no_permute(t, dim, expand_dim=True)
+ if index is not None and pi != index:
+ pt = pt.move_dim(pi, index)
+ else:
+ index = pi
+ ptensors.append(pt)
+ pr = torch.stack(ptensors, index, out=out)
+ return pr.index((index, index + 1), (new_dim, dim))
+
+
+_orig_split = torch.Tensor.split
+
+
+def split(self, split_size_or_sections, dim=0):
+ from . import _Tensor, Dim
+
+ if isinstance(split_size_or_sections, int) or any(
+ isinstance(t, int) for t in split_size_or_sections
+ ):
+ if isinstance(dim, Dim):
+ raise ValueError(
+ "when dim is specified as a Dim object, split sizes must also be dimensions."
+ )
+ return _orig_split(self, split_size_or_sections, dim=dim)
+
+ if isinstance(dim, Dim):
+ assert isinstance(self, _Tensor), f"Tensor does not have dimension {dim}"
+ self, dim = _positional_no_permute(self, dim)
+
+ size = self.size(dim)
+ total_bound_size = 0
+ unbound = []
+ sizes = []
+ for i, d in enumerate(split_size_or_sections):
+ if d.is_bound:
+ sizes.append(d.size)
+ total_bound_size += d.size
+ else:
+ sizes.append(0)
+ unbound.append(i)
+
+ if unbound:
+ assert (
+ total_bound_size <= size
+ ), f"result dimensions are larger than original: {total_bound_size} vs {size} ({split_size_or_sections})"
+ remaining_size = size - total_bound_size
+ chunk_size = -(-remaining_size // len(unbound))
+ for u in unbound:
+ sz = min(chunk_size, remaining_size)
+ split_size_or_sections[u].size = sz
+ sizes[u] = sz
+ remaining_size -= sz
+ else:
+ assert (
+ total_bound_size == size
+ ), f"result dimensions do not match original: {total_bound_size} vs {size} ({split_size_or_sections})"
+ return tuple(
+ t.index(dim, d)
+ for d, t in zip(split_size_or_sections, _orig_split(self, sizes, dim=dim))
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/tree_map.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/tree_map.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d2eae0582c85619e0d28e648af58cbd847eee97
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/tree_map.py
@@ -0,0 +1,15 @@
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+from functorch._C import dim
+
+
+tree_flatten = dim.tree_flatten
+
+
+def tree_map(fn, tree):
+ vs, unflatten = tree_flatten(tree)
+ return unflatten(fn(v) for v in vs)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/wrap_type.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/wrap_type.py
new file mode 100644
index 0000000000000000000000000000000000000000..aae543b91a896e2d5cef3b03d725c3d91ce1305d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/dim/wrap_type.py
@@ -0,0 +1,72 @@
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+from types import (
+ BuiltinMethodType,
+ FunctionType,
+ GetSetDescriptorType,
+ MethodDescriptorType,
+ WrapperDescriptorType,
+)
+
+from functorch._C import dim as _C
+
+
+_wrap_method = _C._wrap_method
+
+FUNC_TYPES = (
+ FunctionType,
+ MethodDescriptorType,
+ BuiltinMethodType,
+ WrapperDescriptorType,
+)
+PROPERTY_TYPES = (GetSetDescriptorType, property)
+
+
+def _py_wrap_method(orig, __torch_function__):
+ def impl(*args, **kwargs):
+ return __torch_function__(orig, None, args, kwargs)
+
+ return impl
+
+
+def wrap_type(use_c, to_patch, pattern, __torch_function__):
+ if use_c:
+ wrap_method = _wrap_method
+ else:
+ wrap_method = _py_wrap_method
+
+ all = {}
+ for t in reversed(pattern.mro()[:-1]): # skip object
+ all.update(t.__dict__)
+
+ def wrap_attr(orig):
+ return property(wrap_method(orig.__get__, __torch_function__))
+
+ for name, obj in all.items():
+ if name in (
+ "__dict__",
+ "__new__",
+ "__init__",
+ "__repr__",
+ "__weakref__",
+ "__doc__",
+ "__module__",
+ "__dir__",
+ ):
+ continue
+
+ # skip things that have been overloaded
+ # things that come from object like `__eq__` still need to be patched, however.
+ if hasattr(to_patch, name) and getattr(to_patch, name) is not getattr(
+ object, name, None
+ ):
+ continue
+
+ if isinstance(obj, FUNC_TYPES):
+ setattr(to_patch, name, wrap_method(obj, __torch_function__))
+ elif isinstance(obj, PROPERTY_TYPES):
+ setattr(to_patch, name, wrap_attr(obj))
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/einops/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/einops/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d7ac34f7a3722010fc0fde97fd1cd72e76fa88b7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/einops/__init__.py
@@ -0,0 +1,4 @@
+from .rearrange import rearrange
+
+
+__all__ = ["rearrange"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/einops/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/einops/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b3b2fb97f2b361046d17903796468f56465ad94c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/einops/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/einops/__pycache__/_parsing.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/einops/__pycache__/_parsing.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b74b6fd3f353caff3911c5c22ab4b12132a13d6b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/einops/__pycache__/_parsing.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/einops/__pycache__/rearrange.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/einops/__pycache__/rearrange.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..83b7ac204185d4281cc442c1040ff08f440e84be
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/einops/__pycache__/rearrange.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/einops/_parsing.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/einops/_parsing.py
new file mode 100644
index 0000000000000000000000000000000000000000..ffb1fc00a20ee9923f63590f522c6dad206f942b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/einops/_parsing.py
@@ -0,0 +1,303 @@
+"""Adapted from https://github.com/arogozhnikov/einops/blob/36c7bb16e57d6e57f8f3050f9e07abdf3f00469f/einops/parsing.py.
+
+MIT License
+
+Copyright (c) 2018 Alex Rogozhnikov
+
+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.
+"""
+from __future__ import annotations
+
+import keyword
+import warnings
+from typing import Collection, List, Mapping, Optional, Set, Tuple, Union
+
+
+_ellipsis: str = "\u2026" # NB, this is a single unicode symbol. String is used as it is not a list, but can be iterated
+
+
+class AnonymousAxis:
+ """Used by `ParsedExpression` to represent an axis with a size (> 1), but no associated identifier.
+
+ Note: Different instances of this class are not equal to each other, even if they have the same value.
+ """
+
+ def __init__(self, value: str) -> None:
+ self.value = int(value)
+ if self.value < 1:
+ raise ValueError(
+ f"Anonymous axis should have positive length, not {self.value}"
+ )
+
+ def __repr__(self) -> str:
+ return f"{self.value}-axis"
+
+
+class ParsedExpression:
+ """Structure containing information about one side of an `einops`-style pattern (e.g. 'b c (h w)')."""
+
+ def __init__(
+ self,
+ expression: str,
+ *,
+ allow_underscore: bool = False,
+ allow_duplicates: bool = False,
+ ) -> None:
+ """Parse the expression and store relevant metadata.
+
+ Args:
+ expression (str): the `einops`-pattern to parse
+ allow_underscore (bool): whether to allow axis identifier names to begin with an underscore
+ allow_duplicates (bool): whether to allow an identifier to appear more than once in the expression
+ """
+ self.has_ellipsis: bool = False
+ self.has_ellipsis_parenthesized: Optional[bool] = None
+ self.identifiers: Set[Union[str, AnonymousAxis]] = set()
+ # that's axes like 2, 3, 4 or 5. Axes with size 1 are exceptional and replaced with empty composition
+ self.has_non_unitary_anonymous_axes: bool = False
+ # composition keeps structure of composite axes, see how different corner cases are handled in tests
+ self.composition: List[Union[List[Union[str, AnonymousAxis]], str]] = []
+ if "." in expression:
+ if "..." not in expression:
+ raise ValueError(
+ "Expression may contain dots only inside ellipsis (...)"
+ )
+ if str.count(expression, "...") != 1 or str.count(expression, ".") != 3:
+ raise ValueError(
+ "Expression may contain dots only inside ellipsis (...); only one ellipsis for tensor "
+ )
+ expression = expression.replace("...", _ellipsis)
+ self.has_ellipsis = True
+
+ bracket_group: Optional[List[Union[str, AnonymousAxis]]] = None
+
+ def add_axis_name(x: str) -> None:
+ if x in self.identifiers:
+ if not (allow_underscore and x == "_") and not allow_duplicates:
+ raise ValueError(
+ f"Indexing expression contains duplicate dimension '{x}'"
+ )
+ if x == _ellipsis:
+ self.identifiers.add(_ellipsis)
+ if bracket_group is None:
+ self.composition.append(_ellipsis)
+ self.has_ellipsis_parenthesized = False
+ else:
+ bracket_group.append(_ellipsis)
+ self.has_ellipsis_parenthesized = True
+ else:
+ is_number = str.isdecimal(x)
+ if is_number and int(x) == 1:
+ # handling the case of anonymous axis of length 1
+ if bracket_group is None:
+ self.composition.append([])
+ else:
+ pass # no need to think about 1s inside parenthesis
+ return
+ is_axis_name, reason = self.check_axis_name_return_reason(
+ x, allow_underscore=allow_underscore
+ )
+ if not (is_number or is_axis_name):
+ raise ValueError(f"Invalid axis identifier: {x}\n{reason}")
+ axis_name: Union[str, AnonymousAxis] = (
+ AnonymousAxis(x) if is_number else x
+ )
+ self.identifiers.add(axis_name)
+ if is_number:
+ self.has_non_unitary_anonymous_axes = True
+ if bracket_group is None:
+ self.composition.append([axis_name])
+ else:
+ bracket_group.append(axis_name)
+
+ current_identifier = None
+ for char in expression:
+ if char in "() ":
+ if current_identifier is not None:
+ add_axis_name(current_identifier)
+ current_identifier = None
+ if char == "(":
+ if bracket_group is not None:
+ raise ValueError(
+ "Axis composition is one-level (brackets inside brackets not allowed)"
+ )
+ bracket_group = []
+ elif char == ")":
+ if bracket_group is None:
+ raise ValueError("Brackets are not balanced")
+ self.composition.append(bracket_group)
+ bracket_group = None
+ elif str.isalnum(char) or char in ["_", _ellipsis]:
+ if current_identifier is None:
+ current_identifier = char
+ else:
+ current_identifier += char
+ else:
+ raise ValueError(f"Unknown character '{char}'")
+
+ if bracket_group is not None:
+ raise ValueError(f"Imbalanced parentheses in expression: '{expression}'")
+ if current_identifier is not None:
+ add_axis_name(current_identifier)
+
+ @staticmethod
+ def check_axis_name_return_reason(
+ name: str, allow_underscore: bool = False
+ ) -> Tuple[bool, str]:
+ """Check if the given axis name is valid, and a message explaining why if not.
+
+ Valid axes names are python identifiers except keywords, and should not start or end with an underscore.
+
+ Args:
+ name (str): the axis name to check
+ allow_underscore (bool): whether axis names are allowed to start with an underscore
+
+ Returns:
+ Tuple[bool, str]: whether the axis name is valid, a message explaining why if not
+ """
+ if not str.isidentifier(name):
+ return False, "not a valid python identifier"
+ elif name[0] == "_" or name[-1] == "_":
+ if name == "_" and allow_underscore:
+ return True, ""
+ return False, "axis name should should not start or end with underscore"
+ else:
+ if keyword.iskeyword(name):
+ warnings.warn(
+ f"It is discouraged to use axes names that are keywords: {name}",
+ RuntimeWarning,
+ )
+ if name in ["axis"]:
+ warnings.warn(
+ "It is discouraged to use 'axis' as an axis name and will raise an error in future",
+ FutureWarning,
+ )
+ return True, ""
+
+ @staticmethod
+ def check_axis_name(name: str) -> bool:
+ """Check if the name is a valid axis name.
+
+ Args:
+ name (str): the axis name to check
+
+ Returns:
+ bool: whether the axis name is valid
+ """
+ is_valid, _ = ParsedExpression.check_axis_name_return_reason(name)
+ return is_valid
+
+
+def parse_pattern(
+ pattern: str, axes_lengths: Mapping[str, int]
+) -> Tuple[ParsedExpression, ParsedExpression]:
+ """Parse an `einops`-style pattern into a left-hand side and right-hand side `ParsedExpression` object.
+
+ Args:
+ pattern (str): the `einops`-style rearrangement pattern
+ axes_lengths (Mapping[str, int]): any additional length specifications for dimensions
+
+ Returns:
+ Tuple[ParsedExpression, ParsedExpression]: a tuple containing the left-hand side and right-hand side expressions
+ """
+ # adapted from einops.einops._prepare_transformation_recipe
+ # https://github.com/arogozhnikov/einops/blob/230ac1526c1f42c9e1f7373912c7f8047496df11/einops/einops.py
+ try:
+ left_str, right_str = pattern.split("->")
+ except ValueError:
+ raise ValueError("Pattern must contain a single '->' separator") from None
+
+ if _ellipsis in axes_lengths:
+ raise ValueError(f"'{_ellipsis}' is not an allowed axis identifier")
+
+ left = ParsedExpression(left_str)
+ right = ParsedExpression(right_str)
+
+ if not left.has_ellipsis and right.has_ellipsis:
+ raise ValueError(
+ f"Ellipsis found in right side, but not left side of a pattern {pattern}"
+ )
+ if left.has_ellipsis and left.has_ellipsis_parenthesized:
+ raise ValueError(
+ f"Ellipsis is parenthesis in the left side is not allowed: {pattern}"
+ )
+
+ return left, right
+
+
+def validate_rearrange_expressions(
+ left: ParsedExpression, right: ParsedExpression, axes_lengths: Mapping[str, int]
+) -> None:
+ """Perform expression validations that are specific to the `rearrange` operation.
+
+ Args:
+ left (ParsedExpression): left-hand side expression
+ right (ParsedExpression): right-hand side expression
+ axes_lengths (Mapping[str, int]): any additional length specifications for dimensions
+ """
+ for length in axes_lengths.values():
+ if (length_type := type(length)) is not int:
+ raise TypeError(
+ f"rearrange axis lengths must be integers, got: {length_type}"
+ )
+
+ if left.has_non_unitary_anonymous_axes or right.has_non_unitary_anonymous_axes:
+ raise ValueError("rearrange only supports unnamed axes of size 1")
+
+ difference = set.symmetric_difference(left.identifiers, right.identifiers)
+ if len(difference) > 0:
+ raise ValueError(
+ f"Identifiers only on one side of rearrange expression (should be on both): {difference}"
+ )
+
+ unmatched_axes = axes_lengths.keys() - left.identifiers
+ if len(unmatched_axes) > 0:
+ raise ValueError(
+ f"Identifiers not found in rearrange expression: {unmatched_axes}"
+ )
+
+
+def comma_separate(collection: Collection[Union[str, Collection[str]]]) -> str:
+ """Convert a collection of strings representing first class dims into a comma-separated string.
+
+ Args:
+ collection (Collection[Union[str, Collection[str]]]): the collection of strings to convert
+
+ Returns:
+ str: the comma-separated string
+
+ Examples:
+ >>> comma_separate(('d0',))
+ 'd0'
+
+ >>> comma_separate(('d0', 'd1', 'd2', 'd3'))
+ 'd0, d1, d2, d3'
+
+ >>> comma_separate([('d1', 'd4')])
+ '(d1, d4)'
+
+ >>> comma_separate([('d0',), (), ('d1',), ('d2',), ('d3', 'd4')])
+ '(d0,), (), (d1,), (d2,), (d3, d4)'
+ """
+ return ", ".join(
+ item
+ if isinstance(item, str)
+ else f"({comma_separate(item)}{',' if len(item) == 1 else ''})"
+ for item in collection
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/einops/rearrange.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/einops/rearrange.py
new file mode 100644
index 0000000000000000000000000000000000000000..1cd3cd8b3cf64f10b2003ebea441ad6a859ee9f4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/einops/rearrange.py
@@ -0,0 +1,208 @@
+from __future__ import annotations
+
+import functools
+from typing import Callable, Dict, List, Sequence, Tuple, Union
+
+import torch
+from functorch._C import dim as _C
+
+from ._parsing import (
+ _ellipsis,
+ AnonymousAxis,
+ comma_separate,
+ parse_pattern,
+ validate_rearrange_expressions,
+)
+
+
+__all__ = ["rearrange"]
+
+dims = _C.dims
+
+
+@functools.lru_cache(256)
+def _create_rearrange_callable(
+ tensor_ndim: int, pattern: str, **axes_lengths: int
+) -> Callable[[torch.Tensor], torch.Tensor]:
+ r"""Translate an `einops`-style pattern into a callable that performs the rearrange using first-class dimensions.
+
+ Since the an equivalent result is computed for tensors with the same number of dimensions, with the same pattern and
+ specified axes lengths, this function can be memoized.
+
+ Args:
+ tensor_ndim (int): the number of dimensions in the tensor to rearrange
+ pattern (str): the `einops`-style rearrangement pattern
+ axes_lengths (int): any additional length specifications for dimensions
+
+ Returns:
+ Callable[[torch.Tensor], torch.Tensor]: a callable that performs the rearrangement
+ """
+ left, right = parse_pattern(pattern, axes_lengths)
+ validate_rearrange_expressions(left, right, axes_lengths)
+
+ n_anon_dims = sum(not dim for dim in left.composition)
+ if left.has_ellipsis:
+ n_ellipsis_dims = tensor_ndim - (len(left.composition) - 1)
+ n_named_dims = len(left.identifiers) - 1
+
+ if (pattern_ndim := n_anon_dims + n_named_dims) > tensor_ndim:
+ raise ValueError(
+ f"Number of dimensions in pattern ({pattern_ndim}) must be less than or equal to the number of "
+ f"dimensions in the tensor ({tensor_ndim})"
+ )
+ else:
+ n_ellipsis_dims = 0
+ n_named_dims = len(left.identifiers)
+
+ if (pattern_ndim := len(left.composition)) != tensor_ndim:
+ raise ValueError(
+ f"Number of dimensions in pattern ({pattern_ndim}) must be equal to the number of dimensions in "
+ f"the tensor ({tensor_ndim})"
+ )
+ n_dims = n_named_dims + n_ellipsis_dims + n_anon_dims
+
+ if n_dims == 0:
+ # an identity rearrangement on a 0-dimension tensor
+ return lambda tensor: tensor
+
+ first_class_dims: Tuple[str, ...] = tuple(f"d{i}" for i in range(n_dims))
+ identifier_dim_map: Dict[Union[str, AnonymousAxis], Tuple[str, ...]] = {}
+ anon_axes: List[AnonymousAxis] = []
+
+ # map the left-hand side identifiers to strings representing first class dims
+ dims_i = 0
+ for dimension in left.composition:
+ if isinstance(dimension, list):
+ for identifier in dimension:
+ # non-unitary anon axes are not allowed in rearrange & unitary anon axes are represented as empty lists
+ assert isinstance(identifier, str)
+ identifier_dim_map[identifier] = (first_class_dims[dims_i],)
+ dims_i += 1
+ if not dimension:
+ # unitary anonymous axis
+ anon_axis = AnonymousAxis("1")
+ identifier_dim_map[anon_axis] = (first_class_dims[dims_i],)
+ anon_axes.append(anon_axis)
+ dimension.append(anon_axis)
+ dims_i += 1
+ elif dimension == _ellipsis:
+ identifier = _ellipsis
+ identifier_dim_map[identifier] = tuple(
+ first_class_dims[dims_i + j] for j in range(n_ellipsis_dims)
+ )
+ dims_i += n_ellipsis_dims
+ else:
+ raise ValueError(f"Unexpected dimension: {dimension}")
+
+ def composition_to_dims(
+ composition: Sequence[Union[List[Union[str, AnonymousAxis]], str]]
+ ) -> List[Union[str, Tuple[str, ...]]]:
+ """Convert a `ParsedExpression.composition` into a `Tensor.__getitem__` index of strings representing first
+ class dims."""
+ dim_composition: List[Union[str, Tuple[str, ...]]] = []
+ for dimension in composition:
+ if isinstance(dimension, list):
+ dim_composition.append(
+ tuple(
+ dim
+ for identifier in dimension
+ for dim in identifier_dim_map[identifier]
+ )
+ )
+ elif dimension == _ellipsis:
+ dim_composition.extend(identifier_dim_map[_ellipsis])
+ else:
+ raise ValueError(f"Unexpected dimension: {dimension}")
+ return dim_composition
+
+ left_dims = composition_to_dims(left.composition)
+ right_dims = composition_to_dims(right.composition)
+ anon_dims = tuple(identifier_dim_map[axis][0] for axis in anon_axes)
+ specified_lengths = tuple(
+ (identifier_dim_map[axis][0], length) for axis, length in axes_lengths.items()
+ )
+
+ custom_rearrange_callable_name = "do_rearrange"
+ custom_rearrange_callable_code = (
+ (
+ f"def {custom_rearrange_callable_name}(tensor):\n"
+ f" {comma_separate(first_class_dims)} = dims({n_dims})\n"
+ )
+ + (
+ "".join(
+ f" {dim}.size = {length}\n" for (dim, length) in specified_lengths
+ )
+ if specified_lengths
+ else ""
+ )
+ + f" tensor = tensor[{comma_separate(left_dims)}].order({comma_separate(right_dims)})\n"
+ + (
+ f" return tensor.sum({comma_separate([anon_dims])}, keepdim=False)\n"
+ if anon_dims
+ else " return tensor\n"
+ )
+ )
+
+ exec(custom_rearrange_callable_code)
+ return locals()[custom_rearrange_callable_name]
+
+
+def rearrange(
+ tensor: Union[torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor, ...]],
+ pattern: str,
+ **axes_lengths: int,
+) -> torch.Tensor:
+ r"""A native implementation of `einops.rearrange`, a reader-friendly smart element reordering for multidimensional
+ tensors. This operation includes functionality of transpose (axes permutation), reshape (view), squeeze, unsqueeze,
+ stack, concatenate and other operations.
+
+ See: https://einops.rocks/api/rearrange/
+
+ Args:
+ tensor (Tensor or sequence of Tensor): the tensor(s) to rearrange
+ pattern (str): the rearrangement pattern
+ axes_lengths (int): any additional length specifications for dimensions
+
+ Returns:
+ Tensor: the rearranged tensor
+
+ Examples:
+ >>> # suppose we have a set of 32 images in "h w c" format (height-width-channel)
+ >>> images = torch.randn((32, 30, 40, 3))
+
+ >>> # stack along first (batch) axis, output is a single array
+ >>> rearrange(images, 'b h w c -> b h w c').shape
+ torch.Size([32, 30, 40, 3])
+
+ >>> # concatenate images along height (vertical axis), 960 = 32 * 30
+ >>> rearrange(images, 'b h w c -> (b h) w c').shape
+ torch.Size([960, 40, 3])
+
+ >>> # concatenated images along horizontal axis, 1280 = 32 * 40
+ >>> rearrange(images, 'b h w c -> h (b w) c').shape
+ torch.Size([30, 1280, 3])
+
+ >>> # reordered axes to "b c h w" format for deep learning
+ >>> rearrange(images, 'b h w c -> b c h w').shape
+ torch.Size([32, 3, 30, 40])
+
+ >>> # flattened each image into a vector, 3600 = 30 * 40 * 3
+ >>> rearrange(images, 'b h w c -> b (c h w)').shape
+ torch.Size([32, 3600])
+
+ >>> # split each image into 4 smaller (top-left, top-right, bottom-left, bottom-right), 128 = 32 * 2 * 2
+ >>> rearrange(images, 'b (h1 h) (w1 w) c -> (b h1 w1) h w c', h1=2, w1=2).shape
+ torch.Size([128, 15, 20, 3])
+
+ >>> # space-to-depth operation
+ >>> rearrange(images, 'b (h h1) (w w1) c -> b h w (c h1 w1)', h1=2, w1=2).shape
+ torch.Size([32, 15, 20, 12])
+ """
+ if not isinstance(tensor, torch.Tensor):
+ tensor = torch.stack(tensor)
+
+ rearrange_callable = _create_rearrange_callable(
+ tensor.ndim, pattern, **axes_lengths
+ )
+
+ return rearrange_callable(tensor)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/experimental/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/experimental/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3941f6d96e1f6df532966d06de4f72a952a58465
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/experimental/__init__.py
@@ -0,0 +1,5 @@
+# PyTorch forward-mode is not mature yet
+from functorch import functionalize
+from torch._functorch.apis import chunk_vmap
+from torch._functorch.batch_norm_replacement import replace_all_batch_norm_modules_
+from torch._functorch.eager_transforms import hessian, jacfwd, jvp
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/experimental/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/experimental/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bb129d1d615ce26d8a4ab5be25b65ac155b24717
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/experimental/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/experimental/__pycache__/control_flow.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/experimental/__pycache__/control_flow.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f1a8ca83f3b7b9078dcba294e897d17dc6638621
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/experimental/__pycache__/control_flow.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/experimental/__pycache__/ops.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/experimental/__pycache__/ops.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c3092c9aff920ef7806ecf222c533c67c517b1b0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/experimental/__pycache__/ops.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/experimental/control_flow.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/experimental/control_flow.py
new file mode 100644
index 0000000000000000000000000000000000000000..cbfd76d184cc224042a1ee19454d6957c2221b3b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/experimental/control_flow.py
@@ -0,0 +1,7 @@
+from torch import cond # noqa: F401
+from torch._higher_order_ops.cond import UnsupportedAliasMutationException # noqa: F401
+from torch._higher_order_ops.map import ( # noqa: F401
+ _stack_pytree,
+ _unstack_pytree,
+ map,
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/experimental/ops.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/experimental/ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a502ef2b002cd824e7b67d08fccac872b313110
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/functorch/experimental/ops.py
@@ -0,0 +1 @@
+from torch._ops import HigherOrderOperator # noqa: F401
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/gitpython-3.1.46.dist-info/licenses/AUTHORS b/data/conda_envs/evalclaw/lib/python3.11/site-packages/gitpython-3.1.46.dist-info/licenses/AUTHORS
new file mode 100644
index 0000000000000000000000000000000000000000..b57113edd14b5854b802710a8914097e9234c31b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/gitpython-3.1.46.dist-info/licenses/AUTHORS
@@ -0,0 +1,60 @@
+GitPython was originally written by Michael Trier.
+GitPython 0.2 was partially (re)written by Sebastian Thiel, based on 0.1.6 and git-dulwich.
+
+Contributors are:
+
+-Michael Trier
+-Alan Briolat
+-Florian Apolloner
+-David Aguilar
+-Jelmer Vernooij
+-Steve Frécinaux
+-Kai Lautaportti
+-Paul Sowden
+-Sebastian Thiel
+-Jonathan Chu
+-Vincent Driessen
+-Phil Elson
+-Bernard `Guyzmo` Pratz
+-Timothy B. Hartman
+-Konstantin Popov
+-Peter Jones
+-Anson Mansfield
+-Ken Odegard
+-Alexis Horgix Chotard
+-Piotr Babij
+-Mikuláš Poul
+-Charles Bouchard-Légaré
+-Yaroslav Halchenko
+-Tim Swast
+-William Luc Ritchie
+-David Host
+-A. Jesse Jiryu Davis
+-Steven Whitman
+-Stefan Stancu
+-César Izurieta
+-Arthur Milchior
+-Anil Khatri
+-JJ Graham
+-Ben Thayer
+-Dries Kennes
+-Pratik Anurag
+-Harmon
+-Liam Beguin
+-Ram Rachum
+-Alba Mendez
+-Robert Westman
+-Hugo van Kemenade
+-Hiroki Tokunaga
+-Julien Mauroy
+-Patrick Gerard
+-Luke Twist
+-Joseph Hale
+-Santos Gallegos
+-Wenhan Zhu
+-Eliah Kagan
+-Ethan Lin
+-Jonas Scharpf
+-Gordon Marx
+
+Portions derived from other open source works and are clearly marked.
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/gitpython-3.1.46.dist-info/licenses/LICENSE b/data/conda_envs/evalclaw/lib/python3.11/site-packages/gitpython-3.1.46.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..ba8a219fe1f27c10b50df8cd4f26c0ab833bbbc8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/gitpython-3.1.46.dist-info/licenses/LICENSE
@@ -0,0 +1,29 @@
+Copyright (C) 2008, 2009 Michael Trier and 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:
+
+* 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 GitPython project 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.
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6a0de9a1e6e4ea4e5248fe2fa374c363bdc78a29
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/__main__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/__main__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f1d5133d8b359742bbb63bc361dac6d340842cc3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/__main__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/_eventloop_macos.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/_eventloop_macos.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..25a494f44c7f087ca27d51a00e91733935646cbe
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/_eventloop_macos.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/_version.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/_version.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f196a9ee8076899e8b2ec0f5eac91b28d05af138
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/_version.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/compiler.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/compiler.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..17a62786011d38a92b8ea43c7f3882ce11c010c6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/compiler.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/connect.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/connect.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b899fbf9c925ef3a9c40341d7d3bc6b1d8666646
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/connect.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/control.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/control.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5616db6119b688b98e8af2d41250cc2de5dc5810
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/control.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/debugger.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/debugger.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1da6cdb38018efeec6dcae3a76ae45a9a37538e9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/debugger.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/displayhook.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/displayhook.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a89003d990bb333d6e2f1f5ca07614a1557ec511
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/displayhook.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/embed.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/embed.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb75dcd1d00c514730876e3f72f412f840ecbea6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/embed.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/eventloops.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/eventloops.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9a5fc435d856896ab8e2c6d9360904a708b3f717
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/eventloops.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/heartbeat.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/heartbeat.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..453a4e8afcc06d0fbb2f06ff6f7899aebd2ca942
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/heartbeat.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/iostream.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/iostream.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..be05e5e0338e0444aaf0bd2de42b6ceefaef86f0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/iostream.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/ipkernel.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/ipkernel.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..866ed4720bfc0e04a7114d98d0958dbb9cee65f9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/ipkernel.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/jsonutil.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/jsonutil.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7d97fe46b53e7f5e9893376e99ffb84b999c7416
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/jsonutil.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/kernelapp.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/kernelapp.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b96f91a537b28da0085c09468581303af6955fab
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/kernelapp.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/kernelbase.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/kernelbase.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..651c40b7eaa4616fc22b76f1998eef5a51701786
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/kernelbase.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/kernelspec.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/kernelspec.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..34722ede6b4a5554de37e4f5411ef1843ef82fd0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/kernelspec.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/log.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/log.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..48b5056df35e56562299fa15aaaa6df887d6f7e8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/log.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/parentpoller.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/parentpoller.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..144e4c29ade33069c3df5193f8daaaa241d7170b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/parentpoller.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/shellchannel.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/shellchannel.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..64aa450d315facfd69e9e60c383e997a172d8a8b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/shellchannel.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/socket_pair.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/socket_pair.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f6186e5282e75cb6dbb8fbaaab187641cf3a5f78
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/socket_pair.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/subshell.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/subshell.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..716bbc01215cdfa45e5278e66c017b1f73ece0f5
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/subshell.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/subshell_manager.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/subshell_manager.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb6a4db88b6de71d1b1b1260329055ace99c392a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/subshell_manager.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/thread.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/thread.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..38f45b5cffb83d6dbe3f2766c4074816e46e63ce
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/thread.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/trio_runner.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/trio_runner.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b945a63efb6bba49608f9f9fb9b75e7fbd1022d6
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/trio_runner.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/utils.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4313dc3ccd3973d9125348e798dc060beddd87da
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/utils.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/zmqshell.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/zmqshell.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1b345c8794fafefbefb2662879fed5eb04634d0b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/__pycache__/zmqshell.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/comm/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/comm/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d56cbe3085bd3914961b1eca76c69f2919bdf596
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/comm/__init__.py
@@ -0,0 +1,4 @@
+__all__ = ["Comm", "CommManager"]
+
+from .comm import Comm
+from .manager import CommManager
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/comm/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/comm/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..38e37d0de805c36f9ad8fcbe86f608aa616b4a6a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/comm/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/comm/__pycache__/comm.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/comm/__pycache__/comm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0b39d62c97ae69f5d177d0f7df46ba2d87befd35
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/comm/__pycache__/comm.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/comm/__pycache__/manager.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/comm/__pycache__/manager.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fd761d40b4bbdc1b73b47e582540f5998db19ee3
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/comm/__pycache__/manager.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/comm/comm.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/comm/comm.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1b659e9a44fc5d8c9df4ed8cf698634f64ee400
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/comm/comm.py
@@ -0,0 +1,100 @@
+"""Base class for a Comm"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import uuid
+from typing import Optional
+from warnings import warn
+
+import comm.base_comm
+import traitlets.config
+from traitlets import Bool, Bytes, Instance, Unicode, default
+
+from ipykernel.jsonutil import json_clean
+from ipykernel.kernelbase import Kernel
+
+
+# this is the class that will be created if we do comm.create_comm
+class BaseComm(comm.base_comm.BaseComm): # type:ignore[misc]
+ """The base class for comms."""
+
+ kernel: Optional["Kernel"] = None
+
+ def publish_msg(self, msg_type, data=None, metadata=None, buffers=None, **keys):
+ """Helper for sending a comm message on IOPub"""
+ if not Kernel.initialized():
+ return
+
+ data = {} if data is None else data
+ metadata = {} if metadata is None else metadata
+ content = json_clean(dict(data=data, comm_id=self.comm_id, **keys))
+
+ if self.kernel is None:
+ self.kernel = Kernel.instance()
+
+ assert self.kernel.session is not None
+ self.kernel.session.send(
+ self.kernel.iopub_socket,
+ msg_type,
+ content,
+ metadata=json_clean(metadata),
+ parent=self.kernel.get_parent(),
+ ident=self.topic,
+ buffers=buffers,
+ )
+
+
+# but for backwards compatibility, we need to inherit from LoggingConfigurable
+class Comm(BaseComm, traitlets.config.LoggingConfigurable):
+ """Class for communicating between a Frontend and a Kernel"""
+
+ kernel = Instance("ipykernel.kernelbase.Kernel", allow_none=True)
+ comm_id = Unicode()
+ primary = Bool(True, help="Am I the primary or secondary Comm?")
+
+ target_name = Unicode("comm")
+ target_module = Unicode(
+ None,
+ allow_none=True,
+ help="""requirejs module from
+ which to load comm target.""",
+ )
+
+ topic = Bytes()
+
+ @default("kernel")
+ def _default_kernel(self):
+ if Kernel.initialized():
+ return Kernel.instance()
+ return None
+
+ @default("comm_id")
+ def _default_comm_id(self):
+ return uuid.uuid4().hex
+
+ def __init__(
+ self, target_name="", data=None, metadata=None, buffers=None, show_warning=True, **kwargs
+ ):
+ """Initialize a comm."""
+ if show_warning:
+ warn(
+ "The `ipykernel.comm.Comm` class has been deprecated. Please use the `comm` module instead."
+ "For creating comms, use the function `from comm import create_comm`.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+ # Handle differing arguments between base classes.
+ had_kernel = "kernel" in kwargs
+ kernel = kwargs.pop("kernel", None)
+ if target_name:
+ kwargs["target_name"] = target_name
+ BaseComm.__init__(self, data=data, metadata=metadata, buffers=buffers, **kwargs) # type:ignore[call-arg]
+ # only re-add kernel if explicitly provided
+ if had_kernel:
+ kwargs["kernel"] = kernel
+ traitlets.config.LoggingConfigurable.__init__(self, **kwargs)
+
+
+__all__ = ["Comm"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/comm/manager.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/comm/manager.py
new file mode 100644
index 0000000000000000000000000000000000000000..aaef027ce42447b9b34d14e052aa29962218417c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/comm/manager.py
@@ -0,0 +1,62 @@
+"""Base class to manage comms"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import logging
+
+import comm.base_comm
+import traitlets
+import traitlets.config
+
+from .comm import Comm
+
+logger = logging.getLogger("ipykernel.comm")
+
+
+class CommManager(comm.base_comm.CommManager, traitlets.config.LoggingConfigurable): # type:ignore[misc]
+ """A comm manager."""
+
+ kernel = traitlets.Instance("ipykernel.kernelbase.Kernel")
+ comms = traitlets.Dict()
+ targets = traitlets.Dict()
+
+ def __init__(self, **kwargs):
+ """Initialize the manager."""
+ # CommManager doesn't take arguments, so we explicitly forward arguments
+ comm.base_comm.CommManager.__init__(self)
+ traitlets.config.LoggingConfigurable.__init__(self, **kwargs)
+
+ def comm_open(self, stream, ident, msg):
+ """Handler for comm_open messages"""
+ # This is for backward compatibility, the comm_open creates a a new ipykernel.comm.Comm
+ # but we should let the base class create the comm with comm.create_comm in a major release
+ content = msg["content"]
+ comm_id = content["comm_id"]
+ target_name = content["target_name"]
+ f = self.targets.get(target_name, None)
+ comm = Comm(
+ comm_id=comm_id,
+ primary=False,
+ target_name=target_name,
+ show_warning=False,
+ )
+ self.register_comm(comm)
+ if f is None:
+ logger.error("No such comm target registered: %s", target_name)
+ else:
+ try:
+ f(comm, msg)
+ return
+ except Exception:
+ logger.error("Exception opening comm with target: %s", target_name, exc_info=True) # noqa: G201
+
+ # Failure.
+ try:
+ comm.close()
+ except Exception:
+ logger.error( # noqa: G201
+ """Could not close comm during `comm_open` failure
+ clean-up. The comm may not have been opened yet.""",
+ exc_info=True,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/gui/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/gui/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..10d31f939e5c56b9659ad963c710381c9871fa29
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/gui/__init__.py
@@ -0,0 +1,15 @@
+"""GUI support for the IPython ZeroMQ kernel.
+
+This package contains the various toolkit-dependent utilities we use to enable
+coordination between the IPython kernel and the event loops of the various GUI
+toolkits.
+"""
+
+# -----------------------------------------------------------------------------
+# Copyright (C) 2010-2011 The IPython Development Team.
+#
+# Distributed under the terms of the BSD License.
+#
+# The full license is in the file LICENSE, distributed as part of this
+# software.
+# -----------------------------------------------------------------------------
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/gui/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/gui/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..21264b65899523ee261090121b7411a63bde441c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/gui/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/gui/__pycache__/gtk3embed.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/gui/__pycache__/gtk3embed.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5aa9a151fb77a1bc83d0d7c5a834d5f2b6e720ca
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/gui/__pycache__/gtk3embed.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/gui/__pycache__/gtkembed.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/gui/__pycache__/gtkembed.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..05d38c3d46e1ceb795c9b6aa6282d646953513fe
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/gui/__pycache__/gtkembed.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/gui/gtk3embed.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/gui/gtk3embed.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab4ec2226f12961baa1135af1c573a8a6515f934
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/gui/gtk3embed.py
@@ -0,0 +1,97 @@
+"""GUI support for the IPython ZeroMQ kernel - GTK toolkit support."""
+# -----------------------------------------------------------------------------
+# Copyright (C) 2010-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file LICENSE, distributed as part of this software.
+# -----------------------------------------------------------------------------
+
+# -----------------------------------------------------------------------------
+# Imports
+# -----------------------------------------------------------------------------
+# stdlib
+import sys
+import warnings
+
+# Third-party
+import gi
+
+gi.require_version("Gdk", "3.0")
+gi.require_version("Gtk", "3.0")
+from gi.repository import GObject, Gtk # noqa: E402
+
+warnings.warn(
+ "The Gtk3 event loop for ipykernel is deprecated", category=DeprecationWarning, stacklevel=2
+)
+
+# -----------------------------------------------------------------------------
+# Classes and functions
+# -----------------------------------------------------------------------------
+
+
+class GTKEmbed:
+ """A class to embed a kernel into the GTK main event loop."""
+
+ def __init__(self, kernel):
+ """Initialize the embed."""
+ self.kernel = kernel
+ # These two will later store the real gtk functions when we hijack them
+ self.gtk_main = None
+ self.gtk_main_quit = None
+
+ def start(self):
+ """Starts the GTK main event loop and sets our kernel startup routine."""
+ # Register our function to initiate the kernel and start gtk
+ GObject.idle_add(self._wire_kernel)
+ Gtk.main()
+
+ def _wire_kernel(self):
+ """Initializes the kernel inside GTK.
+
+ This is meant to run only once at startup, so it does its job and
+ returns False to ensure it doesn't get run again by GTK.
+ """
+ self.gtk_main, self.gtk_main_quit = self._hijack_gtk()
+ GObject.timeout_add(int(1000 * self.kernel._poll_interval), self.iterate_kernel)
+ return False
+
+ def iterate_kernel(self):
+ """Run one iteration of the kernel and return True.
+
+ GTK timer functions must return True to be called again, so we make the
+ call to :meth:`do_one_iteration` and then return True for GTK.
+ """
+ self.kernel.do_one_iteration()
+ return True
+
+ def stop(self):
+ """Stop the embed."""
+ # FIXME: this one isn't getting called because we have no reliable
+ # kernel shutdown. We need to fix that: once the kernel has a
+ # shutdown mechanism, it can call this.
+ if self.gtk_main_quit:
+ self.gtk_main_quit()
+ sys.exit()
+
+ def _hijack_gtk(self):
+ """Hijack a few key functions in GTK for IPython integration.
+
+ Modifies pyGTK's main and main_quit with a dummy so user code does not
+ block IPython. This allows us to use %run to run arbitrary pygtk
+ scripts from a long-lived IPython session, and when they attempt to
+ start or stop
+
+ Returns
+ -------
+ The original functions that have been hijacked:
+ - Gtk.main
+ - Gtk.main_quit
+ """
+
+ def dummy(*args, **kw):
+ """No-op."""
+
+ # save and trap main and main_quit from gtk
+ orig_main, Gtk.main = Gtk.main, dummy
+ orig_main_quit, Gtk.main_quit = Gtk.main_quit, dummy
+ return orig_main, orig_main_quit
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/gui/gtkembed.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/gui/gtkembed.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f3b6d1666e6e73f5bf02e5eeba247c2c4b1ae3b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/gui/gtkembed.py
@@ -0,0 +1,94 @@
+"""GUI support for the IPython ZeroMQ kernel - GTK toolkit support."""
+# -----------------------------------------------------------------------------
+# Copyright (C) 2010-2011 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file LICENSE, distributed as part of this software.
+# -----------------------------------------------------------------------------
+
+# -----------------------------------------------------------------------------
+# Imports
+# -----------------------------------------------------------------------------
+# stdlib
+import sys
+import warnings
+
+# Third-party
+import gobject
+import gtk
+
+warnings.warn(
+ "The Gtk3 event loop for ipykernel is deprecated", category=DeprecationWarning, stacklevel=2
+)
+
+# -----------------------------------------------------------------------------
+# Classes and functions
+# -----------------------------------------------------------------------------
+
+
+class GTKEmbed:
+ """A class to embed a kernel into the GTK main event loop."""
+
+ def __init__(self, kernel):
+ """Initialize the embed."""
+ self.kernel = kernel
+ # These two will later store the real gtk functions when we hijack them
+ self.gtk_main = None
+ self.gtk_main_quit = None
+
+ def start(self):
+ """Starts the GTK main event loop and sets our kernel startup routine."""
+ # Register our function to initiate the kernel and start gtk
+ gobject.idle_add(self._wire_kernel)
+ gtk.main()
+
+ def _wire_kernel(self):
+ """Initializes the kernel inside GTK.
+
+ This is meant to run only once at startup, so it does its job and
+ returns False to ensure it doesn't get run again by GTK.
+ """
+ self.gtk_main, self.gtk_main_quit = self._hijack_gtk()
+ gobject.timeout_add(int(1000 * self.kernel._poll_interval), self.iterate_kernel)
+ return False
+
+ def iterate_kernel(self):
+ """Run one iteration of the kernel and return True.
+
+ GTK timer functions must return True to be called again, so we make the
+ call to :meth:`do_one_iteration` and then return True for GTK.
+ """
+ self.kernel.do_one_iteration()
+ return True
+
+ def stop(self):
+ """Stop the embed."""
+ # FIXME: this one isn't getting called because we have no reliable
+ # kernel shutdown. We need to fix that: once the kernel has a
+ # shutdown mechanism, it can call this.
+ if self.gtk_main_quit:
+ self.gtk_main_quit()
+ sys.exit()
+
+ def _hijack_gtk(self):
+ """Hijack a few key functions in GTK for IPython integration.
+
+ Modifies pyGTK's main and main_quit with a dummy so user code does not
+ block IPython. This allows us to use %run to run arbitrary pygtk
+ scripts from a long-lived IPython session, and when they attempt to
+ start or stop
+
+ Returns
+ -------
+ The original functions that have been hijacked:
+ - gtk.main
+ - gtk.main_quit
+ """
+
+ def dummy(*args, **kw):
+ """No-op."""
+
+ # save and trap main and main_quit from gtk
+ orig_main, gtk.main = gtk.main, dummy
+ orig_main_quit, gtk.main_quit = gtk.main_quit, dummy
+ return orig_main, orig_main_quit
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1069891024c14f6b5186d7f25ee8d6c36a192ad
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__init__.py
@@ -0,0 +1,4 @@
+from .blocking import BlockingInProcessKernelClient
+from .channels import InProcessChannel, InProcessHBChannel
+from .client import InProcessKernelClient
+from .manager import InProcessKernelManager
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..acedffc1ef2be0bf32a0bc25c86346a51ea16983
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/blocking.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/blocking.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5acfce05a34bb8197001459f69cd12ec93dab148
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/blocking.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/channels.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/channels.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a0a74312df347fab1cdee9378436a0c9e67a0b8d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/channels.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/client.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/client.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d29dcd1582203b295613229c400743b9717039ac
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/client.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/constants.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/constants.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..40860a1705e7ec3ac204dc2b4e265624b7af9e85
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/constants.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/ipkernel.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/ipkernel.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a1c4c4c80583e0aef28fb6d1fa1675055637bb82
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/ipkernel.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/manager.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/manager.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..41183077f63669322332529b8df1efbcb05c1496
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/manager.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/socket.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/socket.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e6afca470707fe3f67e4df954ad1a82eec713748
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/__pycache__/socket.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/blocking.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/blocking.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c29919909772b898abf1fcb7360613ed20ad5fe
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/blocking.py
@@ -0,0 +1,110 @@
+"""Implements a fully blocking kernel client.
+
+Useful for test suites and blocking terminal interfaces.
+"""
+
+import sys
+
+# -----------------------------------------------------------------------------
+# Copyright (C) 2012 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file LICENSE, distributed as part of this software.
+# -----------------------------------------------------------------------------
+from queue import Empty, Queue
+
+# IPython imports
+from traitlets import Type
+
+# Local imports
+from .channels import InProcessChannel
+from .client import InProcessKernelClient
+
+
+class BlockingInProcessChannel(InProcessChannel):
+ """A blocking in-process channel."""
+
+ def __init__(self, *args, **kwds):
+ """Initialize the channel."""
+ super().__init__(*args, **kwds)
+ self._in_queue: Queue[object] = Queue()
+
+ def call_handlers(self, msg):
+ """Call the handlers for a message."""
+ self._in_queue.put(msg)
+
+ def get_msg(self, block=True, timeout=None):
+ """Gets a message if there is one that is ready."""
+ if timeout is None:
+ # Queue.get(timeout=None) has stupid uninteruptible
+ # behavior, so wait for a week instead
+ timeout = 604800
+ return self._in_queue.get(block, timeout)
+
+ def get_msgs(self):
+ """Get all messages that are currently ready."""
+ msgs = []
+ while True:
+ try:
+ msgs.append(self.get_msg(block=False))
+ except Empty:
+ break
+ return msgs
+
+ def msg_ready(self):
+ """Is there a message that has been received?"""
+ return not self._in_queue.empty()
+
+
+class BlockingInProcessStdInChannel(BlockingInProcessChannel):
+ """A blocking in-process stdin channel."""
+
+ def call_handlers(self, msg):
+ """Overridden for the in-process channel.
+
+ This methods simply calls raw_input directly.
+ """
+ msg_type = msg["header"]["msg_type"]
+ if msg_type == "input_request":
+ _raw_input = self.client.kernel._sys_raw_input
+ prompt = msg["content"]["prompt"]
+ print(prompt, end="", file=sys.__stdout__)
+ assert sys.__stdout__ is not None
+ sys.__stdout__.flush()
+ self.client.input(_raw_input())
+
+
+class BlockingInProcessKernelClient(InProcessKernelClient):
+ """A blocking in-process kernel client."""
+
+ # The classes to use for the various channels.
+ shell_channel_class = Type(BlockingInProcessChannel)
+ iopub_channel_class = Type(BlockingInProcessChannel)
+ stdin_channel_class = Type(BlockingInProcessStdInChannel)
+
+ def wait_for_ready(self):
+ """Wait for kernel info reply on shell channel."""
+ while True:
+ self.kernel_info()
+ try:
+ msg = self.shell_channel.get_msg(block=True, timeout=1)
+ except Empty:
+ pass
+ else:
+ if msg["msg_type"] == "kernel_info_reply":
+ # Checking that IOPub is connected. If it is not connected, start over.
+ try:
+ self.iopub_channel.get_msg(block=True, timeout=0.2)
+ except Empty:
+ pass
+ else:
+ self._handle_kernel_info_reply(msg)
+ break
+
+ # Flush IOPub channel
+ while True:
+ try:
+ msg = self.iopub_channel.get_msg(block=True, timeout=0.2)
+ print(msg["msg_type"])
+ except Empty:
+ break
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/channels.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/channels.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c01c5bcbc9cc15f89da93c120058b9b48313f13
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/channels.py
@@ -0,0 +1,107 @@
+"""A kernel client for in-process kernels."""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from jupyter_client.channelsabc import HBChannelABC
+
+# -----------------------------------------------------------------------------
+# Channel classes
+# -----------------------------------------------------------------------------
+
+
+class InProcessChannel:
+ """Base class for in-process channels."""
+
+ proxy_methods: list[object] = []
+
+ def __init__(self, client=None):
+ """Initialize the channel."""
+ super().__init__()
+ self.client = client
+ self._is_alive = False
+
+ def is_alive(self):
+ """Test if the channel is alive."""
+ return self._is_alive
+
+ def start(self):
+ """Start the channel."""
+ self._is_alive = True
+
+ def stop(self):
+ """Stop the channel."""
+ self._is_alive = False
+
+ def call_handlers(self, msg):
+ """This method is called in the main thread when a message arrives.
+
+ Subclasses should override this method to handle incoming messages.
+ """
+ msg = "call_handlers must be defined in a subclass."
+ raise NotImplementedError(msg)
+
+ def flush(self, timeout=1.0):
+ """Flush the channel."""
+
+ def call_handlers_later(self, *args, **kwds):
+ """Call the message handlers later.
+
+ The default implementation just calls the handlers immediately, but this
+ method exists so that GUI toolkits can defer calling the handlers until
+ after the event loop has run, as expected by GUI frontends.
+ """
+ self.call_handlers(*args, **kwds)
+
+ def process_events(self):
+ """Process any pending GUI events.
+
+ This method will be never be called from a frontend without an event
+ loop (e.g., a terminal frontend).
+ """
+ raise NotImplementedError
+
+
+class InProcessHBChannel:
+ """A dummy heartbeat channel interface for in-process kernels.
+
+ Normally we use the heartbeat to check that the kernel process is alive.
+ When the kernel is in-process, that doesn't make sense, but clients still
+ expect this interface.
+ """
+
+ time_to_dead = 3.0
+
+ def __init__(self, client=None):
+ """Initialize the channel."""
+ super().__init__()
+ self.client = client
+ self._is_alive = False
+ self._pause = True
+
+ def is_alive(self):
+ """Test if the channel is alive."""
+ return self._is_alive
+
+ def start(self):
+ """Start the channel."""
+ self._is_alive = True
+
+ def stop(self):
+ """Stop the channel."""
+ self._is_alive = False
+
+ def pause(self):
+ """Pause the channel."""
+ self._pause = True
+
+ def unpause(self):
+ """Unpause the channel."""
+ self._pause = False
+
+ def is_beating(self):
+ """Test if the channel is beating."""
+ return not self._pause
+
+
+HBChannelABC.register(InProcessHBChannel)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/client.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/client.py
new file mode 100644
index 0000000000000000000000000000000000000000..d18eec12ec85d6bab51ed80d1ac895024b0a5375
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/client.py
@@ -0,0 +1,233 @@
+"""A client for in-process kernels."""
+
+# -----------------------------------------------------------------------------
+# Copyright (C) 2012 The IPython Development Team
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file LICENSE, distributed as part of this software.
+# -----------------------------------------------------------------------------
+
+# -----------------------------------------------------------------------------
+# Imports
+# -----------------------------------------------------------------------------
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+from jupyter_client.client import KernelClient
+from jupyter_client.clientabc import KernelClientABC
+from jupyter_core.utils import run_sync
+
+# IPython imports
+from traitlets import Instance, Type, default
+
+# Local imports
+from .channels import InProcessChannel, InProcessHBChannel
+
+# -----------------------------------------------------------------------------
+# Main kernel Client class
+# -----------------------------------------------------------------------------
+
+
+class InProcessKernelClient(KernelClient):
+ """A client for an in-process kernel.
+
+ This class implements the interface of
+ `jupyter_client.clientabc.KernelClientABC` and allows
+ (asynchronous) frontends to be used seamlessly with an in-process kernel.
+
+ See `jupyter_client.client.KernelClient` for docstrings.
+ """
+
+ # The classes to use for the various channels.
+ shell_channel_class = Type(InProcessChannel) # type:ignore[assignment]
+ iopub_channel_class = Type(InProcessChannel) # type:ignore[assignment]
+ stdin_channel_class = Type(InProcessChannel) # type:ignore[assignment]
+ control_channel_class = Type(InProcessChannel) # type:ignore[assignment]
+ hb_channel_class = Type(InProcessHBChannel) # type:ignore[assignment]
+
+ kernel = Instance("ipykernel.inprocess.ipkernel.InProcessKernel", allow_none=True)
+
+ # --------------------------------------------------------------------------
+ # Channel management methods
+ # --------------------------------------------------------------------------
+
+ @default("blocking_class")
+ def _default_blocking_class(self):
+ from .blocking import BlockingInProcessKernelClient
+
+ return BlockingInProcessKernelClient
+
+ def get_connection_info(self, session: bool = False) -> dict[str, int | str | bytes]:
+ """Get the connection info for the client."""
+ d = super().get_connection_info(session=session)
+ d["kernel"] = self.kernel # type:ignore[assignment]
+ return d
+
+ def start_channels(self, *args, **kwargs):
+ """Start the channels on the client."""
+ super().start_channels()
+ if self.kernel:
+ self.kernel.frontends.append(self)
+
+ @property
+ def shell_channel(self):
+ if self._shell_channel is None:
+ self._shell_channel = self.shell_channel_class(self)
+ return self._shell_channel
+
+ @property
+ def iopub_channel(self):
+ if self._iopub_channel is None:
+ self._iopub_channel = self.iopub_channel_class(self)
+ return self._iopub_channel
+
+ @property
+ def stdin_channel(self):
+ if self._stdin_channel is None:
+ self._stdin_channel = self.stdin_channel_class(self)
+ return self._stdin_channel
+
+ @property
+ def control_channel(self):
+ if self._control_channel is None:
+ self._control_channel = self.control_channel_class(self)
+ return self._control_channel
+
+ @property
+ def hb_channel(self):
+ if self._hb_channel is None:
+ self._hb_channel = self.hb_channel_class(self)
+ return self._hb_channel
+
+ # Methods for sending specific messages
+ # -------------------------------------
+
+ def execute(
+ self,
+ code: str,
+ silent: bool = False,
+ store_history: bool = True,
+ user_expressions: dict[str, Any] | None = None,
+ allow_stdin: bool | None = None,
+ stop_on_error: bool = True,
+ ) -> str:
+ """Execute code on the client."""
+ if allow_stdin is None:
+ allow_stdin = self.allow_stdin
+ content = dict(
+ code=code,
+ silent=silent,
+ store_history=store_history,
+ user_expressions=user_expressions or {},
+ allow_stdin=allow_stdin,
+ )
+ msg = self.session.msg("execute_request", content)
+ self._dispatch_to_kernel(msg)
+ res = msg["header"]["msg_id"]
+ assert isinstance(res, str)
+ return res
+
+ def complete(self, code, cursor_pos=None):
+ """Get code completion."""
+ if cursor_pos is None:
+ cursor_pos = len(code)
+ content = dict(code=code, cursor_pos=cursor_pos)
+ msg = self.session.msg("complete_request", content)
+ self._dispatch_to_kernel(msg)
+ return msg["header"]["msg_id"]
+
+ def inspect(self, code, cursor_pos=None, detail_level=0):
+ """Get code inspection."""
+ if cursor_pos is None:
+ cursor_pos = len(code)
+ content = dict(
+ code=code,
+ cursor_pos=cursor_pos,
+ detail_level=detail_level,
+ )
+ msg = self.session.msg("inspect_request", content)
+ self._dispatch_to_kernel(msg)
+ return msg["header"]["msg_id"]
+
+ def history(self, raw=True, output=False, hist_access_type="range", **kwds):
+ """Get code history."""
+ content = dict(raw=raw, output=output, hist_access_type=hist_access_type, **kwds)
+ msg = self.session.msg("history_request", content)
+ self._dispatch_to_kernel(msg)
+ return msg["header"]["msg_id"]
+
+ def shutdown(self, restart=False):
+ """Handle shutdown."""
+ # FIXME: What to do here?
+ msg = "Cannot shutdown in-process kernel"
+ raise NotImplementedError(msg)
+
+ def kernel_info(self):
+ """Request kernel info."""
+ msg = self.session.msg("kernel_info_request")
+ self._dispatch_to_kernel(msg)
+ return msg["header"]["msg_id"]
+
+ def comm_info(self, target_name=None):
+ """Request a dictionary of valid comms and their targets."""
+ content = {} if target_name is None else dict(target_name=target_name)
+ msg = self.session.msg("comm_info_request", content)
+ self._dispatch_to_kernel(msg)
+ return msg["header"]["msg_id"]
+
+ def input(self, string):
+ """Handle kernel input."""
+ if self.kernel is None:
+ msg = "Cannot send input reply. No kernel exists."
+ raise RuntimeError(msg)
+ self.kernel.raw_input_str = string
+
+ def is_complete(self, code):
+ """Handle an is_complete request."""
+ msg = self.session.msg("is_complete_request", {"code": code})
+ self._dispatch_to_kernel(msg)
+ return msg["header"]["msg_id"]
+
+ def _dispatch_to_kernel(self, msg):
+ """Send a message to the kernel and handle a reply."""
+ kernel = self.kernel
+ if kernel is None:
+ msg = "Cannot send request. No kernel exists."
+ raise RuntimeError(msg)
+
+ stream = kernel.shell_stream
+ self.session.send(stream, msg)
+ msg_parts = stream.recv_multipart()
+ if run_sync is not None:
+ dispatch_shell = run_sync(kernel.dispatch_shell)
+ dispatch_shell(msg_parts)
+ else:
+ loop = asyncio.get_event_loop() # type:ignore[unreachable]
+ loop.run_until_complete(kernel.dispatch_shell(msg_parts))
+ _idents, reply_msg = self.session.recv(stream, copy=False)
+ self.shell_channel.call_handlers_later(reply_msg)
+
+ def get_shell_msg(self, block=True, timeout=None):
+ """Get a shell message."""
+ return self.shell_channel.get_msg(block, timeout)
+
+ def get_iopub_msg(self, block=True, timeout=None):
+ """Get an iopub message."""
+ return self.iopub_channel.get_msg(block, timeout)
+
+ def get_stdin_msg(self, block=True, timeout=None):
+ """Get a stdin message."""
+ return self.stdin_channel.get_msg(block, timeout)
+
+ def get_control_msg(self, block=True, timeout=None):
+ """Get a control message."""
+ return self.control_channel.get_msg(block, timeout)
+
+
+# -----------------------------------------------------------------------------
+# ABC Registration
+# -----------------------------------------------------------------------------
+
+KernelClientABC.register(InProcessKernelClient)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/constants.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..16d572083a84b034ba01e616b6ddf432bc637aa2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/constants.py
@@ -0,0 +1,7 @@
+"""Shared constants."""
+
+# Because inprocess communication is not networked, we can use a common Session
+# key everywhere. This is not just the empty bytestring to avoid tripping
+# certain security checks in the rest of Jupyter that assumes that empty keys
+# are insecure.
+INPROCESS_KEY = b"inprocess"
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/ipkernel.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/ipkernel.py
new file mode 100644
index 0000000000000000000000000000000000000000..e61af4277a62f6f53ad9bd648c223152fe210077
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/ipkernel.py
@@ -0,0 +1,203 @@
+"""An in-process kernel"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+from __future__ import annotations
+
+import logging
+import sys
+from contextlib import contextmanager
+
+from IPython.core.interactiveshell import InteractiveShellABC
+from traitlets import Any, Enum, Instance, List, Type, default
+
+from ipykernel.ipkernel import IPythonKernel
+from ipykernel.jsonutil import json_clean
+from ipykernel.zmqshell import ZMQInteractiveShell
+
+from ..iostream import BackgroundSocket, IOPubThread, OutStream
+from .constants import INPROCESS_KEY
+from .socket import DummySocket
+
+# -----------------------------------------------------------------------------
+# Main kernel class
+# -----------------------------------------------------------------------------
+
+
+class InProcessKernel(IPythonKernel):
+ """An in-process kernel."""
+
+ # -------------------------------------------------------------------------
+ # InProcessKernel interface
+ # -------------------------------------------------------------------------
+
+ # The frontends connected to this kernel.
+ frontends = List(Instance("ipykernel.inprocess.client.InProcessKernelClient", allow_none=True))
+
+ # The GUI environment that the kernel is running under. This need not be
+ # specified for the normal operation for the kernel, but is required for
+ # IPython's GUI support (including pylab). The default is 'inline' because
+ # it is safe under all GUI toolkits.
+ gui = Enum(("tk", "gtk", "wx", "qt", "qt4", "inline"), default_value="inline")
+
+ raw_input_str = Any()
+ stdout = Any()
+ stderr = Any()
+
+ # -------------------------------------------------------------------------
+ # Kernel interface
+ # -------------------------------------------------------------------------
+
+ shell_class = Type(allow_none=True) # type:ignore[assignment]
+ _underlying_iopub_socket = Instance(DummySocket, ())
+ iopub_thread: IOPubThread = Instance(IOPubThread) # type:ignore[assignment]
+
+ shell_stream = Instance(DummySocket, ()) # type:ignore[assignment]
+
+ @default("iopub_thread")
+ def _default_iopub_thread(self):
+ thread = IOPubThread(self._underlying_iopub_socket, session=self.session)
+ thread.start()
+ return thread
+
+ iopub_socket: BackgroundSocket = Instance(BackgroundSocket) # type:ignore[assignment]
+
+ @default("iopub_socket")
+ def _default_iopub_socket(self):
+ return self.iopub_thread.background_socket
+
+ stdin_socket = Instance(DummySocket, ())
+
+ def __init__(self, **traits):
+ """Initialize the kernel."""
+ super().__init__(**traits)
+
+ self._underlying_iopub_socket.observe(self._io_dispatch, names=["message_sent"])
+ if self.shell:
+ self.shell.kernel = self
+
+ async def execute_request(self, stream, ident, parent):
+ """Override for temporary IO redirection."""
+ with self._redirected_io():
+ await super().execute_request(stream, ident, parent)
+
+ def start(self):
+ """Override registration of dispatchers for streams."""
+ if self.shell:
+ self.shell.exit_now = False
+
+ def _abort_queues(self, subshell_id: str | None = ...):
+ """The in-process kernel doesn't abort requests."""
+
+ def _input_request(self, prompt, ident, parent, password=False):
+ # Flush output before making the request.
+ self.raw_input_str = None
+ if sys.stdout is not None:
+ sys.stdout.flush()
+ if sys.stderr is not None:
+ sys.stderr.flush()
+
+ # Send the input request.
+ content = json_clean(dict(prompt=prompt, password=password))
+ assert self.session is not None
+ msg = self.session.msg("input_request", content, parent)
+ for frontend in self.frontends:
+ assert frontend is not None
+ if frontend.session.session == parent["header"]["session"]:
+ frontend.stdin_channel.call_handlers(msg)
+ break
+ else:
+ logging.error("No frontend found for raw_input request")
+ return ""
+
+ # Await a response.
+ while self.raw_input_str is None:
+ frontend.stdin_channel.process_events()
+ return self.raw_input_str # type:ignore[unreachable]
+
+ # -------------------------------------------------------------------------
+ # Protected interface
+ # -------------------------------------------------------------------------
+
+ @contextmanager
+ def _redirected_io(self):
+ """Temporarily redirect IO to the kernel."""
+ sys_stdout, sys_stderr = sys.stdout, sys.stderr
+ try:
+ sys.stdout, sys.stderr = self.stdout, self.stderr
+ yield
+ finally:
+ sys.stdout, sys.stderr = sys_stdout, sys_stderr
+
+ # ------ Trait change handlers --------------------------------------------
+
+ def _io_dispatch(self, change):
+ """Called when a message is sent to the IO socket."""
+ assert self.iopub_socket.io_thread is not None
+ assert self.session is not None
+ _ident, msg = self.session.recv(self.iopub_socket.io_thread.socket, copy=False)
+ for frontend in self.frontends:
+ assert frontend is not None
+ frontend.iopub_channel.call_handlers(msg)
+
+ # ------ Trait initializers -----------------------------------------------
+
+ @default("log")
+ def _default_log(self):
+ return logging.getLogger(__name__)
+
+ @default("session")
+ def _default_session(self):
+ from jupyter_client.session import Session
+
+ return Session(parent=self, key=INPROCESS_KEY)
+
+ @default("shell_class")
+ def _default_shell_class(self):
+ return InProcessInteractiveShell
+
+ @default("stdout")
+ def _default_stdout(self):
+ return OutStream(self.session, self.iopub_thread, "stdout", watchfd=False)
+
+ @default("stderr")
+ def _default_stderr(self):
+ return OutStream(self.session, self.iopub_thread, "stderr", watchfd=False)
+
+
+# -----------------------------------------------------------------------------
+# Interactive shell subclass
+# -----------------------------------------------------------------------------
+
+
+class InProcessInteractiveShell(ZMQInteractiveShell):
+ """An in-process interactive shell."""
+
+ kernel: InProcessKernel = Instance(
+ "ipykernel.inprocess.ipkernel.InProcessKernel", allow_none=True
+ ) # type:ignore[assignment]
+
+ # -------------------------------------------------------------------------
+ # InteractiveShell interface
+ # -------------------------------------------------------------------------
+
+ def enable_gui(self, gui=None):
+ """Enable GUI integration for the kernel."""
+ if not gui:
+ gui = self.kernel.gui
+ self.active_eventloop = gui
+
+ def enable_matplotlib(self, gui=None):
+ """Enable matplotlib integration for the kernel."""
+ if not gui:
+ gui = self.kernel.gui
+ return super().enable_matplotlib(gui)
+
+ def enable_pylab(self, gui=None, import_all=True):
+ """Activate pylab support at runtime."""
+ if not gui:
+ gui = self.kernel.gui
+ return super().enable_pylab(gui, import_all)
+
+
+InteractiveShellABC.register(InProcessInteractiveShell)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/manager.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/manager.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a3f92c37344c610d7836e7c546e0d2f1ffae588
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/manager.py
@@ -0,0 +1,92 @@
+"""A kernel manager for in-process kernels."""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from jupyter_client.manager import KernelManager
+from jupyter_client.managerabc import KernelManagerABC
+from jupyter_client.session import Session
+from traitlets import DottedObjectName, Instance, default
+
+from .constants import INPROCESS_KEY
+
+
+class InProcessKernelManager(KernelManager):
+ """A manager for an in-process kernel.
+
+ This class implements the interface of
+ `jupyter_client.kernelmanagerabc.KernelManagerABC` and allows
+ (asynchronous) frontends to be used seamlessly with an in-process kernel.
+
+ See `jupyter_client.kernelmanager.KernelManager` for docstrings.
+ """
+
+ # The kernel process with which the KernelManager is communicating.
+ kernel = Instance("ipykernel.inprocess.ipkernel.InProcessKernel", allow_none=True)
+ # the client class for KM.client() shortcut
+ client_class = DottedObjectName("ipykernel.inprocess.BlockingInProcessKernelClient")
+
+ @default("blocking_class")
+ def _default_blocking_class(self):
+ from .blocking import BlockingInProcessKernelClient
+
+ return BlockingInProcessKernelClient
+
+ @default("session")
+ def _default_session(self):
+ # don't sign in-process messages
+ return Session(key=INPROCESS_KEY, parent=self)
+
+ # --------------------------------------------------------------------------
+ # Kernel management methods
+ # --------------------------------------------------------------------------
+
+ def start_kernel(self, **kwds):
+ """Start the kernel."""
+ from ipykernel.inprocess.ipkernel import InProcessKernel
+
+ self.kernel = InProcessKernel(parent=self, session=self.session)
+
+ def shutdown_kernel(self):
+ """Shutdown the kernel."""
+ if self.kernel:
+ self.kernel.iopub_thread.stop()
+ self._kill_kernel()
+
+ def restart_kernel(self, now=False, **kwds):
+ """Restart the kernel."""
+ self.shutdown_kernel()
+ self.start_kernel(**kwds)
+
+ @property
+ def has_kernel(self):
+ return self.kernel is not None
+
+ def _kill_kernel(self):
+ self.kernel = None
+
+ def interrupt_kernel(self):
+ """Interrupt the kernel."""
+ msg = "Cannot interrupt in-process kernel."
+ raise NotImplementedError(msg)
+
+ def signal_kernel(self, signum):
+ """Send a signal to the kernel."""
+ msg = "Cannot signal in-process kernel."
+ raise NotImplementedError(msg)
+
+ def is_alive(self):
+ """Test if the kernel is alive."""
+ return self.kernel is not None
+
+ def client(self, **kwargs):
+ """Get a client for the kernel."""
+ kwargs["kernel"] = self.kernel
+ return super().client(**kwargs)
+
+
+# -----------------------------------------------------------------------------
+# ABC Registration
+# -----------------------------------------------------------------------------
+
+KernelManagerABC.register(InProcessKernelManager)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/socket.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/socket.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a2866cb5361ced3440fcb756556b890a7f5f620
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/inprocess/socket.py
@@ -0,0 +1,41 @@
+"""Defines a dummy socket implementing (part of) the zmq.Socket interface."""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from queue import Queue
+
+import zmq
+from traitlets import HasTraits, Instance, Int
+
+# -----------------------------------------------------------------------------
+# Dummy socket class
+# -----------------------------------------------------------------------------
+
+
+class DummySocket(HasTraits):
+ """A dummy socket implementing (part of) the zmq.Socket interface."""
+
+ queue = Instance(Queue, ())
+ message_sent = Int(0) # Should be an Event
+ context = Instance(zmq.Context)
+
+ def _context_default(self):
+ return zmq.Context()
+
+ # -------------------------------------------------------------------------
+ # Socket interface
+ # -------------------------------------------------------------------------
+
+ def recv_multipart(self, flags=0, copy=True, track=False):
+ """Recv a multipart message."""
+ return self.queue.get_nowait()
+
+ def send_multipart(self, msg_parts, flags=0, copy=True, track=False):
+ """Send a multipart message."""
+ msg_parts = list(map(zmq.Message, msg_parts))
+ self.queue.put_nowait(msg_parts)
+ self.message_sent += 1
+
+ def flush(self, timeout=1.0):
+ """no-op to comply with stream API"""
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/pylab/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/pylab/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/pylab/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/pylab/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8586b4b228e00ee219fb79f4f9de203c22a84d71
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/pylab/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/pylab/__pycache__/backend_inline.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/pylab/__pycache__/backend_inline.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b100bfc07ae203f7038075fb9e2619a92ea89cdf
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/pylab/__pycache__/backend_inline.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/pylab/__pycache__/config.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/pylab/__pycache__/config.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4211a00291f0ae21ffc808a6a6065f0a7526222d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/pylab/__pycache__/config.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/pylab/backend_inline.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/pylab/backend_inline.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ce3716b80a45fd36c453081e4033ba2b24f618a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/pylab/backend_inline.py
@@ -0,0 +1,15 @@
+"""A matplotlib backend for publishing figures via display_data"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import warnings
+
+from matplotlib_inline.backend_inline import * # noqa: F403 # analysis: ignore
+
+warnings.warn(
+ "`ipykernel.pylab.backend_inline` is deprecated, directly "
+ "use `matplotlib_inline.backend_inline`",
+ DeprecationWarning,
+ stacklevel=2,
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/pylab/config.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/pylab/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c3a63ab49820ec408b9b2f64d152356d3288d06
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/pylab/config.py
@@ -0,0 +1,14 @@
+"""Configurable for configuring the IPython inline backend
+
+This module does not import anything from matplotlib.
+"""
+
+import warnings
+
+from matplotlib_inline.config import * # noqa: F403 # analysis: ignore
+
+warnings.warn(
+ "`ipykernel.pylab.config` is deprecated, directly use `matplotlib_inline.config`",
+ DeprecationWarning,
+ stacklevel=2,
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/resources/logo-svg.svg b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/resources/logo-svg.svg
new file mode 100644
index 0000000000000000000000000000000000000000..467b07b265bd7c9ddd575a2ce7178c62a35d6f83
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel/resources/logo-svg.svg
@@ -0,0 +1,265 @@
+
+
+
+
+
+
+
+ image/svg+xml
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7f221cb52b664ff4c38bcefa84975dfb8a1e4fe9
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/__pycache__/cache.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/__pycache__/cache.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6643f15a8857b612c0ffdc8f652b0d95b525159a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/__pycache__/cache.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/__pycache__/client.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/__pycache__/client.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3c42f31a68506359a558e0ebb006a3ef4f830ab2
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/__pycache__/client.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/__pycache__/errors.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/__pycache__/errors.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8bbd7a2ae5bff874e0c77b745aef24f168b8db89
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/__pycache__/errors.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/__pycache__/runtime.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/__pycache__/runtime.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..02d426d384ed2fa3b02e4781df785a0b883a34b7
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/__pycache__/runtime.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/__pycache__/schema.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/__pycache__/schema.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a10db63860ce1dfd3f40e2ed51e2f98be6fa55ca
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/__pycache__/schema.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/__pycache__/sse.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/__pycache__/sse.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8e62c1385f60544132646b1870396dc43e936a50
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/__pycache__/sse.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..16bf0e4ffd13a100a8141ed0f050c10021380704
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__init__.py
@@ -0,0 +1,20 @@
+"""Async client exports."""
+
+from langgraph_sdk._async.assistants import AssistantsClient
+from langgraph_sdk._async.client import LangGraphClient, get_client
+from langgraph_sdk._async.cron import CronClient
+from langgraph_sdk._async.http import HttpClient
+from langgraph_sdk._async.runs import RunsClient
+from langgraph_sdk._async.store import StoreClient
+from langgraph_sdk._async.threads import ThreadsClient
+
+__all__ = [
+ "AssistantsClient",
+ "CronClient",
+ "HttpClient",
+ "LangGraphClient",
+ "RunsClient",
+ "StoreClient",
+ "ThreadsClient",
+ "get_client",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..861c4304e16aab9e96404d3d916e7c0b93ba9780
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/assistants.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/assistants.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b32d99052c3376306e685e4200a37450578d41b0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/assistants.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/client.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/client.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..62d483bb105bbbb0f93c91a62ee7be5a2c57f14f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/client.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/cron.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/cron.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aa7dcf241a4786b458b1ffcb6842ffb7293e3c4c
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/cron.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/http.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/http.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8c228b39a30349b45499880c659001541b4e4fa8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/http.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/runs.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/runs.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3712911fe411d79d7a560557cb4fdea513f4a887
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/runs.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/store.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/store.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6db2cdf68088d1e1a207149c0cdc75fdf6b2040b
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/store.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/threads.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/threads.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4e97fc30682c65056a1b41c6755578282663f80d
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/__pycache__/threads.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/assistants.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/assistants.py
new file mode 100644
index 0000000000000000000000000000000000000000..24d3cfa99d06297d594c983524671fbb1d20a744
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/assistants.py
@@ -0,0 +1,740 @@
+"""Async client for managing assistants in LangGraph."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, Literal, cast, overload
+
+import httpx
+
+from langgraph_sdk._async.http import HttpClient
+from langgraph_sdk._shared.utilities import _quote_path_param
+from langgraph_sdk.schema import (
+ Assistant,
+ AssistantSelectField,
+ AssistantSortBy,
+ AssistantsSearchResponse,
+ AssistantVersion,
+ Config,
+ Context,
+ GraphSchema,
+ Json,
+ OnConflictBehavior,
+ QueryParamTypes,
+ SortOrder,
+ Subgraphs,
+)
+
+
+class AssistantsClient:
+ """Client for managing assistants in LangGraph.
+
+ This class provides methods to interact with assistants,
+ which are versioned configurations of your graph.
+
+ ???+ example "Example"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ assistant = await client.assistants.get("assistant_id_123")
+ ```
+ """
+
+ def __init__(self, http: HttpClient) -> None:
+ self.http = http
+
+ async def get(
+ self,
+ assistant_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Assistant:
+ """Get an assistant by ID.
+
+ Args:
+ assistant_id: The ID of the assistant to get.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ Assistant: Assistant Object.
+
+ ???+ example "Example Usage"
+
+ ```python
+ assistant = await client.assistants.get(
+ assistant_id="my_assistant_id"
+ )
+ print(assistant)
+ ```
+
+ ```shell
+ ----------------------------------------------------
+
+ {
+ 'assistant_id': 'my_assistant_id',
+ 'graph_id': 'agent',
+ 'created_at': '2024-06-25T17:10:33.109781+00:00',
+ 'updated_at': '2024-06-25T17:10:33.109781+00:00',
+ 'config': {},
+ 'metadata': {'created_by': 'system'},
+ 'version': 1,
+ 'name': 'my_assistant'
+ }
+ ```
+ """
+ return await self.http.get(
+ f"/assistants/{_quote_path_param(assistant_id)}",
+ headers=headers,
+ params=params,
+ )
+
+ async def get_graph(
+ self,
+ assistant_id: str,
+ *,
+ xray: int | bool = False,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> dict[str, list[dict[str, Any]]]:
+ """Get the graph of an assistant by ID.
+
+ Args:
+ assistant_id: The ID of the assistant to get the graph of.
+ xray: Include graph representation of subgraphs. If an integer value is provided, only subgraphs with a depth less than or equal to the value will be included.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ Graph: The graph information for the assistant in JSON format.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ graph_info = await client.assistants.get_graph(
+ assistant_id="my_assistant_id"
+ )
+ print(graph_info)
+ ```
+
+ ```shell
+
+ --------------------------------------------------------------------------------------------------------------------------
+
+ {
+ 'nodes':
+ [
+ {'id': '__start__', 'type': 'schema', 'data': '__start__'},
+ {'id': '__end__', 'type': 'schema', 'data': '__end__'},
+ {'id': 'agent','type': 'runnable','data': {'id': ['langgraph', 'utils', 'RunnableCallable'],'name': 'agent'}},
+ ],
+ 'edges':
+ [
+ {'source': '__start__', 'target': 'agent'},
+ {'source': 'agent','target': '__end__'}
+ ]
+ }
+ ```
+
+
+ """
+ query_params = {"xray": xray}
+ if params:
+ query_params.update(params)
+
+ return await self.http.get(
+ f"/assistants/{_quote_path_param(assistant_id)}/graph",
+ params=query_params,
+ headers=headers,
+ )
+
+ async def get_schemas(
+ self,
+ assistant_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> GraphSchema:
+ """Get the schemas of an assistant by ID.
+
+ Args:
+ assistant_id: The ID of the assistant to get the schema of.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ GraphSchema: The graph schema for the assistant.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ schema = await client.assistants.get_schemas(
+ assistant_id="my_assistant_id"
+ )
+ print(schema)
+ ```
+
+ ```shell
+
+ ----------------------------------------------------------------------------------------------------------------------------
+
+ {
+ 'graph_id': 'agent',
+ 'state_schema':
+ {
+ 'title': 'LangGraphInput',
+ '$ref': '#/definitions/AgentState',
+ 'definitions':
+ {
+ 'BaseMessage':
+ {
+ 'title': 'BaseMessage',
+ 'description': 'Base abstract Message class. Messages are the inputs and outputs of ChatModels.',
+ 'type': 'object',
+ 'properties':
+ {
+ 'content':
+ {
+ 'title': 'Content',
+ 'anyOf': [
+ {'type': 'string'},
+ {'type': 'array','items': {'anyOf': [{'type': 'string'}, {'type': 'object'}]}}
+ ]
+ },
+ 'additional_kwargs':
+ {
+ 'title': 'Additional Kwargs',
+ 'type': 'object'
+ },
+ 'response_metadata':
+ {
+ 'title': 'Response Metadata',
+ 'type': 'object'
+ },
+ 'type':
+ {
+ 'title': 'Type',
+ 'type': 'string'
+ },
+ 'name':
+ {
+ 'title': 'Name',
+ 'type': 'string'
+ },
+ 'id':
+ {
+ 'title': 'Id',
+ 'type': 'string'
+ }
+ },
+ 'required': ['content', 'type']
+ },
+ 'AgentState':
+ {
+ 'title': 'AgentState',
+ 'type': 'object',
+ 'properties':
+ {
+ 'messages':
+ {
+ 'title': 'Messages',
+ 'type': 'array',
+ 'items': {'$ref': '#/definitions/BaseMessage'}
+ }
+ },
+ 'required': ['messages']
+ }
+ }
+ },
+ 'context_schema':
+ {
+ 'title': 'Context',
+ 'type': 'object',
+ 'properties':
+ {
+ 'model_name':
+ {
+ 'title': 'Model Name',
+ 'enum': ['anthropic', 'openai'],
+ 'type': 'string'
+ }
+ }
+ }
+ }
+ ```
+
+ """
+ return await self.http.get(
+ f"/assistants/{_quote_path_param(assistant_id)}/schemas",
+ headers=headers,
+ params=params,
+ )
+
+ async def get_subgraphs(
+ self,
+ assistant_id: str,
+ namespace: str | None = None,
+ recurse: bool = False,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Subgraphs:
+ """Get the schemas of an assistant by ID.
+
+ Args:
+ assistant_id: The ID of the assistant to get the schema of.
+ namespace: Optional namespace to filter by.
+ recurse: Whether to recursively get subgraphs.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ Subgraphs: The graph schema for the assistant.
+
+ """
+ get_params = {"recurse": recurse}
+ if params:
+ get_params = {**get_params, **dict(params)}
+ if namespace is not None:
+ return await self.http.get(
+ f"/assistants/{_quote_path_param(assistant_id)}/subgraphs/{_quote_path_param(namespace)}",
+ params=get_params,
+ headers=headers,
+ )
+ else:
+ return await self.http.get(
+ f"/assistants/{_quote_path_param(assistant_id)}/subgraphs",
+ params=get_params,
+ headers=headers,
+ )
+
+ async def create(
+ self,
+ graph_id: str | None,
+ config: Config | None = None,
+ *,
+ context: Context | None = None,
+ metadata: Json = None,
+ assistant_id: str | None = None,
+ if_exists: OnConflictBehavior | None = None,
+ name: str | None = None,
+ headers: Mapping[str, str] | None = None,
+ description: str | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Assistant:
+ """Create a new assistant.
+
+ Useful when graph is configurable and you want to create different assistants based on different configurations.
+
+ Args:
+ graph_id: The ID of the graph the assistant should use. The graph ID is normally set in your langgraph.json configuration.
+ config: Configuration to use for the graph.
+ metadata: Metadata to add to assistant.
+ context: Static context to add to the assistant.
+ !!! version-added "Added in version 0.6.0"
+ assistant_id: Assistant ID to use, will default to a random UUID if not provided.
+ if_exists: How to handle duplicate creation. Defaults to 'raise' under the hood.
+ Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing assistant).
+ name: The name of the assistant. Defaults to 'Untitled' under the hood.
+ headers: Optional custom headers to include with the request.
+ description: Optional description of the assistant.
+ The description field is available for langgraph-api server version>=0.0.45
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ Assistant: The created assistant.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ assistant = await client.assistants.create(
+ graph_id="agent",
+ context={"model_name": "openai"},
+ metadata={"number":1},
+ assistant_id="my-assistant-id",
+ if_exists="do_nothing",
+ name="my_name"
+ )
+ ```
+ """
+ payload: dict[str, Any] = {
+ "graph_id": graph_id,
+ }
+ if config:
+ payload["config"] = config
+ if context:
+ payload["context"] = context
+ if metadata:
+ payload["metadata"] = metadata
+ if assistant_id:
+ payload["assistant_id"] = assistant_id
+ if if_exists:
+ payload["if_exists"] = if_exists
+ if name:
+ payload["name"] = name
+ if description:
+ payload["description"] = description
+ return await self.http.post(
+ "/assistants", json=payload, headers=headers, params=params
+ )
+
+ async def update(
+ self,
+ assistant_id: str,
+ *,
+ graph_id: str | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ metadata: Json = None,
+ name: str | None = None,
+ headers: Mapping[str, str] | None = None,
+ description: str | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Assistant:
+ """Update an assistant.
+
+ Use this to point to a different graph, update the configuration, or change the metadata of an assistant.
+
+ Args:
+ assistant_id: Assistant to update.
+ graph_id: The ID of the graph the assistant should use.
+ The graph ID is normally set in your langgraph.json configuration. If `None`, assistant will keep pointing to same graph.
+ config: Configuration to use for the graph.
+ context: Static context to add to the assistant.
+ !!! version-added "Added in version 0.6.0"
+ metadata: Metadata to merge with existing assistant metadata.
+ name: The new name for the assistant.
+ headers: Optional custom headers to include with the request.
+ description: Optional description of the assistant.
+ The description field is available for langgraph-api server version>=0.0.45
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The updated assistant.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ assistant = await client.assistants.update(
+ assistant_id='e280dad7-8618-443f-87f1-8e41841c180f',
+ graph_id="other-graph",
+ context={"model_name": "anthropic"},
+ metadata={"number":2}
+ )
+ ```
+
+ """
+ payload: dict[str, Any] = {}
+ if graph_id:
+ payload["graph_id"] = graph_id
+ if config is not None:
+ payload["config"] = config
+ if context is not None:
+ payload["context"] = context
+ if metadata:
+ payload["metadata"] = metadata
+ if name:
+ payload["name"] = name
+ if description:
+ payload["description"] = description
+ return await self.http.patch(
+ f"/assistants/{_quote_path_param(assistant_id)}",
+ json=payload,
+ headers=headers,
+ params=params,
+ )
+
+ async def delete(
+ self,
+ assistant_id: str,
+ *,
+ delete_threads: bool = False,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Delete an assistant.
+
+ Args:
+ assistant_id: The assistant ID to delete.
+ delete_threads: If true, delete all threads with `metadata.assistant_id`
+ matching this assistant, along with runs and checkpoints belonging to
+ those threads.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ await client.assistants.delete(
+ assistant_id="my_assistant_id"
+ )
+ ```
+
+ """
+ query_params: dict[str, Any] = {}
+ if delete_threads:
+ query_params["delete_threads"] = True
+ if params:
+ query_params.update(params)
+ await self.http.delete(
+ f"/assistants/{_quote_path_param(assistant_id)}",
+ headers=headers,
+ params=query_params or None,
+ )
+
+ @overload
+ async def search(
+ self,
+ *,
+ metadata: Json = None,
+ graph_id: str | None = None,
+ name: str | None = None,
+ limit: int = 10,
+ offset: int = 0,
+ sort_by: AssistantSortBy | None = None,
+ sort_order: SortOrder | None = None,
+ select: list[AssistantSelectField] | None = None,
+ response_format: Literal["object"],
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> AssistantsSearchResponse: ...
+
+ @overload
+ async def search(
+ self,
+ *,
+ metadata: Json = None,
+ graph_id: str | None = None,
+ name: str | None = None,
+ limit: int = 10,
+ offset: int = 0,
+ sort_by: AssistantSortBy | None = None,
+ sort_order: SortOrder | None = None,
+ select: list[AssistantSelectField] | None = None,
+ response_format: Literal["array"] = "array",
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> list[Assistant]: ...
+
+ async def search(
+ self,
+ *,
+ metadata: Json = None,
+ graph_id: str | None = None,
+ name: str | None = None,
+ limit: int = 10,
+ offset: int = 0,
+ sort_by: AssistantSortBy | None = None,
+ sort_order: SortOrder | None = None,
+ select: list[AssistantSelectField] | None = None,
+ response_format: Literal["array", "object"] = "array",
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> AssistantsSearchResponse | list[Assistant]:
+ """Search for assistants.
+
+ Args:
+ metadata: Metadata to filter by. Exact match filter for each KV pair.
+ graph_id: The ID of the graph to filter by.
+ The graph ID is normally set in your langgraph.json configuration.
+ name: The name of the assistant to filter by.
+ The filtering logic will match assistants where 'name' is a substring (case insensitive) of the assistant name.
+ limit: The maximum number of results to return.
+ offset: The number of results to skip.
+ sort_by: The field to sort by.
+ sort_order: The order to sort by.
+ select: Specific assistant fields to include in the response.
+ response_format: Controls the response shape. Use `"array"` (default)
+ to return a bare list of assistants, or `"object"` to return
+ a mapping containing assistants plus pagination metadata.
+ Defaults to "array", though this default will be changed to "object" in a future release.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ A list of assistants (when `response_format="array"`) or a mapping
+ with the assistants and the next pagination cursor (when
+ `response_format="object"`).
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ response = await client.assistants.search(
+ metadata = {"name":"my_name"},
+ graph_id="my_graph_id",
+ limit=5,
+ offset=5,
+ response_format="object"
+ )
+ next_cursor = response["next"]
+ assistants = response["assistants"]
+ ```
+ """
+ if response_format not in ("array", "object"):
+ raise ValueError(
+ f"response_format must be 'array' or 'object', got {response_format!r}"
+ )
+ payload: dict[str, Any] = {
+ "limit": limit,
+ "offset": offset,
+ }
+ if metadata:
+ payload["metadata"] = metadata
+ if graph_id:
+ payload["graph_id"] = graph_id
+ if name:
+ payload["name"] = name
+ if sort_by:
+ payload["sort_by"] = sort_by
+ if sort_order:
+ payload["sort_order"] = sort_order
+ if select:
+ payload["select"] = select
+ next_cursor: str | None = None
+
+ def capture_pagination(response: httpx.Response) -> None:
+ nonlocal next_cursor
+ next_cursor = response.headers.get("X-Pagination-Next")
+
+ assistants = cast(
+ list[Assistant],
+ await self.http.post(
+ "/assistants/search",
+ json=payload,
+ headers=headers,
+ params=params,
+ on_response=capture_pagination if response_format == "object" else None,
+ ),
+ )
+ if response_format == "object":
+ return {"assistants": assistants, "next": next_cursor}
+ return assistants
+
+ async def count(
+ self,
+ *,
+ metadata: Json = None,
+ graph_id: str | None = None,
+ name: str | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> int:
+ """Count assistants matching filters.
+
+ Args:
+ metadata: Metadata to filter by. Exact match for each key/value.
+ graph_id: Optional graph id to filter by.
+ name: Optional name to filter by.
+ The filtering logic will match assistants where 'name' is a substring (case insensitive) of the assistant name.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ int: Number of assistants matching the criteria.
+ """
+ payload: dict[str, Any] = {}
+ if metadata:
+ payload["metadata"] = metadata
+ if graph_id:
+ payload["graph_id"] = graph_id
+ if name:
+ payload["name"] = name
+ return await self.http.post(
+ "/assistants/count", json=payload, headers=headers, params=params
+ )
+
+ async def get_versions(
+ self,
+ assistant_id: str,
+ metadata: Json = None,
+ limit: int = 10,
+ offset: int = 0,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> list[AssistantVersion]:
+ """List all versions of an assistant.
+
+ Args:
+ assistant_id: The assistant ID to get versions for.
+ metadata: Metadata to filter versions by. Exact match filter for each KV pair.
+ limit: The maximum number of versions to return.
+ offset: The number of versions to skip.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ A list of assistant versions.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ assistant_versions = await client.assistants.get_versions(
+ assistant_id="my_assistant_id"
+ )
+ ```
+ """
+
+ payload: dict[str, Any] = {
+ "limit": limit,
+ "offset": offset,
+ }
+ if metadata:
+ payload["metadata"] = metadata
+ return await self.http.post(
+ f"/assistants/{_quote_path_param(assistant_id)}/versions",
+ json=payload,
+ headers=headers,
+ params=params,
+ )
+
+ async def set_latest(
+ self,
+ assistant_id: str,
+ version: int,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Assistant:
+ """Change the version of an assistant.
+
+ Args:
+ assistant_id: The assistant ID to delete.
+ version: The version to change to.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ Assistant Object.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ new_version_assistant = await client.assistants.set_latest(
+ assistant_id="my_assistant_id",
+ version=3
+ )
+ ```
+
+ """
+
+ payload: dict[str, Any] = {"version": version}
+
+ return await self.http.post(
+ f"/assistants/{_quote_path_param(assistant_id)}/latest",
+ json=payload,
+ headers=headers,
+ params=params,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/client.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/client.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc852c41f65b3f1461d36b40766277b00a90453c
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/client.py
@@ -0,0 +1,178 @@
+"""Async LangGraph client."""
+
+from __future__ import annotations
+
+import logging
+import os
+from collections.abc import Mapping
+from types import TracebackType
+
+import httpx
+
+from langgraph_sdk._async.assistants import AssistantsClient
+from langgraph_sdk._async.cron import CronClient
+from langgraph_sdk._async.http import HttpClient
+from langgraph_sdk._async.runs import RunsClient
+from langgraph_sdk._async.store import StoreClient
+from langgraph_sdk._async.threads import ThreadsClient
+from langgraph_sdk._shared.types import TimeoutTypes
+from langgraph_sdk._shared.utilities import (
+ NOT_PROVIDED,
+ _get_headers,
+ _registered_transports,
+ get_asgi_transport,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def get_client(
+ *,
+ url: str | None = None,
+ api_key: str | None = NOT_PROVIDED,
+ headers: Mapping[str, str] | None = None,
+ timeout: TimeoutTypes | None = None,
+) -> LangGraphClient:
+ """Create and configure a LangGraphClient.
+
+ The client provides programmatic access to LangSmith Deployment. It supports
+ both remote servers and local in-process connections (when running inside a LangGraph server).
+
+ Args:
+ url:
+ Base URL of the LangGraph API.
+ - If `None`, the client first attempts an in-process connection via ASGI transport.
+ If that fails, it defers registration until after app initialization. This
+ only works if the client is used from within the Agent server.
+ api_key:
+ API key for authentication. Can be:
+ - A string: use this exact API key
+ - `None`: explicitly skip loading from environment variables
+ - Not provided (default): auto-load from environment in this order:
+ 1. `LANGGRAPH_API_KEY`
+ 2. `LANGSMITH_API_KEY`
+ 3. `LANGCHAIN_API_KEY`
+ headers:
+ Additional HTTP headers to include in requests. Merged with authentication headers.
+ timeout:
+ HTTP timeout configuration. May be:
+ - `httpx.Timeout` instance
+ - float (total seconds)
+ - tuple `(connect, read, write, pool)` in seconds
+ Defaults: connect=5, read=300, write=300, pool=5.
+
+ Returns:
+ LangGraphClient:
+ A top-level client exposing sub-clients for assistants, threads,
+ runs, and cron operations.
+
+ ???+ example "Connect to a remote server:"
+
+ ```python
+ from langgraph_sdk import get_client
+
+ # get top-level LangGraphClient
+ client = get_client(url="http://localhost:8123")
+
+ # example usage: client..()
+ assistants = await client.assistants.get(assistant_id="some_uuid")
+ ```
+
+ ???+ example "Connect in-process to a running LangGraph server:"
+
+ ```python
+ from langgraph_sdk import get_client
+
+ client = get_client(url=None)
+
+ async def my_node(...):
+ subagent_result = await client.runs.wait(
+ thread_id=None,
+ assistant_id="agent",
+ input={"messages": [{"role": "user", "content": "Foo"}]},
+ )
+ ```
+
+ ???+ example "Skip auto-loading API key from environment:"
+
+ ```python
+ from langgraph_sdk import get_client
+
+ # Don't load API key from environment variables
+ client = get_client(
+ url="http://localhost:8123",
+ api_key=None
+ )
+ ```
+ """
+
+ transport: httpx.AsyncBaseTransport | None = None
+ if url is None:
+ url = "http://api"
+ if os.environ.get("__LANGGRAPH_DEFER_LOOPBACK_TRANSPORT") == "true":
+ transport = get_asgi_transport()(app=None, root_path="/noauth") # ty: ignore[invalid-argument-type]
+ _registered_transports.append(transport)
+ else:
+ try:
+ from langgraph_api.server import app # type: ignore
+
+ transport = get_asgi_transport()(app, root_path="/noauth")
+ except Exception:
+ logger.debug(
+ "Failed to connect to in-process LangGraph server. Deferring configuration.",
+ exc_info=True,
+ )
+ transport = get_asgi_transport()(app=None, root_path="/noauth") # ty: ignore[invalid-argument-type]
+ _registered_transports.append(transport)
+
+ if transport is None:
+ transport = httpx.AsyncHTTPTransport(retries=5)
+ client = httpx.AsyncClient(
+ base_url=url,
+ transport=transport,
+ timeout=(
+ httpx.Timeout(timeout) # ty: ignore[invalid-argument-type]
+ if timeout is not None
+ else httpx.Timeout(connect=5, read=300, write=300, pool=5)
+ ),
+ headers=_get_headers(api_key, headers),
+ )
+ return LangGraphClient(client)
+
+
+class LangGraphClient:
+ """Top-level client for LangGraph API.
+
+ Attributes:
+ assistants: Manages versioned configuration for your graphs.
+ threads: Handles (potentially) multi-turn interactions, such as conversational threads.
+ runs: Controls individual invocations of the graph.
+ crons: Manages scheduled operations.
+ store: Interfaces with persistent, shared data storage.
+ """
+
+ def __init__(self, client: httpx.AsyncClient) -> None:
+ self.http = HttpClient(client)
+ self.assistants = AssistantsClient(self.http)
+ self.threads = ThreadsClient(self.http)
+ self.runs = RunsClient(self.http)
+ self.crons = CronClient(self.http)
+ self.store = StoreClient(self.http)
+
+ async def __aenter__(self) -> LangGraphClient:
+ """Enter the async context manager."""
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: TracebackType | None,
+ ) -> None:
+ """Exit the async context manager."""
+ await self.aclose()
+
+ async def aclose(self) -> None:
+ """Close the underlying HTTP client."""
+ if hasattr(self, "http"):
+ await self.http.client.aclose()
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/cron.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/cron.py
new file mode 100644
index 0000000000000000000000000000000000000000..792fba5b035a0c3f992058ce0a14b77c7f836096
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/cron.py
@@ -0,0 +1,534 @@
+"""Async client for managing recurrent runs (cron jobs) in LangGraph."""
+
+from __future__ import annotations
+
+import warnings
+from collections.abc import Mapping, Sequence
+from datetime import datetime, tzinfo
+from typing import Any
+
+from langgraph_sdk._async.http import HttpClient
+from langgraph_sdk._shared.utilities import _quote_path_param, _resolve_timezone
+from langgraph_sdk.schema import (
+ All,
+ Config,
+ Context,
+ Cron,
+ CronSelectField,
+ CronSortBy,
+ Durability,
+ Input,
+ Json,
+ OnCompletionBehavior,
+ QueryParamTypes,
+ Run,
+ SortOrder,
+ StreamMode,
+)
+
+
+class CronClient:
+ """Client for managing recurrent runs (cron jobs) in LangGraph.
+
+ A run is a single invocation of an assistant with optional input, config, and context.
+ This client allows scheduling recurring runs to occur automatically.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024"))
+ cron_job = await client.crons.create_for_thread(
+ thread_id="thread_123",
+ assistant_id="asst_456",
+ schedule="0 9 * * *",
+ input={"message": "Daily update"}
+ )
+ ```
+
+ !!! note "Feature Availability"
+
+ The crons client functionality is not supported on all licenses.
+ Please check the relevant license documentation for the most up-to-date
+ details on feature availability.
+ """
+
+ def __init__(self, http_client: HttpClient) -> None:
+ self.http = http_client
+
+ async def create_for_thread(
+ self,
+ thread_id: str,
+ assistant_id: str,
+ *,
+ schedule: str,
+ input: Input | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint_during: bool | None = None, # deprecated
+ interrupt_before: All | list[str] | None = None,
+ interrupt_after: All | list[str] | None = None,
+ webhook: str | None = None,
+ multitask_strategy: str | None = None,
+ end_time: datetime | None = None,
+ enabled: bool | None = None,
+ timezone: str | tzinfo | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ stream_subgraphs: bool | None = None,
+ stream_resumable: bool | None = None,
+ durability: Durability | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Run:
+ """Create a cron job for a thread.
+
+ Args:
+ thread_id: the thread ID to run the cron job on.
+ assistant_id: The assistant ID or graph name to use for the cron job.
+ If using graph name, will default to first assistant created from that graph.
+ schedule: The cron schedule to execute this job on.
+ Schedules are interpreted in UTC unless a timezone is specified.
+ input: The input to the graph.
+ metadata: Metadata to assign to the cron job runs.
+ config: The configuration for the assistant.
+ context: Static context to add to the assistant.
+ !!! version-added "Added in version 0.6.0"
+ checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
+ interrupt_before: Nodes to interrupt immediately before they get executed.
+
+ interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
+
+ webhook: Webhook to call after LangGraph API call is done.
+ multitask_strategy: Multitask strategy to use.
+ Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
+ end_time: The time to stop running the cron job. If not provided, the cron job will run indefinitely.
+ enabled: Whether the cron job is enabled or not.
+ timezone: IANA timezone for the cron schedule. Accepts a string (e.g. 'America/New_York') or a ``datetime.tzinfo`` instance (e.g. ``ZoneInfo("America/New_York")``).
+ stream_mode: The stream mode(s) to use.
+ stream_subgraphs: Whether to stream output from subgraphs.
+ stream_resumable: Whether to persist the stream chunks in order to resume the stream later.
+ durability: Durability level for the run. Must be one of 'sync', 'async', or 'exit'.
+ "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
+ "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
+ "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The cron run.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ cron_run = await client.crons.create_for_thread(
+ thread_id="my-thread-id",
+ assistant_id="agent",
+ schedule="27 15 * * *",
+ input={"messages": [{"role": "user", "content": "hello!"}]},
+ metadata={"name":"my_run"},
+ context={"model_name": "openai"},
+ interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
+ interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
+ webhook="https://my.fake.webhook.com",
+ multitask_strategy="interrupt",
+ enabled=True,
+ )
+ ```
+ """
+ if checkpoint_during is not None:
+ warnings.warn(
+ "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+ payload = {
+ "schedule": schedule,
+ "input": input,
+ "config": config,
+ "metadata": metadata,
+ "context": context,
+ "assistant_id": assistant_id,
+ "checkpoint_during": checkpoint_during,
+ "interrupt_before": interrupt_before,
+ "interrupt_after": interrupt_after,
+ "webhook": webhook,
+ "end_time": end_time.isoformat() if end_time else None,
+ "enabled": enabled,
+ "timezone": _resolve_timezone(timezone),
+ "stream_mode": stream_mode,
+ "stream_subgraphs": stream_subgraphs,
+ "stream_resumable": stream_resumable,
+ "durability": durability,
+ }
+ if multitask_strategy:
+ payload["multitask_strategy"] = multitask_strategy
+ payload = {k: v for k, v in payload.items() if v is not None}
+ return await self.http.post(
+ f"/threads/{_quote_path_param(thread_id)}/runs/crons",
+ json=payload,
+ headers=headers,
+ params=params,
+ )
+
+ async def create(
+ self,
+ assistant_id: str,
+ *,
+ schedule: str,
+ input: Input | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint_during: bool | None = None, # deprecated
+ interrupt_before: All | list[str] | None = None,
+ interrupt_after: All | list[str] | None = None,
+ webhook: str | None = None,
+ on_run_completed: OnCompletionBehavior | None = None,
+ multitask_strategy: str | None = None,
+ end_time: datetime | None = None,
+ enabled: bool | None = None,
+ timezone: str | tzinfo | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ stream_subgraphs: bool | None = None,
+ stream_resumable: bool | None = None,
+ durability: Durability | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Run:
+ """Create a cron run.
+
+ Args:
+ assistant_id: The assistant ID or graph name to use for the cron job.
+ If using graph name, will default to first assistant created from that graph.
+ schedule: The cron schedule to execute this job on.
+ Schedules are interpreted in UTC unless a timezone is specified.
+ input: The input to the graph.
+ metadata: Metadata to assign to the cron job runs.
+ config: The configuration for the assistant.
+ context: Static context to add to the assistant.
+ !!! version-added "Added in version 0.6.0"
+ checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
+ interrupt_before: Nodes to interrupt immediately before they get executed.
+ interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
+ webhook: Webhook to call after LangGraph API call is done.
+ on_run_completed: What to do with the thread after the run completes.
+ Must be one of 'delete' (default) or 'keep'. 'delete' removes the thread
+ after execution. 'keep' creates a new thread for each execution but does not
+ clean them up. Clients are responsible for cleaning up kept threads.
+ multitask_strategy: Multitask strategy to use.
+ Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
+ end_time: The time to stop running the cron job. If not provided, the cron job will run indefinitely.
+ enabled: Whether the cron job is enabled or not.
+ timezone: IANA timezone for the cron schedule. Accepts a string (e.g. 'America/New_York') or a ``datetime.tzinfo`` instance (e.g. ``ZoneInfo("America/New_York")``).
+ stream_mode: The stream mode(s) to use.
+ stream_subgraphs: Whether to stream output from subgraphs.
+ stream_resumable: Whether to persist the stream chunks in order to resume the stream later.
+ durability: Durability level for the run. Must be one of 'sync', 'async', or 'exit'.
+ "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
+ "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
+ "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The cron run.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ cron_run = client.crons.create(
+ assistant_id="agent",
+ schedule="27 15 * * *",
+ input={"messages": [{"role": "user", "content": "hello!"}]},
+ metadata={"name":"my_run"},
+ context={"model_name": "openai"},
+ interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
+ interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
+ webhook="https://my.fake.webhook.com",
+ multitask_strategy="interrupt",
+ enabled=True,
+ )
+ ```
+
+ """
+ if checkpoint_during is not None:
+ warnings.warn(
+ "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+ payload = {
+ "schedule": schedule,
+ "input": input,
+ "config": config,
+ "metadata": metadata,
+ "context": context,
+ "assistant_id": assistant_id,
+ "checkpoint_during": checkpoint_during,
+ "interrupt_before": interrupt_before,
+ "interrupt_after": interrupt_after,
+ "webhook": webhook,
+ "on_run_completed": on_run_completed,
+ "end_time": end_time.isoformat() if end_time else None,
+ "enabled": enabled,
+ "timezone": _resolve_timezone(timezone),
+ "stream_mode": stream_mode,
+ "stream_subgraphs": stream_subgraphs,
+ "stream_resumable": stream_resumable,
+ "durability": durability,
+ }
+ if multitask_strategy:
+ payload["multitask_strategy"] = multitask_strategy
+ payload = {k: v for k, v in payload.items() if v is not None}
+ return await self.http.post(
+ "/runs/crons", json=payload, headers=headers, params=params
+ )
+
+ async def delete(
+ self,
+ cron_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Delete a cron.
+
+ Args:
+ cron_id: The cron ID to delete.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ await client.crons.delete(
+ cron_id="cron_to_delete"
+ )
+ ```
+
+ """
+ await self.http.delete(
+ f"/runs/crons/{_quote_path_param(cron_id)}", headers=headers, params=params
+ )
+
+ async def update(
+ self,
+ cron_id: str,
+ *,
+ schedule: str | None = None,
+ end_time: datetime | None = None,
+ input: Input | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ webhook: str | None = None,
+ interrupt_before: All | list[str] | None = None,
+ interrupt_after: All | list[str] | None = None,
+ on_run_completed: OnCompletionBehavior | None = None,
+ enabled: bool | None = None,
+ timezone: str | tzinfo | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ stream_subgraphs: bool | None = None,
+ stream_resumable: bool | None = None,
+ durability: Durability | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Cron:
+ """Update a cron job by ID.
+
+ Args:
+ cron_id: The cron ID to update.
+ schedule: The cron schedule to execute this job on.
+ Schedules are interpreted in UTC unless a timezone is specified.
+ end_time: The end date to stop running the cron.
+ input: The input to the graph.
+ metadata: Metadata to assign to the cron job runs.
+ config: The configuration for the assistant.
+ context: Static context added to the assistant.
+ webhook: Webhook to call after LangGraph API call is done.
+ interrupt_before: Nodes to interrupt immediately before they get executed.
+ interrupt_after: Nodes to interrupt immediately after they get executed.
+ on_run_completed: What to do with the thread after the run completes.
+ Must be one of 'delete' or 'keep'. 'delete' removes the thread
+ after execution. 'keep' creates a new thread for each execution but does not
+ clean them up.
+ enabled: Enable or disable the cron job.
+ timezone: IANA timezone for the cron schedule. Accepts a string (e.g. 'America/New_York') or a ``datetime.tzinfo`` instance (e.g. ``ZoneInfo("America/New_York")``).
+ stream_mode: The stream mode(s) to use.
+ stream_subgraphs: Whether to stream output from subgraphs.
+ stream_resumable: Whether to persist the stream chunks in order to resume the stream later.
+ durability: Durability level for the run. Must be one of 'sync', 'async', or 'exit'.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The updated cron job.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ updated_cron = await client.crons.update(
+ cron_id="1ef3cefa-4c09-6926-96d0-3dc97fd5e39b",
+ schedule="0 10 * * *",
+ enabled=False,
+ )
+ ```
+
+ """
+ payload = {
+ "schedule": schedule,
+ "end_time": end_time.isoformat() if end_time else None,
+ "input": input,
+ "metadata": metadata,
+ "config": config,
+ "context": context,
+ "webhook": webhook,
+ "interrupt_before": interrupt_before,
+ "interrupt_after": interrupt_after,
+ "on_run_completed": on_run_completed,
+ "enabled": enabled,
+ "timezone": _resolve_timezone(timezone),
+ "stream_mode": stream_mode,
+ "stream_subgraphs": stream_subgraphs,
+ "stream_resumable": stream_resumable,
+ "durability": durability,
+ }
+ payload = {k: v for k, v in payload.items() if v is not None}
+ return await self.http.patch(
+ f"/runs/crons/{_quote_path_param(cron_id)}",
+ json=payload,
+ headers=headers,
+ params=params,
+ )
+
+ async def search(
+ self,
+ *,
+ assistant_id: str | None = None,
+ thread_id: str | None = None,
+ enabled: bool | None = None,
+ metadata: Json = None,
+ limit: int = 10,
+ offset: int = 0,
+ sort_by: CronSortBy | None = None,
+ sort_order: SortOrder | None = None,
+ select: list[CronSelectField] | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> list[Cron]:
+ """Get a list of cron jobs.
+
+ Args:
+ assistant_id: The assistant ID or graph name to search for.
+ thread_id: the thread ID to search for.
+ enabled: The enabled status to search for.
+ metadata: Metadata to filter by. Exact match filter for each KV pair.
+ !!! version-added "Added in Agent Server version 0.9.0"
+ limit: The maximum number of results to return.
+ offset: The number of results to skip.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The list of cron jobs returned by the search,
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ cron_jobs = await client.crons.search(
+ assistant_id="my_assistant_id",
+ thread_id="my_thread_id",
+ enabled=True,
+ limit=5,
+ offset=5,
+ )
+ print(cron_jobs)
+ ```
+ ```shell
+
+ ----------------------------------------------------------
+
+ [
+ {
+ 'cron_id': '1ef3cefa-4c09-6926-96d0-3dc97fd5e39b',
+ 'assistant_id': 'my_assistant_id',
+ 'thread_id': 'my_thread_id',
+ 'user_id': None,
+ 'payload':
+ {
+ 'input': {'start_time': ''},
+ 'schedule': '4 * * * *',
+ 'assistant_id': 'my_assistant_id'
+ },
+ 'schedule': '4 * * * *',
+ 'next_run_date': '2024-07-25T17:04:00+00:00',
+ 'end_time': None,
+ 'created_at': '2024-07-08T06:02:23.073257+00:00',
+ 'updated_at': '2024-07-08T06:02:23.073257+00:00'
+ }
+ ]
+ ```
+
+ """
+ payload: dict[str, Any] = {
+ "assistant_id": assistant_id,
+ "thread_id": thread_id,
+ "enabled": enabled,
+ "limit": limit,
+ "offset": offset,
+ }
+ if metadata:
+ payload["metadata"] = metadata
+ if sort_by:
+ payload["sort_by"] = sort_by
+ if sort_order:
+ payload["sort_order"] = sort_order
+ if select:
+ payload["select"] = select
+ payload = {k: v for k, v in payload.items() if v is not None}
+ return await self.http.post(
+ "/runs/crons/search", json=payload, headers=headers, params=params
+ )
+
+ async def count(
+ self,
+ *,
+ assistant_id: str | None = None,
+ thread_id: str | None = None,
+ metadata: Json = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> int:
+ """Count cron jobs matching filters.
+
+ Args:
+ assistant_id: Assistant ID to filter by.
+ thread_id: Thread ID to filter by.
+ metadata: Metadata to filter by. Exact match filter for each KV pair.
+ !!! version-added "Added in Agent Server version 0.9.0"
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ int: Number of crons matching the criteria.
+ """
+ payload: dict[str, Any] = {}
+ if assistant_id:
+ payload["assistant_id"] = assistant_id
+ if thread_id:
+ payload["thread_id"] = thread_id
+ if metadata:
+ payload["metadata"] = metadata
+ return await self.http.post(
+ "/runs/crons/count", json=payload, headers=headers, params=params
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/http.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/http.py
new file mode 100644
index 0000000000000000000000000000000000000000..47c0f043fd0a8cb08ea92d438c299eb20c4c1282
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/http.py
@@ -0,0 +1,312 @@
+"""HTTP client for async operations."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import sys
+import warnings
+from collections.abc import AsyncIterator, Callable, Mapping
+from typing import Any, cast
+
+import httpx
+import orjson
+
+from langgraph_sdk._shared.utilities import (
+ _orjson_default,
+ _validate_reconnect_location,
+)
+from langgraph_sdk.errors import _araise_for_status_typed
+from langgraph_sdk.schema import QueryParamTypes, StreamPart
+from langgraph_sdk.sse import SSEDecoder, aiter_lines_raw
+
+logger = logging.getLogger(__name__)
+
+
+class HttpClient:
+ """Handle async requests to the LangGraph API.
+
+ Adds additional error messaging & content handling above the
+ provided httpx client.
+
+ Attributes:
+ client (httpx.AsyncClient): Underlying HTTPX async client.
+ """
+
+ def __init__(self, client: httpx.AsyncClient) -> None:
+ self.client = client
+
+ async def get(
+ self,
+ path: str,
+ *,
+ params: QueryParamTypes | None = None,
+ headers: Mapping[str, str] | None = None,
+ on_response: Callable[[httpx.Response], None] | None = None,
+ ) -> Any:
+ """Send a `GET` request."""
+ r = await self.client.get(path, params=params, headers=headers)
+ if on_response:
+ on_response(r)
+ await _araise_for_status_typed(r)
+ return await _adecode_json(r)
+
+ async def post(
+ self,
+ path: str,
+ *,
+ json: dict[str, Any] | list | None,
+ params: QueryParamTypes | None = None,
+ headers: Mapping[str, str] | None = None,
+ on_response: Callable[[httpx.Response], None] | None = None,
+ ) -> Any:
+ """Send a `POST` request."""
+ if json is not None:
+ request_headers, content = await _aencode_json(json)
+ else:
+ request_headers, content = {}, b""
+ # Merge headers, with runtime headers taking precedence
+ if headers:
+ request_headers.update(headers)
+ r = await self.client.post(
+ path, headers=request_headers, content=content, params=params
+ )
+ if on_response:
+ on_response(r)
+ await _araise_for_status_typed(r)
+ return await _adecode_json(r)
+
+ async def put(
+ self,
+ path: str,
+ *,
+ json: dict,
+ params: QueryParamTypes | None = None,
+ headers: Mapping[str, str] | None = None,
+ on_response: Callable[[httpx.Response], None] | None = None,
+ ) -> Any:
+ """Send a `PUT` request."""
+ request_headers, content = await _aencode_json(json)
+ if headers:
+ request_headers.update(headers)
+ r = await self.client.put(
+ path, headers=request_headers, content=content, params=params
+ )
+ if on_response:
+ on_response(r)
+ await _araise_for_status_typed(r)
+ return await _adecode_json(r)
+
+ async def patch(
+ self,
+ path: str,
+ *,
+ json: dict,
+ params: QueryParamTypes | None = None,
+ headers: Mapping[str, str] | None = None,
+ on_response: Callable[[httpx.Response], None] | None = None,
+ ) -> Any:
+ """Send a `PATCH` request."""
+ request_headers, content = await _aencode_json(json)
+ if headers:
+ request_headers.update(headers)
+ r = await self.client.patch(
+ path, headers=request_headers, content=content, params=params
+ )
+ if on_response:
+ on_response(r)
+ await _araise_for_status_typed(r)
+ return await _adecode_json(r)
+
+ async def delete(
+ self,
+ path: str,
+ *,
+ json: Any | None = None,
+ params: QueryParamTypes | None = None,
+ headers: Mapping[str, str] | None = None,
+ on_response: Callable[[httpx.Response], None] | None = None,
+ ) -> None:
+ """Send a `DELETE` request."""
+ r = await self.client.request(
+ "DELETE", path, json=json, params=params, headers=headers
+ )
+ if on_response:
+ on_response(r)
+ await _araise_for_status_typed(r)
+
+ async def request_reconnect(
+ self,
+ path: str,
+ method: str,
+ *,
+ json: dict[str, Any] | None = None,
+ params: QueryParamTypes | None = None,
+ headers: Mapping[str, str] | None = None,
+ on_response: Callable[[httpx.Response], None] | None = None,
+ reconnect_limit: int = 5,
+ ) -> Any:
+ """Send a request that automatically reconnects to Location header."""
+ request_headers, content = await _aencode_json(json)
+ if headers:
+ request_headers.update(headers)
+ async with self.client.stream(
+ method, path, headers=request_headers, content=content, params=params
+ ) as r:
+ if on_response:
+ on_response(r)
+ try:
+ r.raise_for_status()
+ except httpx.HTTPStatusError as e:
+ body = (await r.aread()).decode()
+ if sys.version_info >= (3, 11):
+ e.add_note(body)
+ else:
+ logger.error(f"Error from langgraph-api: {body}", exc_info=e)
+ raise e
+ loc = r.headers.get("location")
+ if reconnect_limit <= 0 or not loc:
+ return await _adecode_json(r)
+ _validate_reconnect_location(self.client.base_url, loc)
+ try:
+ return await _adecode_json(r)
+ except httpx.HTTPError:
+ warnings.warn(
+ f"Request failed, attempting reconnect to Location: {loc}",
+ stacklevel=2,
+ )
+ await r.aclose()
+ return await self.request_reconnect(
+ loc,
+ "GET",
+ headers=request_headers,
+ # don't pass on_response so it's only called once
+ reconnect_limit=reconnect_limit - 1,
+ )
+
+ async def stream(
+ self,
+ path: str,
+ method: str,
+ *,
+ json: dict[str, Any] | None = None,
+ params: QueryParamTypes | None = None,
+ headers: Mapping[str, str] | None = None,
+ on_response: Callable[[httpx.Response], None] | None = None,
+ ) -> AsyncIterator[StreamPart]:
+ """Stream results using SSE."""
+ request_headers, content = await _aencode_json(json)
+ request_headers["Accept"] = "text/event-stream"
+ request_headers["Cache-Control"] = "no-store"
+ # Add runtime headers with precedence
+ if headers:
+ request_headers.update(headers)
+
+ reconnect_headers = {
+ key: value
+ for key, value in request_headers.items()
+ if key.lower() not in {"content-length", "content-type"}
+ }
+
+ last_event_id: str | None = None
+ reconnect_path: str | None = None
+ reconnect_attempts = 0
+ max_reconnect_attempts = 5
+
+ while True:
+ current_headers = dict(
+ request_headers if reconnect_path is None else reconnect_headers
+ )
+ if last_event_id is not None:
+ current_headers["Last-Event-ID"] = last_event_id
+
+ current_method = method if reconnect_path is None else "GET"
+ current_content = content if reconnect_path is None else None
+ current_params = params if reconnect_path is None else None
+
+ retry = False
+ async with self.client.stream(
+ current_method,
+ reconnect_path or path,
+ headers=current_headers,
+ content=current_content,
+ params=current_params,
+ ) as res:
+ if reconnect_path is None and on_response:
+ on_response(res)
+ # check status
+ await _araise_for_status_typed(res)
+ # check content type
+ content_type = res.headers.get("content-type", "").partition(";")[0]
+ if "text/event-stream" not in content_type:
+ raise httpx.TransportError(
+ "Expected response header Content-Type to contain 'text/event-stream', "
+ f"got {content_type!r}"
+ )
+
+ reconnect_location = res.headers.get("location")
+ if reconnect_location:
+ _validate_reconnect_location(
+ self.client.base_url, reconnect_location
+ )
+ reconnect_path = reconnect_location
+
+ # parse SSE
+ decoder = SSEDecoder()
+ try:
+ async for line in aiter_lines_raw(res):
+ sse = decoder.decode(line=cast("bytes", line).rstrip(b"\n"))
+ if sse is not None:
+ if decoder.last_event_id is not None:
+ last_event_id = decoder.last_event_id
+ if sse.event or sse.data is not None:
+ yield sse
+ except httpx.HTTPError:
+ # httpx.TransportError inherits from HTTPError, so transient
+ # disconnects during streaming land here.
+ if reconnect_path is None:
+ raise
+ retry = True
+ else:
+ if sse := decoder.decode(b""):
+ if decoder.last_event_id is not None:
+ last_event_id = decoder.last_event_id
+ if sse.event or sse.data is not None:
+ # decoder.decode(b"") flushes the in-flight event and may
+ # return an empty placeholder when there is no pending
+ # message. Skip these no-op events so the stream doesn't
+ # emit a trailing blank item after reconnects.
+ yield sse
+ if retry:
+ reconnect_attempts += 1
+ if reconnect_attempts > max_reconnect_attempts:
+ raise httpx.TransportError(
+ "Exceeded maximum SSE reconnection attempts"
+ )
+ continue
+ break
+
+
+async def _aencode_json(json: Any) -> tuple[dict[str, str], bytes | None]:
+ if json is None:
+ return {}, None
+ body = await asyncio.get_running_loop().run_in_executor(
+ None,
+ orjson.dumps,
+ json,
+ _orjson_default,
+ orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_NON_STR_KEYS,
+ )
+ content_length = str(len(body))
+ content_type = "application/json"
+ headers = {"Content-Length": content_length, "Content-Type": content_type}
+ return headers, body
+
+
+async def _adecode_json(r: httpx.Response) -> Any:
+ body = await r.aread()
+ return (
+ await asyncio.get_running_loop().run_in_executor(None, orjson.loads, body)
+ if body
+ else None
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/runs.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/runs.py
new file mode 100644
index 0000000000000000000000000000000000000000..76782b36c54e43c71a8684df5d03007d83932bfa
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/runs.py
@@ -0,0 +1,1190 @@
+"""Async client for managing runs in LangGraph."""
+
+from __future__ import annotations
+
+import builtins
+import warnings
+from collections.abc import AsyncIterator, Callable, Mapping, Sequence
+from typing import Any, Literal, overload
+
+import httpx
+
+from langgraph_sdk._async.http import HttpClient
+from langgraph_sdk._shared.utilities import (
+ _get_run_metadata_from_response,
+ _quote_path_param,
+ _sse_to_v2_dict,
+)
+from langgraph_sdk.schema import (
+ All,
+ BulkCancelRunsStatus,
+ CancelAction,
+ Checkpoint,
+ Command,
+ Config,
+ Context,
+ DisconnectMode,
+ Durability,
+ IfNotExists,
+ Input,
+ LangSmithTracing,
+ MultitaskStrategy,
+ OnCompletionBehavior,
+ QueryParamTypes,
+ Run,
+ RunCreate,
+ RunCreateMetadata,
+ RunSelectField,
+ RunStatus,
+ StreamMode,
+ StreamPart,
+ StreamPartV2,
+ StreamVersion,
+)
+
+
+async def _wrap_stream_v2(
+ raw: AsyncIterator[StreamPart],
+) -> AsyncIterator[StreamPartV2]:
+ """Wrap a raw SSE stream, converting each event to a v2 dict."""
+ async for part in raw:
+ v2 = _sse_to_v2_dict(part.event, part.data)
+ if v2 is not None:
+ yield v2 # ty: ignore[invalid-yield]
+
+
+class RunsClient:
+ """Client for managing runs in LangGraph.
+
+ A run is a single assistant invocation with optional input, config, context, and metadata.
+ This client manages runs, which can be stateful (on threads) or stateless.
+
+ ???+ example "Example"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ run = await client.runs.create(assistant_id="asst_123", thread_id="thread_456", input={"query": "Hello"})
+ ```
+ """
+
+ def __init__(self, http: HttpClient) -> None:
+ self.http = http
+
+ @overload
+ def stream(
+ self,
+ thread_id: str,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ stream_resumable: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ feedback_keys: Sequence[str] | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ webhook: str | None = None,
+ multitask_strategy: MultitaskStrategy | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ version: Literal["v1"] = "v1",
+ ) -> AsyncIterator[StreamPart]: ...
+
+ @overload
+ def stream(
+ self,
+ thread_id: str,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ stream_resumable: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ feedback_keys: Sequence[str] | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ webhook: str | None = None,
+ multitask_strategy: MultitaskStrategy | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ version: Literal["v2"],
+ ) -> AsyncIterator[StreamPartV2]: ...
+
+ @overload
+ def stream(
+ self,
+ thread_id: None,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ stream_resumable: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ feedback_keys: Sequence[str] | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ on_completion: OnCompletionBehavior | None = None,
+ if_not_exists: IfNotExists | None = None,
+ webhook: str | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ version: Literal["v1"] = "v1",
+ ) -> AsyncIterator[StreamPart]: ...
+
+ @overload
+ def stream(
+ self,
+ thread_id: None,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ stream_resumable: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ feedback_keys: Sequence[str] | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ on_completion: OnCompletionBehavior | None = None,
+ if_not_exists: IfNotExists | None = None,
+ webhook: str | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ version: Literal["v2"],
+ ) -> AsyncIterator[StreamPartV2]: ...
+
+ def stream(
+ self,
+ thread_id: str | None,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ stream_resumable: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None,
+ checkpoint_during: bool | None = None, # deprecated
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ feedback_keys: Sequence[str] | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ on_completion: OnCompletionBehavior | None = None,
+ webhook: str | None = None,
+ multitask_strategy: MultitaskStrategy | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ durability: Durability | None = None,
+ version: StreamVersion = "v1",
+ ) -> AsyncIterator[StreamPart | StreamPartV2]:
+ """Create a run and stream the results.
+
+ Args:
+ thread_id: the thread ID to assign to the thread.
+ If `None` will create a stateless run.
+ assistant_id: The assistant ID or graph name to stream from.
+ If using graph name, will default to first assistant created from that graph.
+ input: The input to the graph.
+ command: A command to execute. Cannot be combined with input.
+ stream_mode: The stream mode(s) to use.
+ stream_subgraphs: Whether to stream output from subgraphs.
+ stream_resumable: Whether the stream is considered resumable.
+ If true, the stream can be resumed and replayed in its entirety even after disconnection.
+ metadata: Metadata to assign to the run.
+ config: The configuration for the assistant.
+ context: Static context to add to the assistant.
+ !!! version-added "Added in version 0.6.0"
+ checkpoint: The checkpoint to resume from.
+ checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
+ interrupt_before: Nodes to interrupt immediately before they get executed.
+ interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
+ feedback_keys: Feedback keys to assign to run.
+ on_disconnect: The disconnect mode to use.
+ Must be one of 'cancel' or 'continue'.
+ on_completion: Whether to delete or keep the thread created for a stateless run.
+ Must be one of 'delete' or 'keep'.
+ webhook: Webhook to call after LangGraph API call is done.
+ multitask_strategy: Multitask strategy to use.
+ Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
+ if_not_exists: How to handle missing thread. Defaults to 'reject'.
+ Must be either 'reject' (raise error if missing), or 'create' (create new thread).
+ after_seconds: The number of seconds to wait before starting the run.
+ Use to schedule future runs.
+ langsmith_tracing: LangSmith tracing configuration. Allows routing traces
+ to a specific project or associating with a dataset example.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+ on_run_created: Callback when a run is created.
+ durability: The durability to use for the run. Values are "sync", "async", or "exit".
+ "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
+ "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
+ "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
+ version: Stream format version. "v1" (default) returns raw SSE StreamPart
+ NamedTuples. "v2" returns typed dicts with `type`, `ns`, and `data` keys.
+
+ Returns:
+ Asynchronous iterator of stream results.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024)
+ async for chunk in client.runs.stream(
+ thread_id=None,
+ assistant_id="agent",
+ input={"messages": [{"role": "user", "content": "how are you?"}]},
+ stream_mode=["values","debug"],
+ metadata={"name":"my_run"},
+ context={"model_name": "anthropic"},
+ interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
+ interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
+ feedback_keys=["my_feedback_key_1","my_feedback_key_2"],
+ webhook="https://my.fake.webhook.com",
+ multitask_strategy="interrupt"
+ ):
+ print(chunk)
+ ```
+
+ ```shell
+
+ ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+
+ StreamPart(event='metadata', data={'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2'})
+ StreamPart(event='values', data={'messages': [{'content': 'how are you?', 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'human', 'name': None, 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10', 'example': False}]})
+ StreamPart(event='values', data={'messages': [{'content': 'how are you?', 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'human', 'name': None, 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10', 'example': False}, {'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.", 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'ai', 'name': None, 'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b', 'example': False, 'tool_calls': [], 'invalid_tool_calls': [], 'usage_metadata': None}]})
+ StreamPart(event='end', data=None)
+ ```
+
+ """
+ if checkpoint_during is not None:
+ warnings.warn(
+ "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+ payload: dict[str, Any] = {
+ "input": input,
+ "command": (
+ {k: v for k, v in command.items() if v is not None} if command else None
+ ),
+ "config": config,
+ "context": context,
+ "metadata": metadata,
+ "stream_mode": stream_mode,
+ "stream_subgraphs": stream_subgraphs,
+ "stream_resumable": stream_resumable,
+ "assistant_id": assistant_id,
+ "interrupt_before": interrupt_before,
+ "interrupt_after": interrupt_after,
+ "feedback_keys": feedback_keys,
+ "webhook": webhook,
+ "checkpoint": checkpoint,
+ "checkpoint_id": checkpoint_id,
+ "checkpoint_during": checkpoint_during,
+ "multitask_strategy": multitask_strategy,
+ "if_not_exists": if_not_exists,
+ "on_disconnect": on_disconnect,
+ "on_completion": on_completion,
+ "after_seconds": after_seconds,
+ "durability": durability,
+ "langsmith_tracer": langsmith_tracing,
+ }
+ endpoint = (
+ f"/threads/{_quote_path_param(thread_id)}/runs/stream"
+ if thread_id is not None
+ else "/runs/stream"
+ )
+
+ def on_response(res: httpx.Response):
+ """Callback function to handle the response."""
+ if on_run_created and (metadata := _get_run_metadata_from_response(res)):
+ on_run_created(metadata)
+
+ raw = self.http.stream(
+ endpoint,
+ "POST",
+ json={k: v for k, v in payload.items() if v is not None},
+ params=params,
+ headers=headers,
+ on_response=on_response if on_run_created else None,
+ )
+ if version == "v2":
+ return _wrap_stream_v2(raw)
+ return raw
+
+ @overload
+ async def create(
+ self,
+ thread_id: None,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ stream_resumable: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ checkpoint_during: bool | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ webhook: str | None = None,
+ on_completion: OnCompletionBehavior | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ ) -> Run: ...
+
+ @overload
+ async def create(
+ self,
+ thread_id: str,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ stream_resumable: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ webhook: str | None = None,
+ multitask_strategy: MultitaskStrategy | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ ) -> Run: ...
+
+ async def create(
+ self,
+ thread_id: str | None,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ stream_resumable: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None,
+ checkpoint_during: bool | None = None, # deprecated
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ webhook: str | None = None,
+ multitask_strategy: MultitaskStrategy | None = None,
+ if_not_exists: IfNotExists | None = None,
+ on_completion: OnCompletionBehavior | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ durability: Durability | None = None,
+ ) -> Run:
+ """Create a background run.
+
+ Args:
+ thread_id: the thread ID to assign to the thread.
+ If `None` will create a stateless run.
+ assistant_id: The assistant ID or graph name to stream from.
+ If using graph name, will default to first assistant created from that graph.
+ input: The input to the graph.
+ command: A command to execute. Cannot be combined with input.
+ stream_mode: The stream mode(s) to use.
+ stream_subgraphs: Whether to stream output from subgraphs.
+ stream_resumable: Whether the stream is considered resumable.
+ If true, the stream can be resumed and replayed in its entirety even after disconnection.
+ metadata: Metadata to assign to the run.
+ config: The configuration for the assistant.
+ context: Static context to add to the assistant.
+ !!! version-added "Added in version 0.6.0"
+ checkpoint: The checkpoint to resume from.
+ checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
+ interrupt_before: Nodes to interrupt immediately before they get executed.
+ interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
+ webhook: Webhook to call after LangGraph API call is done.
+ multitask_strategy: Multitask strategy to use.
+ Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
+ on_completion: Whether to delete or keep the thread created for a stateless run.
+ Must be one of 'delete' or 'keep'.
+ if_not_exists: How to handle missing thread. Defaults to 'reject'.
+ Must be either 'reject' (raise error if missing), or 'create' (create new thread).
+ after_seconds: The number of seconds to wait before starting the run.
+ Use to schedule future runs.
+ langsmith_tracing: LangSmith tracing configuration. Allows routing traces
+ to a specific project or associating with a dataset example.
+ headers: Optional custom headers to include with the request.
+ on_run_created: Optional callback to call when a run is created.
+ durability: The durability to use for the run. Values are "sync", "async", or "exit".
+ "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
+ "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
+ "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
+
+ Returns:
+ The created background run.
+
+ ???+ example "Example Usage"
+
+ ```python
+
+ background_run = await client.runs.create(
+ thread_id="my_thread_id",
+ assistant_id="my_assistant_id",
+ input={"messages": [{"role": "user", "content": "hello!"}]},
+ metadata={"name":"my_run"},
+ context={"model_name": "openai"},
+ interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
+ interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
+ webhook="https://my.fake.webhook.com",
+ multitask_strategy="interrupt"
+ )
+ print(background_run)
+ ```
+
+ ```shell
+ --------------------------------------------------------------------------------
+
+ {
+ 'run_id': 'my_run_id',
+ 'thread_id': 'my_thread_id',
+ 'assistant_id': 'my_assistant_id',
+ 'created_at': '2024-07-25T15:35:42.598503+00:00',
+ 'updated_at': '2024-07-25T15:35:42.598503+00:00',
+ 'metadata': {},
+ 'status': 'pending',
+ 'kwargs':
+ {
+ 'input':
+ {
+ 'messages': [
+ {
+ 'role': 'user',
+ 'content': 'how are you?'
+ }
+ ]
+ },
+ 'config':
+ {
+ 'metadata':
+ {
+ 'created_by': 'system'
+ },
+ 'configurable':
+ {
+ 'run_id': 'my_run_id',
+ 'user_id': None,
+ 'graph_id': 'agent',
+ 'thread_id': 'my_thread_id',
+ 'checkpoint_id': None,
+ 'assistant_id': 'my_assistant_id'
+ },
+ },
+ 'context':
+ {
+ 'model_name': 'openai'
+ }
+ 'webhook': "https://my.fake.webhook.com",
+ 'temporary': False,
+ 'stream_mode': ['values'],
+ 'feedback_keys': None,
+ 'interrupt_after': ["node_to_stop_after_1","node_to_stop_after_2"],
+ 'interrupt_before': ["node_to_stop_before_1","node_to_stop_before_2"]
+ },
+ 'multitask_strategy': 'interrupt'
+ }
+ ```
+ """
+ if checkpoint_during is not None:
+ warnings.warn(
+ "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ payload = {
+ "input": input,
+ "command": (
+ {k: v for k, v in command.items() if v is not None} if command else None
+ ),
+ "stream_mode": stream_mode,
+ "stream_subgraphs": stream_subgraphs,
+ "stream_resumable": stream_resumable,
+ "config": config,
+ "context": context,
+ "metadata": metadata,
+ "assistant_id": assistant_id,
+ "interrupt_before": interrupt_before,
+ "interrupt_after": interrupt_after,
+ "webhook": webhook,
+ "checkpoint": checkpoint,
+ "checkpoint_id": checkpoint_id,
+ "checkpoint_during": checkpoint_during,
+ "multitask_strategy": multitask_strategy,
+ "if_not_exists": if_not_exists,
+ "on_completion": on_completion,
+ "after_seconds": after_seconds,
+ "durability": durability,
+ "langsmith_tracer": langsmith_tracing,
+ }
+ payload = {k: v for k, v in payload.items() if v is not None}
+
+ def on_response(res: httpx.Response):
+ """Callback function to handle the response."""
+ if on_run_created and (metadata := _get_run_metadata_from_response(res)):
+ on_run_created(metadata)
+
+ return await self.http.post(
+ f"/threads/{_quote_path_param(thread_id)}/runs" if thread_id else "/runs",
+ json=payload,
+ params=params,
+ headers=headers,
+ on_response=on_response if on_run_created else None,
+ )
+
+ async def create_batch(
+ self,
+ payloads: builtins.list[RunCreate],
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> builtins.list[Run]:
+ """Create a batch of stateless background runs."""
+
+ def filter_payload(payload: RunCreate):
+ return {k: v for k, v in payload.items() if v is not None}
+
+ filtered = [filter_payload(payload) for payload in payloads]
+ return await self.http.post(
+ "/runs/batch", json=filtered, headers=headers, params=params
+ )
+
+ @overload
+ async def wait(
+ self,
+ thread_id: str,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ webhook: str | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ multitask_strategy: MultitaskStrategy | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ raise_error: bool = True,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ ) -> builtins.list[dict] | dict[str, Any]: ...
+
+ @overload
+ async def wait(
+ self,
+ thread_id: None,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ webhook: str | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ on_completion: OnCompletionBehavior | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ raise_error: bool = True,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ ) -> builtins.list[dict] | dict[str, Any]: ...
+
+ async def wait(
+ self,
+ thread_id: str | None,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None,
+ checkpoint_during: bool | None = None, # deprecated
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ webhook: str | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ on_completion: OnCompletionBehavior | None = None,
+ multitask_strategy: MultitaskStrategy | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ raise_error: bool = True,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ durability: Durability | None = None,
+ ) -> builtins.list[dict] | dict[str, Any]:
+ """Create a run, wait until it finishes and return the final state.
+
+ Args:
+ thread_id: the thread ID to create the run on.
+ If `None` will create a stateless run.
+ assistant_id: The assistant ID or graph name to run.
+ If using graph name, will default to first assistant created from that graph.
+ input: The input to the graph.
+ command: A command to execute. Cannot be combined with input.
+ metadata: Metadata to assign to the run.
+ config: The configuration for the assistant.
+ context: Static context to add to the assistant.
+ !!! version-added "Added in version 0.6.0"
+ checkpoint: The checkpoint to resume from.
+ checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
+ interrupt_before: Nodes to interrupt immediately before they get executed.
+ interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
+ webhook: Webhook to call after LangGraph API call is done.
+ on_disconnect: The disconnect mode to use.
+ Must be one of 'cancel' or 'continue'.
+ on_completion: Whether to delete or keep the thread created for a stateless run.
+ Must be one of 'delete' or 'keep'.
+ multitask_strategy: Multitask strategy to use.
+ Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
+ if_not_exists: How to handle missing thread. Defaults to 'reject'.
+ Must be either 'reject' (raise error if missing), or 'create' (create new thread).
+ after_seconds: The number of seconds to wait before starting the run.
+ Use to schedule future runs.
+ langsmith_tracing: LangSmith tracing configuration. Allows routing traces
+ to a specific project or associating with a dataset example.
+ headers: Optional custom headers to include with the request.
+ on_run_created: Optional callback to call when a run is created.
+ durability: The durability to use for the run. Values are "sync", "async", or "exit".
+ "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
+ "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
+ "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
+
+ Returns:
+ The output of the run.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ final_state_of_run = await client.runs.wait(
+ thread_id=None,
+ assistant_id="agent",
+ input={"messages": [{"role": "user", "content": "how are you?"}]},
+ metadata={"name":"my_run"},
+ context={"model_name": "anthropic"},
+ interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
+ interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
+ webhook="https://my.fake.webhook.com",
+ multitask_strategy="interrupt"
+ )
+ print(final_state_of_run)
+ ```
+
+ ```shell
+ -------------------------------------------------------------------------------------------------------------------------------------------
+
+ {
+ 'messages': [
+ {
+ 'content': 'how are you?',
+ 'additional_kwargs': {},
+ 'response_metadata': {},
+ 'type': 'human',
+ 'name': None,
+ 'id': 'f51a862c-62fe-4866-863b-b0863e8ad78a',
+ 'example': False
+ },
+ {
+ 'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
+ 'additional_kwargs': {},
+ 'response_metadata': {},
+ 'type': 'ai',
+ 'name': None,
+ 'id': 'run-bf1cd3c6-768f-4c16-b62d-ba6f17ad8b36',
+ 'example': False,
+ 'tool_calls': [],
+ 'invalid_tool_calls': [],
+ 'usage_metadata': None
+ }
+ ]
+ }
+ ```
+
+ """
+ if checkpoint_during is not None:
+ warnings.warn(
+ "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ payload = {
+ "input": input,
+ "command": (
+ {k: v for k, v in command.items() if v is not None} if command else None
+ ),
+ "config": config,
+ "context": context,
+ "metadata": metadata,
+ "assistant_id": assistant_id,
+ "interrupt_before": interrupt_before,
+ "interrupt_after": interrupt_after,
+ "webhook": webhook,
+ "checkpoint": checkpoint,
+ "checkpoint_id": checkpoint_id,
+ "multitask_strategy": multitask_strategy,
+ "checkpoint_during": checkpoint_during,
+ "if_not_exists": if_not_exists,
+ "on_disconnect": on_disconnect,
+ "on_completion": on_completion,
+ "after_seconds": after_seconds,
+ "durability": durability,
+ "langsmith_tracer": langsmith_tracing,
+ }
+ endpoint = (
+ f"/threads/{_quote_path_param(thread_id)}/runs/wait"
+ if thread_id is not None
+ else "/runs/wait"
+ )
+
+ def on_response(res: httpx.Response):
+ """Callback function to handle the response."""
+ if on_run_created and (metadata := _get_run_metadata_from_response(res)):
+ on_run_created(metadata)
+
+ response = await self.http.request_reconnect(
+ endpoint,
+ "POST",
+ json={k: v for k, v in payload.items() if v is not None},
+ params=params,
+ headers=headers,
+ on_response=on_response if on_run_created else None,
+ )
+ if (
+ raise_error
+ and isinstance(response, dict)
+ and "__error__" in response
+ and isinstance(response["__error__"], dict)
+ ):
+ raise Exception(
+ f"{response['__error__'].get('error')}: {response['__error__'].get('message')}"
+ )
+ return response
+
+ async def list(
+ self,
+ thread_id: str,
+ *,
+ limit: int = 10,
+ offset: int = 0,
+ status: RunStatus | None = None,
+ select: builtins.list[RunSelectField] | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> builtins.list[Run]:
+ """List runs.
+
+ Args:
+ thread_id: The thread ID to list runs for.
+ limit: The maximum number of results to return.
+ offset: The number of results to skip.
+ status: The status of the run to filter by.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The runs for the thread.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ await client.runs.list(
+ thread_id="thread_id",
+ limit=5,
+ offset=5,
+ )
+ ```
+
+ """
+ query_params: dict[str, Any] = {
+ "limit": limit,
+ "offset": offset,
+ }
+ if status is not None:
+ query_params["status"] = status
+ if select:
+ query_params["select"] = select
+ if params:
+ query_params.update(params)
+ return await self.http.get(
+ f"/threads/{_quote_path_param(thread_id)}/runs",
+ params=query_params,
+ headers=headers,
+ )
+
+ async def get(
+ self,
+ thread_id: str,
+ run_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Run:
+ """Get a run.
+
+ Args:
+ thread_id: The thread ID to get.
+ run_id: The run ID to get.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `Run` object.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ run = await client.runs.get(
+ thread_id="thread_id_to_delete",
+ run_id="run_id_to_delete",
+ )
+ ```
+
+ """
+
+ return await self.http.get(
+ f"/threads/{_quote_path_param(thread_id)}/runs/{_quote_path_param(run_id)}",
+ headers=headers,
+ params=params,
+ )
+
+ async def cancel(
+ self,
+ thread_id: str,
+ run_id: str,
+ *,
+ wait: bool = False,
+ action: CancelAction = "interrupt",
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Get a run.
+
+ Args:
+ thread_id: The thread ID to cancel.
+ run_id: The run ID to cancel.
+ wait: Whether to wait until run has completed.
+ action: Action to take when cancelling the run. Possible values
+ are `interrupt` or `rollback`. Default is `interrupt`.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ await client.runs.cancel(
+ thread_id="thread_id_to_cancel",
+ run_id="run_id_to_cancel",
+ wait=True,
+ action="interrupt"
+ )
+ ```
+
+ """
+ query_params = {
+ "wait": 1 if wait else 0,
+ "action": action,
+ }
+ if params:
+ query_params.update(params)
+ if wait:
+ return await self.http.request_reconnect(
+ f"/threads/{_quote_path_param(thread_id)}/runs/{_quote_path_param(run_id)}/cancel",
+ "POST",
+ params=query_params,
+ headers=headers,
+ )
+ else:
+ return await self.http.post(
+ f"/threads/{_quote_path_param(thread_id)}/runs/{_quote_path_param(run_id)}/cancel",
+ json=None,
+ params=query_params,
+ headers=headers,
+ )
+
+ async def cancel_many(
+ self,
+ *,
+ thread_id: str | None = None,
+ run_ids: Sequence[str] | None = None,
+ status: BulkCancelRunsStatus | None = None,
+ action: CancelAction = "interrupt",
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Cancel one or more runs.
+
+ Can cancel runs by thread ID and run IDs, or by status filter.
+
+ Args:
+ thread_id: The ID of the thread containing runs to cancel.
+ run_ids: List of run IDs to cancel.
+ status: Filter runs by status to cancel. Must be one of
+ `"pending"`, `"running"`, or `"all"`.
+ action: Action to take when cancelling the run. Possible values
+ are `"interrupt"` or `"rollback"`. Default is `"interrupt"`.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ # Cancel all pending runs
+ await client.runs.cancel_many(status="pending")
+ # Cancel specific runs on a thread
+ await client.runs.cancel_many(
+ thread_id="my_thread_id",
+ run_ids=["run_1", "run_2"],
+ action="rollback",
+ )
+ ```
+
+ """
+ payload: dict[str, Any] = {}
+ if thread_id:
+ payload["thread_id"] = thread_id
+ if run_ids:
+ payload["run_ids"] = run_ids
+ if status:
+ payload["status"] = status
+ query_params: dict[str, Any] = {"action": action}
+ if params:
+ query_params.update(params)
+ await self.http.post(
+ "/runs/cancel",
+ json=payload,
+ headers=headers,
+ params=query_params,
+ )
+
+ async def join(
+ self,
+ thread_id: str,
+ run_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> dict:
+ """Block until a run is done. Returns the final state of the thread.
+
+ Args:
+ thread_id: The thread ID to join.
+ run_id: The run ID to join.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ result =await client.runs.join(
+ thread_id="thread_id_to_join",
+ run_id="run_id_to_join"
+ )
+ ```
+
+ """
+ return await self.http.request_reconnect(
+ f"/threads/{_quote_path_param(thread_id)}/runs/{_quote_path_param(run_id)}/join",
+ "GET",
+ headers=headers,
+ params=params,
+ )
+
+ def join_stream(
+ self,
+ thread_id: str,
+ run_id: str,
+ *,
+ cancel_on_disconnect: bool = False,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ last_event_id: str | None = None,
+ ) -> AsyncIterator[StreamPart]:
+ """Stream output from a run in real-time, until the run is done.
+ Output is not buffered, so any output produced before this call will
+ not be received here.
+
+ Args:
+ thread_id: The thread ID to join.
+ run_id: The run ID to join.
+ cancel_on_disconnect: Whether to cancel the run when the stream is disconnected.
+ stream_mode: The stream mode(s) to use. Must be a subset of the stream modes passed
+ when creating the run. Background runs default to having the union of all
+ stream modes.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+ last_event_id: The last event ID to use for the stream.
+
+ Returns:
+ The stream of parts.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ async for part in client.runs.join_stream(
+ thread_id="thread_id_to_join",
+ run_id="run_id_to_join",
+ stream_mode=["values", "debug"]
+ ):
+ print(part)
+ ```
+
+ """
+ query_params = {
+ "cancel_on_disconnect": cancel_on_disconnect,
+ "stream_mode": stream_mode,
+ }
+ if params:
+ query_params.update(params)
+ return self.http.stream(
+ f"/threads/{_quote_path_param(thread_id)}/runs/{_quote_path_param(run_id)}/stream",
+ "GET",
+ params=query_params,
+ headers={
+ **({"Last-Event-ID": last_event_id} if last_event_id else {}),
+ **(headers or {}),
+ }
+ or None,
+ )
+
+ async def delete(
+ self,
+ thread_id: str,
+ run_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Delete a run.
+
+ Args:
+ thread_id: The thread ID to delete.
+ run_id: The run ID to delete.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ await client.runs.delete(
+ thread_id="thread_id_to_delete",
+ run_id="run_id_to_delete"
+ )
+ ```
+
+ """
+ await self.http.delete(
+ f"/threads/{_quote_path_param(thread_id)}/runs/{_quote_path_param(run_id)}",
+ headers=headers,
+ params=params,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/store.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/store.py
new file mode 100644
index 0000000000000000000000000000000000000000..9efb2758150d16c30a95a0c0e73f2b8a708be11d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/store.py
@@ -0,0 +1,313 @@
+"""Async Store client for LangGraph SDK."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping, Sequence
+from typing import Any, Literal
+
+from langgraph_sdk._async.http import HttpClient
+from langgraph_sdk._shared.utilities import _provided_vals
+from langgraph_sdk.schema import (
+ Item,
+ ListNamespaceResponse,
+ QueryParamTypes,
+ SearchItemsResponse,
+)
+
+
+class StoreClient:
+ """Client for interacting with the graph's shared storage.
+
+ The Store provides a key-value storage system for persisting data across graph executions,
+ allowing for stateful operations and data sharing across threads.
+
+ ???+ example "Example"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ await client.store.put_item(["users", "user123"], "mem-123451342", {"name": "Alice", "score": 100})
+ ```
+ """
+
+ def __init__(self, http: HttpClient) -> None:
+ self.http = http
+
+ async def put_item(
+ self,
+ namespace: Sequence[str],
+ /,
+ key: str,
+ value: Mapping[str, Any],
+ index: Literal[False] | list[str] | None = None,
+ ttl: int | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Store or update an item.
+
+ Args:
+ namespace: A list of strings representing the namespace path.
+ key: The unique identifier for the item within the namespace.
+ value: A dictionary containing the item's data.
+ index: Controls search indexing - None (use defaults), False (disable), or list of field paths to index.
+ ttl: Optional time-to-live in minutes for the item, or None for no expiration.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ await client.store.put_item(
+ ["documents", "user123"],
+ key="item456",
+ value={"title": "My Document", "content": "Hello World"}
+ )
+ ```
+ """
+ for label in namespace:
+ if "." in label:
+ raise ValueError(
+ f"Invalid namespace label '{label}'. Namespace labels cannot contain periods ('.')."
+ )
+ payload = {
+ "namespace": namespace,
+ "key": key,
+ "value": value,
+ "index": index,
+ "ttl": ttl,
+ }
+ await self.http.put(
+ "/store/items", json=_provided_vals(payload), headers=headers, params=params
+ )
+
+ async def get_item(
+ self,
+ namespace: Sequence[str],
+ /,
+ key: str,
+ *,
+ refresh_ttl: bool | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Item:
+ """Retrieve a single item.
+
+ Args:
+ key: The unique identifier for the item.
+ namespace: Optional list of strings representing the namespace path.
+ refresh_ttl: Whether to refresh the TTL on this read operation. If `None`, uses the store's default behavior.
+
+ Returns:
+ Item: The retrieved item.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ item = await client.store.get_item(
+ ["documents", "user123"],
+ key="item456",
+ )
+ print(item)
+ ```
+ ```shell
+
+ ----------------------------------------------------------------
+
+ {
+ 'namespace': ['documents', 'user123'],
+ 'key': 'item456',
+ 'value': {'title': 'My Document', 'content': 'Hello World'},
+ 'created_at': '2024-07-30T12:00:00Z',
+ 'updated_at': '2024-07-30T12:00:00Z'
+ }
+ ```
+ """
+ for label in namespace:
+ if "." in label:
+ raise ValueError(
+ f"Invalid namespace label '{label}'. Namespace labels cannot contain periods ('.')."
+ )
+ get_params: dict[str, Any] = {"namespace": ".".join(namespace), "key": key}
+ if refresh_ttl is not None:
+ get_params["refresh_ttl"] = refresh_ttl
+ if params:
+ get_params = {**get_params, **dict(params)}
+ return await self.http.get("/store/items", params=get_params, headers=headers)
+
+ async def delete_item(
+ self,
+ namespace: Sequence[str],
+ /,
+ key: str,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Delete an item.
+
+ Args:
+ key: The unique identifier for the item.
+ namespace: Optional list of strings representing the namespace path.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ await client.store.delete_item(
+ ["documents", "user123"],
+ key="item456",
+ )
+ ```
+ """
+ await self.http.delete(
+ "/store/items",
+ json={"namespace": namespace, "key": key},
+ headers=headers,
+ params=params,
+ )
+
+ async def search_items(
+ self,
+ namespace_prefix: Sequence[str],
+ /,
+ filter: Mapping[str, Any] | None = None,
+ limit: int = 10,
+ offset: int = 0,
+ query: str | None = None,
+ refresh_ttl: bool | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> SearchItemsResponse:
+ """Search for items within a namespace prefix.
+
+ Args:
+ namespace_prefix: List of strings representing the namespace prefix.
+ filter: Optional dictionary of key-value pairs to filter results.
+ limit: Maximum number of items to return (default is 10).
+ offset: Number of items to skip before returning results (default is 0).
+ query: Optional query for natural language search.
+ refresh_ttl: Whether to refresh the TTL on items returned by this search. If `None`, uses the store's default behavior.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ A list of items matching the search criteria.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ items = await client.store.search_items(
+ ["documents"],
+ filter={"author": "John Doe"},
+ limit=5,
+ offset=0
+ )
+ print(items)
+ ```
+ ```shell
+
+ ----------------------------------------------------------------
+
+ {
+ "items": [
+ {
+ "namespace": ["documents", "user123"],
+ "key": "item789",
+ "value": {
+ "title": "Another Document",
+ "author": "John Doe"
+ },
+ "created_at": "2024-07-30T12:00:00Z",
+ "updated_at": "2024-07-30T12:00:00Z"
+ },
+ # ... additional items ...
+ ]
+ }
+ ```
+ """
+ payload = {
+ "namespace_prefix": namespace_prefix,
+ "filter": filter,
+ "limit": limit,
+ "offset": offset,
+ "query": query,
+ "refresh_ttl": refresh_ttl,
+ }
+
+ return await self.http.post(
+ "/store/items/search",
+ json=_provided_vals(payload),
+ headers=headers,
+ params=params,
+ )
+
+ async def list_namespaces(
+ self,
+ prefix: list[str] | None = None,
+ suffix: list[str] | None = None,
+ max_depth: int | None = None,
+ limit: int = 100,
+ offset: int = 0,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> ListNamespaceResponse:
+ """List namespaces with optional match conditions.
+
+ Args:
+ prefix: Optional list of strings representing the prefix to filter namespaces.
+ suffix: Optional list of strings representing the suffix to filter namespaces.
+ max_depth: Optional integer specifying the maximum depth of namespaces to return.
+ limit: Maximum number of namespaces to return (default is 100).
+ offset: Number of namespaces to skip before returning results (default is 0).
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ A list of namespaces matching the criteria.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ namespaces = await client.store.list_namespaces(
+ prefix=["documents"],
+ max_depth=3,
+ limit=10,
+ offset=0
+ )
+ print(namespaces)
+
+ ----------------------------------------------------------------
+
+ [
+ ["documents", "user123", "reports"],
+ ["documents", "user456", "invoices"],
+ ...
+ ]
+ ```
+ """
+ payload = {
+ "prefix": prefix,
+ "suffix": suffix,
+ "max_depth": max_depth,
+ "limit": limit,
+ "offset": offset,
+ }
+ return await self.http.post(
+ "/store/namespaces",
+ json=_provided_vals(payload),
+ headers=headers,
+ params=params,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/threads.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/threads.py
new file mode 100644
index 0000000000000000000000000000000000000000..7dbe003c9289d1b1acdb76db92d53acf49660f06
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_async/threads.py
@@ -0,0 +1,782 @@
+"""Async client for managing threads in LangGraph."""
+
+from __future__ import annotations
+
+from collections.abc import AsyncIterator, Mapping, Sequence
+from typing import Any, Literal, overload
+
+from langgraph_sdk._async.http import HttpClient
+from langgraph_sdk._shared.utilities import _quote_path_param
+from langgraph_sdk.schema import (
+ Checkpoint,
+ Json,
+ OnConflictBehavior,
+ PruneStrategy,
+ QueryParamTypes,
+ SortOrder,
+ StreamPart,
+ Thread,
+ ThreadSelectField,
+ ThreadSortBy,
+ ThreadState,
+ ThreadStatus,
+ ThreadStreamMode,
+ ThreadUpdateStateResponse,
+)
+
+
+class ThreadsClient:
+ """Client for managing threads in LangGraph.
+
+ A thread maintains the state of a graph across multiple interactions/invocations (aka runs).
+ It accumulates and persists the graph's state, allowing for continuity between separate
+ invocations of the graph.
+
+ ???+ example "Example"
+
+ ```python
+ client = get_client(url="http://localhost:2024"))
+ new_thread = await client.threads.create(metadata={"user_id": "123"})
+ ```
+ """
+
+ def __init__(self, http: HttpClient) -> None:
+ self.http = http
+
+ async def get(
+ self,
+ thread_id: str,
+ *,
+ include: Sequence[str] | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Thread:
+ """Get a thread by ID.
+
+ Args:
+ thread_id: The ID of the thread to get.
+ include: Additional fields to include in the response.
+ Supported values: `"ttl"`.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ Thread object.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ thread = await client.threads.get(
+ thread_id="my_thread_id"
+ )
+ print(thread)
+ ```
+
+ ```shell
+ -----------------------------------------------------
+
+ {
+ 'thread_id': 'my_thread_id',
+ 'created_at': '2024-07-18T18:35:15.540834+00:00',
+ 'updated_at': '2024-07-18T18:35:15.540834+00:00',
+ 'metadata': {'graph_id': 'agent'}
+ }
+ ```
+
+ """
+ query_params: dict[str, Any] = {}
+ if include:
+ query_params["include"] = ",".join(include)
+ if params:
+ query_params.update(params)
+ return await self.http.get(
+ f"/threads/{_quote_path_param(thread_id)}",
+ headers=headers,
+ params=query_params or None,
+ )
+
+ async def create(
+ self,
+ *,
+ metadata: Json = None,
+ thread_id: str | None = None,
+ if_exists: OnConflictBehavior | None = None,
+ supersteps: Sequence[dict[str, Sequence[dict[str, Any]]]] | None = None,
+ graph_id: str | None = None,
+ ttl: int | Mapping[str, Any] | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Thread:
+ """Create a new thread.
+
+ Args:
+ metadata: Metadata to add to thread.
+ thread_id: ID of thread.
+ If `None`, ID will be a randomly generated UUID.
+ if_exists: How to handle duplicate creation. Defaults to 'raise' under the hood.
+ Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing thread).
+ supersteps: Apply a list of supersteps when creating a thread, each containing a sequence of updates.
+ Each update has `values` or `command` and `as_node`. Used for copying a thread between deployments.
+ graph_id: Optional graph ID to associate with the thread.
+ ttl: Optional time-to-live in minutes for the thread. You can pass an
+ integer (minutes) or a mapping with keys `ttl` and optional
+ `strategy` (defaults to "delete").
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The created thread.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ thread = await client.threads.create(
+ metadata={"number":1},
+ thread_id="my-thread-id",
+ if_exists="raise"
+ )
+ ```
+ """
+ payload: dict[str, Any] = {}
+ if thread_id:
+ payload["thread_id"] = thread_id
+ if metadata or graph_id:
+ payload["metadata"] = {
+ **(metadata or {}),
+ **({"graph_id": graph_id} if graph_id else {}),
+ }
+ if if_exists:
+ payload["if_exists"] = if_exists
+ if supersteps:
+ payload["supersteps"] = [
+ {
+ "updates": [
+ {
+ "values": u["values"],
+ "command": u.get("command"),
+ "as_node": u["as_node"],
+ }
+ for u in s["updates"]
+ ]
+ }
+ for s in supersteps
+ ]
+ if ttl is not None:
+ if isinstance(ttl, (int, float)):
+ payload["ttl"] = {"ttl": ttl, "strategy": "delete"}
+ else:
+ payload["ttl"] = ttl
+
+ return await self.http.post(
+ "/threads", json=payload, headers=headers, params=params
+ )
+
+ @overload
+ async def update(
+ self,
+ thread_id: str,
+ *,
+ metadata: Mapping[str, Any],
+ ttl: int | Mapping[str, Any] | None = None,
+ return_minimal: Literal[False] = False,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Thread: ...
+
+ @overload
+ async def update(
+ self,
+ thread_id: str,
+ *,
+ metadata: Mapping[str, Any],
+ ttl: int | Mapping[str, Any] | None = None,
+ return_minimal: Literal[True],
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None: ...
+
+ @overload
+ async def update(
+ self,
+ thread_id: str,
+ *,
+ metadata: Mapping[str, Any],
+ ttl: int | Mapping[str, Any] | None = None,
+ return_minimal: bool,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Thread | None: ...
+
+ async def update(
+ self,
+ thread_id: str,
+ *,
+ metadata: Mapping[str, Any],
+ ttl: int | Mapping[str, Any] | None = None,
+ return_minimal: bool = False,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Thread | None:
+ """Update a thread.
+
+ Args:
+ thread_id: ID of thread to update.
+ metadata: Metadata to merge with existing thread metadata.
+ ttl: Optional time-to-live in minutes for the thread. You can pass an
+ integer (minutes) or a mapping with keys `ttl` and optional
+ `strategy` (defaults to "delete").
+ return_minimal: If `True`, request a 204 response with no body.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The updated thread, or `None` when `return_minimal=True`.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ thread = await client.threads.update(
+ thread_id="my-thread-id",
+ metadata={"number":1},
+ ttl=43_200,
+ )
+ ```
+ """
+ payload: dict[str, Any] = {"metadata": metadata}
+ if ttl is not None:
+ if isinstance(ttl, (int, float)):
+ payload["ttl"] = {"ttl": ttl, "strategy": "delete"}
+ else:
+ payload["ttl"] = ttl
+ request_headers = dict(headers or {})
+ if return_minimal:
+ request_headers["Prefer"] = "return=minimal"
+ return await self.http.patch(
+ f"/threads/{_quote_path_param(thread_id)}",
+ json=payload,
+ headers=request_headers or None,
+ params=params,
+ )
+
+ async def delete(
+ self,
+ thread_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Delete a thread.
+
+ Args:
+ thread_id: The ID of the thread to delete.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost2024)
+ await client.threads.delete(
+ thread_id="my_thread_id"
+ )
+ ```
+
+ """
+ await self.http.delete(
+ f"/threads/{_quote_path_param(thread_id)}", headers=headers, params=params
+ )
+
+ async def search(
+ self,
+ *,
+ metadata: Json = None,
+ values: Json = None,
+ ids: Sequence[str] | None = None,
+ status: ThreadStatus | None = None,
+ limit: int = 10,
+ offset: int = 0,
+ sort_by: ThreadSortBy | None = None,
+ sort_order: SortOrder | None = None,
+ select: list[ThreadSelectField] | None = None,
+ extract: dict[str, str] | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> list[Thread]:
+ """Search for threads.
+
+ Args:
+ metadata: Thread metadata to filter on.
+ values: State values to filter on.
+ ids: List of thread IDs to filter by.
+ status: Thread status to filter on.
+ Must be one of 'idle', 'busy', 'interrupted' or 'error'.
+ limit: Limit on number of threads to return.
+ offset: Offset in threads table to start search from.
+ sort_by: Sort by field.
+ sort_order: Sort order.
+ select: List of fields to include in the response.
+ extract: Dictionary mapping aliases to JSONB paths to extract
+ from thread data. Paths use dot notation for nested keys and
+ bracket notation for array indices (e.g.,
+ `{"last_msg": "values.messages[-1]"}`). Extracted values are
+ returned in an `extracted` field on each thread. Maximum 10
+ paths per request.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ List of the threads matching the search parameters.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ threads = await client.threads.search(
+ metadata={"number":1},
+ status="interrupted",
+ limit=15,
+ offset=5
+ )
+ ```
+
+ """
+ payload: dict[str, Any] = {
+ "limit": limit,
+ "offset": offset,
+ }
+ if metadata:
+ payload["metadata"] = metadata
+ if values:
+ payload["values"] = values
+ if ids:
+ payload["ids"] = ids
+ if status:
+ payload["status"] = status
+ if sort_by:
+ payload["sort_by"] = sort_by
+ if sort_order:
+ payload["sort_order"] = sort_order
+ if select:
+ payload["select"] = select
+ if extract:
+ payload["extract"] = extract
+ return await self.http.post(
+ "/threads/search",
+ json=payload,
+ headers=headers,
+ params=params,
+ )
+
+ async def count(
+ self,
+ *,
+ metadata: Json = None,
+ values: Json = None,
+ status: ThreadStatus | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> int:
+ """Count threads matching filters.
+
+ Args:
+ metadata: Thread metadata to filter on.
+ values: State values to filter on.
+ status: Thread status to filter on.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ int: Number of threads matching the criteria.
+ """
+ payload: dict[str, Any] = {}
+ if metadata:
+ payload["metadata"] = metadata
+ if values:
+ payload["values"] = values
+ if status:
+ payload["status"] = status
+ return await self.http.post(
+ "/threads/count", json=payload, headers=headers, params=params
+ )
+
+ async def copy(
+ self,
+ thread_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Copy a thread.
+
+ Args:
+ thread_id: The ID of the thread to copy.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024)
+ await client.threads.copy(
+ thread_id="my_thread_id"
+ )
+ ```
+
+ """
+ return await self.http.post(
+ f"/threads/{_quote_path_param(thread_id)}/copy",
+ json=None,
+ headers=headers,
+ params=params,
+ )
+
+ async def prune(
+ self,
+ thread_ids: Sequence[str],
+ *,
+ strategy: PruneStrategy = "delete",
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> dict[str, Any]:
+ """Prune threads by ID.
+
+ Args:
+ thread_ids: List of thread IDs to prune.
+ strategy: The prune strategy. `"delete"` removes threads entirely.
+ `"keep_latest"` prunes old checkpoints but keeps threads and their
+ latest state. Defaults to `"delete"`.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ A dict containing `pruned_count` (number of threads pruned).
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024")
+ result = await client.threads.prune(
+ thread_ids=["thread_1", "thread_2"],
+ )
+ print(result) # {'pruned_count': 2}
+ ```
+
+ """
+ payload: dict[str, Any] = {
+ "thread_ids": thread_ids,
+ }
+ if strategy != "delete":
+ payload["strategy"] = strategy
+ return await self.http.post(
+ "/threads/prune", json=payload, headers=headers, params=params
+ )
+
+ async def get_state(
+ self,
+ thread_id: str,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None, # deprecated
+ *,
+ subgraphs: bool = False,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> ThreadState:
+ """Get the state of a thread.
+
+ Args:
+ thread_id: The ID of the thread to get the state of.
+ checkpoint: The checkpoint to get the state of.
+ checkpoint_id: (deprecated) The checkpoint ID to get the state of.
+ subgraphs: Include subgraphs states.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The thread of the state.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024)
+ thread_state = await client.threads.get_state(
+ thread_id="my_thread_id",
+ checkpoint_id="my_checkpoint_id"
+ )
+ print(thread_state)
+ ```
+
+ ```shell
+ ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
+
+ {
+ 'values': {
+ 'messages': [
+ {
+ 'content': 'how are you?',
+ 'additional_kwargs': {},
+ 'response_metadata': {},
+ 'type': 'human',
+ 'name': None,
+ 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10',
+ 'example': False
+ },
+ {
+ 'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
+ 'additional_kwargs': {},
+ 'response_metadata': {},
+ 'type': 'ai',
+ 'name': None,
+ 'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
+ 'example': False,
+ 'tool_calls': [],
+ 'invalid_tool_calls': [],
+ 'usage_metadata': None
+ }
+ ]
+ },
+ 'next': [],
+ 'checkpoint':
+ {
+ 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
+ 'checkpoint_ns': '',
+ 'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1'
+ }
+ 'metadata':
+ {
+ 'step': 1,
+ 'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2',
+ 'source': 'loop',
+ 'writes':
+ {
+ 'agent':
+ {
+ 'messages': [
+ {
+ 'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
+ 'name': None,
+ 'type': 'ai',
+ 'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
+ 'example': False,
+ 'tool_calls': [],
+ 'usage_metadata': None,
+ 'additional_kwargs': {},
+ 'response_metadata': {},
+ 'invalid_tool_calls': []
+ }
+ ]
+ }
+ },
+ 'user_id': None,
+ 'graph_id': 'agent',
+ 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
+ 'created_by': 'system',
+ 'assistant_id': 'fe096781-5601-53d2-b2f6-0d3403f7e9ca'},
+ 'created_at': '2024-07-25T15:35:44.184703+00:00',
+ 'parent_config':
+ {
+ 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
+ 'checkpoint_ns': '',
+ 'checkpoint_id': '1ef4a9b8-d80d-6fa7-8000-9300467fad0f'
+ }
+ }
+ ```
+ """
+ if checkpoint:
+ return await self.http.post(
+ f"/threads/{_quote_path_param(thread_id)}/state/checkpoint",
+ json={"checkpoint": checkpoint, "subgraphs": subgraphs},
+ headers=headers,
+ params=params,
+ )
+ elif checkpoint_id:
+ get_params = {"subgraphs": subgraphs}
+ if params:
+ get_params = {**get_params, **dict(params)}
+ return await self.http.get(
+ f"/threads/{_quote_path_param(thread_id)}/state/{_quote_path_param(checkpoint_id)}",
+ params=get_params,
+ headers=headers,
+ )
+ else:
+ get_params = {"subgraphs": subgraphs}
+ if params:
+ get_params = {**get_params, **dict(params)}
+ return await self.http.get(
+ f"/threads/{_quote_path_param(thread_id)}/state",
+ params=get_params,
+ headers=headers,
+ )
+
+ async def update_state(
+ self,
+ thread_id: str,
+ values: dict[str, Any] | Sequence[dict] | None,
+ *,
+ as_node: str | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None, # deprecated
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> ThreadUpdateStateResponse:
+ """Update the state of a thread.
+
+ Args:
+ thread_id: The ID of the thread to update.
+ values: The values to update the state with.
+ as_node: Update the state as if this node had just executed.
+ checkpoint: The checkpoint to update the state of.
+ checkpoint_id: (deprecated) The checkpoint ID to update the state of.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ Response after updating a thread's state.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024)
+ response = await client.threads.update_state(
+ thread_id="my_thread_id",
+ values={"messages":[{"role": "user", "content": "hello!"}]},
+ as_node="my_node",
+ )
+ print(response)
+ ```
+ ```shell
+
+ ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
+
+ {
+ 'checkpoint': {
+ 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
+ 'checkpoint_ns': '',
+ 'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1',
+ 'checkpoint_map': {}
+ }
+ }
+ ```
+ """
+ payload: dict[str, Any] = {
+ "values": values,
+ }
+ if checkpoint_id:
+ payload["checkpoint_id"] = checkpoint_id
+ if checkpoint:
+ payload["checkpoint"] = checkpoint
+ if as_node:
+ payload["as_node"] = as_node
+ return await self.http.post(
+ f"/threads/{_quote_path_param(thread_id)}/state",
+ json=payload,
+ headers=headers,
+ params=params,
+ )
+
+ async def get_history(
+ self,
+ thread_id: str,
+ *,
+ limit: int = 10,
+ before: str | Checkpoint | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ checkpoint: Checkpoint | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> list[ThreadState]:
+ """Get the state history of a thread.
+
+ Args:
+ thread_id: The ID of the thread to get the state history for.
+ checkpoint: Return states for this subgraph. If empty defaults to root.
+ limit: The maximum number of states to return.
+ before: Return states before this checkpoint.
+ metadata: Filter states by metadata key-value pairs.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The state history of the thread.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_client(url="http://localhost:2024)
+ thread_state = await client.threads.get_history(
+ thread_id="my_thread_id",
+ limit=5,
+ )
+ ```
+
+ """
+ payload: dict[str, Any] = {
+ "limit": limit,
+ }
+ if before:
+ payload["before"] = before
+ if metadata:
+ payload["metadata"] = metadata
+ if checkpoint:
+ payload["checkpoint"] = checkpoint
+ return await self.http.post(
+ f"/threads/{_quote_path_param(thread_id)}/history",
+ json=payload,
+ headers=headers,
+ params=params,
+ )
+
+ async def join_stream(
+ self,
+ thread_id: str,
+ *,
+ last_event_id: str | None = None,
+ stream_mode: ThreadStreamMode | Sequence[ThreadStreamMode] = "run_modes",
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> AsyncIterator[StreamPart]:
+ """Get a stream of events for a thread.
+
+ Args:
+ thread_id: The ID of the thread to get the stream for.
+ last_event_id: The ID of the last event to get.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ An iterator of stream parts.
+
+ ???+ example "Example Usage"
+
+ ```python
+
+ for chunk in client.threads.join_stream(
+ thread_id="my_thread_id",
+ last_event_id="my_event_id",
+ ):
+ print(chunk)
+ ```
+
+ """
+ query_params = {
+ "stream_mode": stream_mode,
+ }
+ if params:
+ query_params.update(params)
+ return self.http.stream(
+ f"/threads/{_quote_path_param(thread_id)}/stream",
+ "GET",
+ headers={
+ **({"Last-Event-ID": last_event_id} if last_event_id else {}),
+ **(headers or {}),
+ },
+ params=query_params,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_shared/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_shared/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5783ce0c2365d7063cec3d2bf9fdfaefc557575b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_shared/__init__.py
@@ -0,0 +1 @@
+"""Shared utilities for async and sync clients."""
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_shared/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_shared/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3c2677bdf34c8a3681e8f6285c79d6ee516baa11
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_shared/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_shared/__pycache__/types.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_shared/__pycache__/types.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2dc4d2858721a53b0086e459da5c58a431377cd0
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_shared/__pycache__/types.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_shared/__pycache__/utilities.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_shared/__pycache__/utilities.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a5089bbe220901039a18cd78adf2814b98e68407
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_shared/__pycache__/utilities.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_shared/types.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_shared/types.py
new file mode 100644
index 0000000000000000000000000000000000000000..073b1380a249c620c5e788dda25bb321a484e60d
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_shared/types.py
@@ -0,0 +1,10 @@
+"""Type aliases and constants."""
+
+from __future__ import annotations
+
+TimeoutTypes = (
+ None
+ | float
+ | tuple[float | None, float | None]
+ | tuple[float | None, float | None, float | None, float | None]
+)
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_shared/utilities.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_shared/utilities.py
new file mode 100644
index 0000000000000000000000000000000000000000..da2db64377a03a772cbc6e22d71ae85ee6aa50bd
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_shared/utilities.py
@@ -0,0 +1,251 @@
+"""Shared utility functions for async and sync clients."""
+
+from __future__ import annotations
+
+import functools
+import os
+import re
+from collections.abc import Mapping
+from datetime import tzinfo
+from typing import TYPE_CHECKING, Any, cast
+from urllib.parse import quote, urlparse
+
+import httpx
+
+import langgraph_sdk
+from langgraph_sdk.schema import RunCreateMetadata
+
+if TYPE_CHECKING:
+ from zoneinfo import ZoneInfo
+
+RESERVED_HEADERS = ("x-api-key",)
+
+NOT_PROVIDED = cast(None, object())
+
+
+def _get_api_key(api_key: str | None = NOT_PROVIDED) -> str | None:
+ """Get the API key from the environment.
+ Precedence:
+ 1. explicit string argument
+ 2. LANGGRAPH_API_KEY (if api_key not provided)
+ 3. LANGSMITH_API_KEY (if api_key not provided)
+ 4. LANGCHAIN_API_KEY (if api_key not provided)
+
+ Args:
+ api_key: The API key to use. Can be:
+ - A string: use this exact API key
+ - None: explicitly skip loading from environment
+ - NOT_PROVIDED (default): auto-load from environment variables
+ """
+ if isinstance(api_key, str):
+ return api_key
+ if api_key is NOT_PROVIDED:
+ # api_key is not explicitly provided, try to load from environment
+ for prefix in ["LANGGRAPH", "LANGSMITH", "LANGCHAIN"]:
+ if env := os.getenv(f"{prefix}_API_KEY"):
+ return env.strip().strip('"').strip("'")
+ # api_key is explicitly None, don't load from environment
+ return None
+
+
+def _get_headers(
+ api_key: str | None,
+ custom_headers: Mapping[str, str] | None,
+) -> dict[str, str]:
+ """Combine api_key and custom user-provided headers."""
+ custom_headers = custom_headers or {}
+ for header in RESERVED_HEADERS:
+ if header in custom_headers:
+ raise ValueError(f"Cannot set reserved header '{header}'")
+
+ headers = {
+ "User-Agent": f"langgraph-sdk-py/{langgraph_sdk.__version__}",
+ **custom_headers,
+ }
+ resolved_api_key = _get_api_key(api_key)
+ if resolved_api_key:
+ headers["x-api-key"] = resolved_api_key
+
+ return headers
+
+
+def _orjson_default(obj: Any) -> Any:
+ is_class = isinstance(obj, type)
+ if hasattr(obj, "model_dump") and callable(obj.model_dump):
+ if is_class:
+ raise TypeError(
+ f"Cannot JSON-serialize type object: {obj!r}. Did you mean to pass an instance of the object instead?"
+ f"\nReceived type: {obj!r}"
+ )
+ return obj.model_dump()
+ elif hasattr(obj, "dict") and callable(obj.dict):
+ if is_class:
+ raise TypeError(
+ f"Cannot JSON-serialize type object: {obj!r}. Did you mean to pass an instance of the object instead?"
+ f"\nReceived type: {obj!r}"
+ )
+ return obj.dict()
+ elif isinstance(obj, (set, frozenset)):
+ return list(obj)
+ else:
+ raise TypeError(f"Object of type {type(obj)} is not JSON serializable")
+
+
+# Compiled regex pattern for extracting run metadata from Content-Location header
+_RUN_METADATA_PATTERN = re.compile(
+ r"(\/threads\/(?P.+))?\/runs\/(?P.+)"
+)
+
+
+def _get_run_metadata_from_response(
+ response: httpx.Response,
+) -> RunCreateMetadata | None:
+ """Extract run metadata from the response headers."""
+ if (content_location := response.headers.get("Content-Location")) and (
+ match := _RUN_METADATA_PATTERN.search(content_location)
+ ):
+ return RunCreateMetadata(
+ run_id=match.group("run_id"),
+ thread_id=match.group("thread_id") or None,
+ )
+
+ return None
+
+
+def _sse_to_v2_dict(event: str, data: Any) -> dict[str, Any] | None:
+ """Convert an SSE event+data pair into a v2 stream part dict.
+
+ Returns None for ``end`` events (signals end of stream).
+ """
+ if event == "end":
+ return None
+ parts = event.split("|")
+ event_type = parts[0]
+ ns = parts[1:] if len(parts) > 1 else []
+ result: dict[str, Any] = {"type": event_type, "ns": ns, "data": data}
+ if event_type == "values" and isinstance(data, dict):
+ result["interrupts"] = data.pop("__interrupt__", [])
+ else:
+ result["interrupts"] = []
+ return result
+
+
+def _resolve_timezone(tz: str | tzinfo | ZoneInfo | None) -> str | None:
+ """Convert a timezone argument to an IANA timezone string.
+
+ Accepts:
+ - A string (returned as-is, assumed to be an IANA timezone name)
+ - A ``datetime.tzinfo`` instance (e.g. ``zoneinfo.ZoneInfo("America/New_York")``,
+ ``datetime.timezone.utc``). The ``key`` attribute is used if available,
+ otherwise ``tzname(None)`` is used.
+ - ``None`` (returned as ``None``)
+ """
+ if tz is None or isinstance(tz, str):
+ return tz
+ if isinstance(tz, tzinfo):
+ # ZoneInfo objects have a .key attribute with the IANA name
+ key = getattr(tz, "key", None)
+ if isinstance(key, str):
+ return key
+ # Fall back to tzname for fixed-offset timezones like datetime.timezone.utc
+ name = tz.tzname(None)
+ if name is not None:
+ return name
+ raise ValueError(
+ f"Cannot determine timezone name from {tz!r}. "
+ "Use a zoneinfo.ZoneInfo instance or pass a string like 'America/New_York'."
+ )
+ raise TypeError(
+ f"Expected str, datetime.tzinfo, or None for timezone, got {type(tz).__name__}"
+ )
+
+
+def _default_port(scheme: str) -> int:
+ return 443 if scheme == "https" else 80
+
+
+def _validate_reconnect_location(base_url: httpx.URL, location: str) -> str:
+ """Validate that a reconnect Location URL is same-origin as the base URL.
+
+ Raises ValueError if the Location header points to a different origin
+ (scheme + host + port), which would leak credentials to an external server.
+ """
+ parsed = urlparse(location)
+ # Relative URLs are safe — they resolve against the base
+ if not parsed.scheme and not parsed.netloc:
+ return location
+ # Compare origin components (normalize default ports to avoid mismatches)
+ base_scheme = str(base_url.scheme)
+ base_origin = (
+ base_scheme,
+ str(base_url.host),
+ base_url.port or _default_port(base_scheme),
+ )
+ loc_origin = (
+ parsed.scheme,
+ parsed.hostname or "",
+ parsed.port or _default_port(parsed.scheme),
+ )
+ if base_origin != loc_origin:
+ raise ValueError(
+ f"Refusing to follow cross-origin reconnect Location: {location!r} "
+ f"(origin {loc_origin}) does not match base URL origin {base_origin}"
+ )
+ return location
+
+
+def _provided_vals(d: Mapping[str, Any]) -> dict[str, Any]:
+ return {k: v for k, v in d.items() if v is not None}
+
+
+def _quote_path_param(value: Any) -> str:
+ """Encode a value for safe interpolation into a request path segment.
+
+ Path segments are encoded with ``safe=""`` so that ``/`` and other reserved
+ characters are escaped. Standalone dot-segments (``.`` and ``..``) are also
+ encoded because some URL-handling stacks (including ``httpx``) collapse
+ them client-side as relative-path traversal before transmission. The value
+ is coerced to ``str`` so callers can pass ``uuid.UUID`` and similar types
+ directly without changing call sites.
+
+ A properly formed identifier (for example, a standard UUID, which contains
+ no dots or reserved characters) round-trips through this function
+ unchanged.
+
+ Raises:
+ TypeError: If `value` is `None` or a `bytes`/`bytearray` instance.
+ Coercing those would produce misleading paths (e.g. `/threads/None`),
+ so surface the caller bug instead.
+ """
+ if value is None:
+ raise TypeError("path parameter must not be None")
+ if isinstance(value, (bytes, bytearray)):
+ raise TypeError("path parameter must not be bytes; pass a str or uuid.UUID")
+ quoted = quote(str(value), safe="")
+ # Bare "." or ".." (or any all-dot string) acts as a relative-path segment
+ # that some HTTP stacks (including ``httpx``) collapse client-side before
+ # transmission. Encode the dots so the segment becomes opaque to that
+ # logic. Mixed values like "agent.v1" are unaffected.
+ if quoted and all(c == "." for c in quoted):
+ quoted = "%2E" * len(quoted)
+ return quoted
+
+
+_registered_transports: list[httpx.ASGITransport] = []
+
+
+# Do not move; this is used in the server.
+def configure_loopback_transports(app: Any) -> None:
+ for transport in _registered_transports:
+ transport.app = app
+
+
+@functools.lru_cache(maxsize=1)
+def get_asgi_transport() -> type[httpx.ASGITransport]:
+ try:
+ from langgraph_api import asgi_transport # ty: ignore[unresolved-import]
+
+ return asgi_transport.ASGITransport
+ except ImportError:
+ # Older versions of the server
+ return httpx.ASGITransport
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ab36bf804bf431c415683bae0e69d7baa813bd7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__init__.py
@@ -0,0 +1,20 @@
+"""Sync client exports."""
+
+from langgraph_sdk._sync.assistants import SyncAssistantsClient
+from langgraph_sdk._sync.client import SyncLangGraphClient, get_sync_client
+from langgraph_sdk._sync.cron import SyncCronClient
+from langgraph_sdk._sync.http import SyncHttpClient
+from langgraph_sdk._sync.runs import SyncRunsClient
+from langgraph_sdk._sync.store import SyncStoreClient
+from langgraph_sdk._sync.threads import SyncThreadsClient
+
+__all__ = [
+ "SyncAssistantsClient",
+ "SyncCronClient",
+ "SyncHttpClient",
+ "SyncLangGraphClient",
+ "SyncRunsClient",
+ "SyncStoreClient",
+ "SyncThreadsClient",
+ "get_sync_client",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c3b94ef60279f13ea20f69d1dec4e83203caef1a
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/assistants.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/assistants.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d2de81f4f9f1777adca8de1e2adf6a458c50215f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/assistants.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/client.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/client.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6e134d62f8f73b61535f2bd9bd142ef5287097d8
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/client.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/cron.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/cron.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0c126d32320fb6f06bd73eed38d1ecdec6630474
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/cron.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/http.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/http.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e0c371721fbd57c71e441a49c3f03f26d82b8115
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/http.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/runs.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/runs.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7ae72fe1dd4685613f3ce25d35a445daf3235746
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/runs.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/store.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/store.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..25f9cbdbbac7d6dbaa47f1ead28178e4c477fefc
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/store.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/threads.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/threads.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..67666373272ece73a1d200cfa79f8374e831ae44
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/__pycache__/threads.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/assistants.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/assistants.py
new file mode 100644
index 0000000000000000000000000000000000000000..af3a63965e83a3377b3e6417973ee6c76091aee0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/assistants.py
@@ -0,0 +1,738 @@
+"""Synchronous client for managing assistants in LangGraph."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, Literal, cast, overload
+
+import httpx
+
+from langgraph_sdk._shared.utilities import _quote_path_param
+from langgraph_sdk._sync.http import SyncHttpClient
+from langgraph_sdk.schema import (
+ Assistant,
+ AssistantSelectField,
+ AssistantSortBy,
+ AssistantsSearchResponse,
+ AssistantVersion,
+ Config,
+ Context,
+ GraphSchema,
+ Json,
+ OnConflictBehavior,
+ QueryParamTypes,
+ SortOrder,
+ Subgraphs,
+)
+
+
+class SyncAssistantsClient:
+ """Client for managing assistants in LangGraph synchronously.
+
+ This class provides methods to interact with assistants, which are versioned configurations of your graph.
+
+ ???+ example "Example"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ assistant = client.assistants.get("assistant_id_123")
+ ```
+ """
+
+ def __init__(self, http: SyncHttpClient) -> None:
+ self.http = http
+
+ def get(
+ self,
+ assistant_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Assistant:
+ """Get an assistant by ID.
+
+ Args:
+ assistant_id: The ID of the assistant to get OR the name of the graph (to use the default assistant).
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `Assistant` Object.
+
+ ???+ example "Example Usage"
+
+ ```python
+ assistant = client.assistants.get(
+ assistant_id="my_assistant_id"
+ )
+ print(assistant)
+ ```
+
+ ```shell
+ ----------------------------------------------------
+
+ {
+ 'assistant_id': 'my_assistant_id',
+ 'graph_id': 'agent',
+ 'created_at': '2024-06-25T17:10:33.109781+00:00',
+ 'updated_at': '2024-06-25T17:10:33.109781+00:00',
+ 'config': {},
+ 'context': {},
+ 'metadata': {'created_by': 'system'}
+ }
+ ```
+
+ """
+ return self.http.get(
+ f"/assistants/{_quote_path_param(assistant_id)}",
+ headers=headers,
+ params=params,
+ )
+
+ def get_graph(
+ self,
+ assistant_id: str,
+ *,
+ xray: int | bool = False,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> dict[str, list[dict[str, Any]]]:
+ """Get the graph of an assistant by ID.
+
+ Args:
+ assistant_id: The ID of the assistant to get the graph of.
+ xray: Include graph representation of subgraphs. If an integer value is provided, only subgraphs with a depth less than or equal to the value will be included.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The graph information for the assistant in JSON format.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ graph_info = client.assistants.get_graph(
+ assistant_id="my_assistant_id"
+ )
+ print(graph_info)
+
+ --------------------------------------------------------------------------------------------------------------------------
+
+ {
+ 'nodes':
+ [
+ {'id': '__start__', 'type': 'schema', 'data': '__start__'},
+ {'id': '__end__', 'type': 'schema', 'data': '__end__'},
+ {'id': 'agent','type': 'runnable','data': {'id': ['langgraph', 'utils', 'RunnableCallable'],'name': 'agent'}},
+ ],
+ 'edges':
+ [
+ {'source': '__start__', 'target': 'agent'},
+ {'source': 'agent','target': '__end__'}
+ ]
+ }
+ ```
+
+ """
+ query_params = {"xray": xray}
+ if params:
+ query_params.update(params)
+ return self.http.get(
+ f"/assistants/{_quote_path_param(assistant_id)}/graph",
+ params=query_params,
+ headers=headers,
+ )
+
+ def get_schemas(
+ self,
+ assistant_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> GraphSchema:
+ """Get the schemas of an assistant by ID.
+
+ Args:
+ assistant_id: The ID of the assistant to get the schema of.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ GraphSchema: The graph schema for the assistant.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ schema = client.assistants.get_schemas(
+ assistant_id="my_assistant_id"
+ )
+ print(schema)
+ ```
+ ```shell
+ ----------------------------------------------------------------------------------------------------------------------------
+
+ {
+ 'graph_id': 'agent',
+ 'state_schema':
+ {
+ 'title': 'LangGraphInput',
+ '$ref': '#/definitions/AgentState',
+ 'definitions':
+ {
+ 'BaseMessage':
+ {
+ 'title': 'BaseMessage',
+ 'description': 'Base abstract Message class. Messages are the inputs and outputs of ChatModels.',
+ 'type': 'object',
+ 'properties':
+ {
+ 'content':
+ {
+ 'title': 'Content',
+ 'anyOf': [
+ {'type': 'string'},
+ {'type': 'array','items': {'anyOf': [{'type': 'string'}, {'type': 'object'}]}}
+ ]
+ },
+ 'additional_kwargs':
+ {
+ 'title': 'Additional Kwargs',
+ 'type': 'object'
+ },
+ 'response_metadata':
+ {
+ 'title': 'Response Metadata',
+ 'type': 'object'
+ },
+ 'type':
+ {
+ 'title': 'Type',
+ 'type': 'string'
+ },
+ 'name':
+ {
+ 'title': 'Name',
+ 'type': 'string'
+ },
+ 'id':
+ {
+ 'title': 'Id',
+ 'type': 'string'
+ }
+ },
+ 'required': ['content', 'type']
+ },
+ 'AgentState':
+ {
+ 'title': 'AgentState',
+ 'type': 'object',
+ 'properties':
+ {
+ 'messages':
+ {
+ 'title': 'Messages',
+ 'type': 'array',
+ 'items': {'$ref': '#/definitions/BaseMessage'}
+ }
+ },
+ 'required': ['messages']
+ }
+ }
+ },
+ 'config_schema':
+ {
+ 'title': 'Configurable',
+ 'type': 'object',
+ 'properties':
+ {
+ 'model_name':
+ {
+ 'title': 'Model Name',
+ 'enum': ['anthropic', 'openai'],
+ 'type': 'string'
+ }
+ }
+ },
+ 'context_schema':
+ {
+ 'title': 'Context',
+ 'type': 'object',
+ 'properties':
+ {
+ 'model_name':
+ {
+ 'title': 'Model Name',
+ 'enum': ['anthropic', 'openai'],
+ 'type': 'string'
+ }
+ }
+ }
+ }
+ ```
+
+ """
+ return self.http.get(
+ f"/assistants/{_quote_path_param(assistant_id)}/schemas",
+ headers=headers,
+ params=params,
+ )
+
+ def get_subgraphs(
+ self,
+ assistant_id: str,
+ namespace: str | None = None,
+ recurse: bool = False,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Subgraphs:
+ """Get the schemas of an assistant by ID.
+
+ Args:
+ assistant_id: The ID of the assistant to get the schema of.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ Subgraphs: The graph schema for the assistant.
+
+ """
+ get_params = {"recurse": recurse}
+ if params:
+ get_params = {**get_params, **dict(params)}
+ if namespace is not None:
+ return self.http.get(
+ f"/assistants/{_quote_path_param(assistant_id)}/subgraphs/{_quote_path_param(namespace)}",
+ params=get_params,
+ headers=headers,
+ )
+ else:
+ return self.http.get(
+ f"/assistants/{_quote_path_param(assistant_id)}/subgraphs",
+ params=get_params,
+ headers=headers,
+ )
+
+ def create(
+ self,
+ graph_id: str | None,
+ config: Config | None = None,
+ *,
+ context: Context | None = None,
+ metadata: Json = None,
+ assistant_id: str | None = None,
+ if_exists: OnConflictBehavior | None = None,
+ name: str | None = None,
+ headers: Mapping[str, str] | None = None,
+ description: str | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Assistant:
+ """Create a new assistant.
+
+ Useful when graph is configurable and you want to create different assistants based on different configurations.
+
+ Args:
+ graph_id: The ID of the graph the assistant should use. The graph ID is normally set in your langgraph.json configuration.
+ config: Configuration to use for the graph.
+ context: Static context to add to the assistant.
+ !!! version-added "Added in version 0.6.0"
+ metadata: Metadata to add to assistant.
+ assistant_id: Assistant ID to use, will default to a random UUID if not provided.
+ if_exists: How to handle duplicate creation. Defaults to 'raise' under the hood.
+ Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing assistant).
+ name: The name of the assistant. Defaults to 'Untitled' under the hood.
+ headers: Optional custom headers to include with the request.
+ description: Optional description of the assistant.
+ The description field is available for langgraph-api server version>=0.0.45
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The created assistant.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ assistant = client.assistants.create(
+ graph_id="agent",
+ context={"model_name": "openai"},
+ metadata={"number":1},
+ assistant_id="my-assistant-id",
+ if_exists="do_nothing",
+ name="my_name"
+ )
+ ```
+ """
+ payload: dict[str, Any] = {
+ "graph_id": graph_id,
+ }
+ if config:
+ payload["config"] = config
+ if context:
+ payload["context"] = context
+ if metadata:
+ payload["metadata"] = metadata
+ if assistant_id:
+ payload["assistant_id"] = assistant_id
+ if if_exists:
+ payload["if_exists"] = if_exists
+ if name:
+ payload["name"] = name
+ if description:
+ payload["description"] = description
+ return self.http.post(
+ "/assistants", json=payload, headers=headers, params=params
+ )
+
+ def update(
+ self,
+ assistant_id: str,
+ *,
+ graph_id: str | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ metadata: Json = None,
+ name: str | None = None,
+ headers: Mapping[str, str] | None = None,
+ description: str | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Assistant:
+ """Update an assistant.
+
+ Use this to point to a different graph, update the configuration, or change the metadata of an assistant.
+
+ Args:
+ assistant_id: Assistant to update.
+ graph_id: The ID of the graph the assistant should use.
+ The graph ID is normally set in your langgraph.json configuration. If `None`, assistant will keep pointing to same graph.
+ config: Configuration to use for the graph.
+ context: Static context to add to the assistant.
+ !!! version-added "Added in version 0.6.0"
+ metadata: Metadata to merge with existing assistant metadata.
+ name: The new name for the assistant.
+ headers: Optional custom headers to include with the request.
+ description: Optional description of the assistant.
+ The description field is available for langgraph-api server version>=0.0.45
+
+ Returns:
+ The updated assistant.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ assistant = client.assistants.update(
+ assistant_id='e280dad7-8618-443f-87f1-8e41841c180f',
+ graph_id="other-graph",
+ context={"model_name": "anthropic"},
+ metadata={"number":2}
+ )
+ ```
+ """
+ payload: dict[str, Any] = {}
+ if graph_id:
+ payload["graph_id"] = graph_id
+ if config is not None:
+ payload["config"] = config
+ if context is not None:
+ payload["context"] = context
+ if metadata:
+ payload["metadata"] = metadata
+ if name:
+ payload["name"] = name
+ if description:
+ payload["description"] = description
+ return self.http.patch(
+ f"/assistants/{_quote_path_param(assistant_id)}",
+ json=payload,
+ headers=headers,
+ params=params,
+ )
+
+ def delete(
+ self,
+ assistant_id: str,
+ *,
+ delete_threads: bool = False,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Delete an assistant.
+
+ Args:
+ assistant_id: The assistant ID to delete.
+ delete_threads: If true, delete all threads with `metadata.assistant_id`
+ matching this assistant, along with runs and checkpoints belonging to
+ those threads.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ client.assistants.delete(
+ assistant_id="my_assistant_id"
+ )
+ ```
+
+ """
+ query_params: dict[str, Any] = {}
+ if delete_threads:
+ query_params["delete_threads"] = True
+ if params:
+ query_params.update(params)
+ self.http.delete(
+ f"/assistants/{_quote_path_param(assistant_id)}",
+ headers=headers,
+ params=query_params or None,
+ )
+
+ @overload
+ def search(
+ self,
+ *,
+ metadata: Json = None,
+ graph_id: str | None = None,
+ name: str | None = None,
+ limit: int = 10,
+ offset: int = 0,
+ sort_by: AssistantSortBy | None = None,
+ sort_order: SortOrder | None = None,
+ select: list[AssistantSelectField] | None = None,
+ response_format: Literal["object"],
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> AssistantsSearchResponse: ...
+
+ @overload
+ def search(
+ self,
+ *,
+ metadata: Json = None,
+ graph_id: str | None = None,
+ name: str | None = None,
+ limit: int = 10,
+ offset: int = 0,
+ sort_by: AssistantSortBy | None = None,
+ sort_order: SortOrder | None = None,
+ select: list[AssistantSelectField] | None = None,
+ response_format: Literal["array"] = "array",
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> list[Assistant]: ...
+
+ def search(
+ self,
+ *,
+ metadata: Json = None,
+ graph_id: str | None = None,
+ name: str | None = None,
+ limit: int = 10,
+ offset: int = 0,
+ sort_by: AssistantSortBy | None = None,
+ sort_order: SortOrder | None = None,
+ select: list[AssistantSelectField] | None = None,
+ response_format: Literal["array", "object"] = "array",
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> AssistantsSearchResponse | list[Assistant]:
+ """Search for assistants.
+
+ Args:
+ metadata: Metadata to filter by. Exact match filter for each KV pair.
+ graph_id: The ID of the graph to filter by.
+ The graph ID is normally set in your langgraph.json configuration.
+ name: The name of the assistant to filter by.
+ The filtering logic will match assistants where 'name' is a substring (case insensitive) of the assistant name.
+ limit: The maximum number of results to return.
+ offset: The number of results to skip.
+ sort_by: The field to sort by.
+ sort_order: The order to sort by.
+ select: Specific assistant fields to include in the response.
+ response_format: Controls the response shape. Use `"array"` (default)
+ to return a bare list of assistants, or `"object"` to return
+ a mapping containing assistants plus pagination metadata.
+ Defaults to "array", though this default will be changed to "object" in a future release.
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ A list of assistants (when `response_format="array"`) or a mapping
+ with the assistants and the next pagination cursor (when
+ `response_format="object"`).
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ response = client.assistants.search(
+ metadata = {"name":"my_name"},
+ graph_id="my_graph_id",
+ limit=5,
+ offset=5,
+ response_format="object",
+ )
+ assistants = response["assistants"]
+ next_cursor = response["next"]
+ ```
+ """
+ if response_format not in ("array", "object"):
+ raise ValueError("response_format must be 'array' or 'object'")
+ payload: dict[str, Any] = {
+ "limit": limit,
+ "offset": offset,
+ }
+ if metadata:
+ payload["metadata"] = metadata
+ if graph_id:
+ payload["graph_id"] = graph_id
+ if name:
+ payload["name"] = name
+ if sort_by:
+ payload["sort_by"] = sort_by
+ if sort_order:
+ payload["sort_order"] = sort_order
+ if select:
+ payload["select"] = select
+ next_cursor: str | None = None
+
+ def capture_pagination(response: httpx.Response) -> None:
+ nonlocal next_cursor
+ next_cursor = response.headers.get("X-Pagination-Next")
+
+ assistants = cast(
+ list[Assistant],
+ self.http.post(
+ "/assistants/search",
+ json=payload,
+ headers=headers,
+ params=params,
+ on_response=capture_pagination if response_format == "object" else None,
+ ),
+ )
+ if response_format == "object":
+ return {"assistants": assistants, "next": next_cursor}
+ return assistants
+
+ def count(
+ self,
+ *,
+ metadata: Json = None,
+ graph_id: str | None = None,
+ name: str | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> int:
+ """Count assistants matching filters.
+
+ Args:
+ metadata: Metadata to filter by. Exact match for each key/value.
+ graph_id: Optional graph id to filter by.
+ name: Optional name to filter by.
+ The filtering logic will match assistants where 'name' is a substring (case insensitive) of the assistant name.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ int: Number of assistants matching the criteria.
+ """
+ payload: dict[str, Any] = {}
+ if metadata:
+ payload["metadata"] = metadata
+ if graph_id:
+ payload["graph_id"] = graph_id
+ if name:
+ payload["name"] = name
+ return self.http.post(
+ "/assistants/count", json=payload, headers=headers, params=params
+ )
+
+ def get_versions(
+ self,
+ assistant_id: str,
+ metadata: Json = None,
+ limit: int = 10,
+ offset: int = 0,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> list[AssistantVersion]:
+ """List all versions of an assistant.
+
+ Args:
+ assistant_id: The assistant ID to get versions for.
+ metadata: Metadata to filter versions by. Exact match filter for each KV pair.
+ limit: The maximum number of versions to return.
+ offset: The number of versions to skip.
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ A list of assistants.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ assistant_versions = client.assistants.get_versions(
+ assistant_id="my_assistant_id"
+ )
+ ```
+
+ """
+
+ payload: dict[str, Any] = {
+ "limit": limit,
+ "offset": offset,
+ }
+ if metadata:
+ payload["metadata"] = metadata
+ return self.http.post(
+ f"/assistants/{_quote_path_param(assistant_id)}/versions",
+ json=payload,
+ headers=headers,
+ params=params,
+ )
+
+ def set_latest(
+ self,
+ assistant_id: str,
+ version: int,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Assistant:
+ """Change the version of an assistant.
+
+ Args:
+ assistant_id: The assistant ID to delete.
+ version: The version to change to.
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ `Assistant` Object.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ new_version_assistant = client.assistants.set_latest(
+ assistant_id="my_assistant_id",
+ version=3
+ )
+ ```
+
+ """
+
+ payload: dict[str, Any] = {"version": version}
+
+ return self.http.post(
+ f"/assistants/{_quote_path_param(assistant_id)}/latest",
+ json=payload,
+ headers=headers,
+ params=params,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/client.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/client.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d943b554647e6869ca46d2f3b64e41d81177c95
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/client.py
@@ -0,0 +1,127 @@
+"""Sync LangGraph client."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from types import TracebackType
+
+import httpx
+
+from langgraph_sdk._shared.types import TimeoutTypes
+from langgraph_sdk._shared.utilities import NOT_PROVIDED, _get_headers
+from langgraph_sdk._sync.assistants import SyncAssistantsClient
+from langgraph_sdk._sync.cron import SyncCronClient
+from langgraph_sdk._sync.http import SyncHttpClient
+from langgraph_sdk._sync.runs import SyncRunsClient
+from langgraph_sdk._sync.store import SyncStoreClient
+from langgraph_sdk._sync.threads import SyncThreadsClient
+
+
+def get_sync_client(
+ *,
+ url: str | None = None,
+ api_key: str | None = NOT_PROVIDED,
+ headers: Mapping[str, str] | None = None,
+ timeout: TimeoutTypes | None = None,
+) -> SyncLangGraphClient:
+ """Get a synchronous LangGraphClient instance.
+
+ Args:
+ url: The URL of the LangGraph API.
+ api_key: API key for authentication. Can be:
+ - A string: use this exact API key
+ - `None`: explicitly skip loading from environment variables
+ - Not provided (default): auto-load from environment in this order:
+ 1. `LANGGRAPH_API_KEY`
+ 2. `LANGSMITH_API_KEY`
+ 3. `LANGCHAIN_API_KEY`
+ headers: Optional custom headers
+ timeout: Optional timeout configuration for the HTTP client.
+ Accepts an httpx.Timeout instance, a float (seconds), or a tuple of timeouts.
+ Tuple format is (connect, read, write, pool)
+ If not provided, defaults to connect=5s, read=300s, write=300s, and pool=5s.
+ Returns:
+ SyncLangGraphClient: The top-level synchronous client for accessing AssistantsClient,
+ ThreadsClient, RunsClient, and CronClient.
+
+ ???+ example "Example"
+
+ ```python
+ from langgraph_sdk import get_sync_client
+
+ # get top-level synchronous LangGraphClient
+ client = get_sync_client(url="http://localhost:8123")
+
+ # example usage: client..()
+ assistant = client.assistants.get(assistant_id="some_uuid")
+ ```
+
+ ???+ example "Skip auto-loading API key from environment:"
+
+ ```python
+ from langgraph_sdk import get_sync_client
+
+ # Don't load API key from environment variables
+ client = get_sync_client(
+ url="http://localhost:8123",
+ api_key=None
+ )
+ ```
+ """
+
+ if url is None:
+ url = "http://localhost:8123"
+
+ transport = httpx.HTTPTransport(retries=5)
+ client = httpx.Client(
+ base_url=url,
+ transport=transport,
+ timeout=(
+ httpx.Timeout(timeout) # ty: ignore[invalid-argument-type]
+ if timeout is not None
+ else httpx.Timeout(connect=5, read=300, write=300, pool=5)
+ ),
+ headers=_get_headers(api_key, headers),
+ )
+ return SyncLangGraphClient(client)
+
+
+class SyncLangGraphClient:
+ """Synchronous client for interacting with the LangGraph API.
+
+ This class provides synchronous access to LangGraph API endpoints for managing
+ assistants, threads, runs, cron jobs, and data storage.
+
+ ???+ example "Example"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ assistant = client.assistants.get("asst_123")
+ ```
+ """
+
+ def __init__(self, client: httpx.Client) -> None:
+ self.http = SyncHttpClient(client)
+ self.assistants = SyncAssistantsClient(self.http)
+ self.threads = SyncThreadsClient(self.http)
+ self.runs = SyncRunsClient(self.http)
+ self.crons = SyncCronClient(self.http)
+ self.store = SyncStoreClient(self.http)
+
+ def __enter__(self) -> SyncLangGraphClient:
+ """Enter the sync context manager."""
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: TracebackType | None,
+ ) -> None:
+ """Exit the sync context manager."""
+ self.close()
+
+ def close(self) -> None:
+ """Close the underlying HTTP client."""
+ if hasattr(self, "http"):
+ self.http.client.close()
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/cron.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/cron.py
new file mode 100644
index 0000000000000000000000000000000000000000..24acae5bd39e865fb2655b87016ef27c5ff738a3
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/cron.py
@@ -0,0 +1,521 @@
+"""Synchronous cron client for LangGraph SDK."""
+
+from __future__ import annotations
+
+import warnings
+from collections.abc import Mapping, Sequence
+from datetime import datetime, tzinfo
+from typing import Any
+
+from langgraph_sdk._shared.utilities import _quote_path_param, _resolve_timezone
+from langgraph_sdk._sync.http import SyncHttpClient
+from langgraph_sdk.schema import (
+ All,
+ Config,
+ Context,
+ Cron,
+ CronSelectField,
+ CronSortBy,
+ Durability,
+ Input,
+ Json,
+ OnCompletionBehavior,
+ QueryParamTypes,
+ Run,
+ SortOrder,
+ StreamMode,
+)
+
+
+class SyncCronClient:
+ """Synchronous client for managing cron jobs in LangGraph.
+
+ This class provides methods to create and manage scheduled tasks (cron jobs) for automated graph executions.
+
+ ???+ example "Example"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ cron_job = client.crons.create_for_thread(thread_id="thread_123", assistant_id="asst_456", schedule="0 * * * *")
+ ```
+
+ !!! note "Feature Availability"
+
+ The crons client functionality is not supported on all licenses.
+ Please check the relevant license documentation for the most up-to-date
+ details on feature availability.
+ """
+
+ def __init__(self, http_client: SyncHttpClient) -> None:
+ self.http = http_client
+
+ def create_for_thread(
+ self,
+ thread_id: str,
+ assistant_id: str,
+ *,
+ schedule: str,
+ input: Input | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint_during: bool | None = None, # deprecated
+ interrupt_before: All | list[str] | None = None,
+ interrupt_after: All | list[str] | None = None,
+ webhook: str | None = None,
+ multitask_strategy: str | None = None,
+ end_time: datetime | None = None,
+ enabled: bool | None = None,
+ timezone: str | tzinfo | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ stream_subgraphs: bool | None = None,
+ stream_resumable: bool | None = None,
+ durability: Durability | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Run:
+ """Create a cron job for a thread.
+
+ Args:
+ thread_id: the thread ID to run the cron job on.
+ assistant_id: The assistant ID or graph name to use for the cron job.
+ If using graph name, will default to first assistant created from that graph.
+ schedule: The cron schedule to execute this job on.
+ Schedules are interpreted in UTC unless a timezone is specified.
+ input: The input to the graph.
+ metadata: Metadata to assign to the cron job runs.
+ config: The configuration for the assistant.
+ context: Static context to add to the assistant.
+ !!! version-added "Added in version 0.6.0"
+ checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
+ interrupt_before: Nodes to interrupt immediately before they get executed.
+ interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
+ webhook: Webhook to call after LangGraph API call is done.
+ multitask_strategy: Multitask strategy to use.
+ Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
+ end_time: The time to stop running the cron job. If not provided, the cron job will run indefinitely.
+ enabled: Whether the cron job is enabled. By default, it is considered enabled.
+ timezone: IANA timezone for the cron schedule. Accepts a string (e.g. 'America/New_York') or a ``datetime.tzinfo`` instance (e.g. ``ZoneInfo("America/New_York")``).
+ stream_mode: The stream mode(s) to use.
+ stream_subgraphs: Whether to stream output from subgraphs.
+ stream_resumable: Whether to persist the stream chunks in order to resume the stream later.
+ durability: Durability level for the run. Must be one of 'sync', 'async', or 'exit'.
+ "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
+ "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
+ "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ The cron `Run`.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ cron_run = client.crons.create_for_thread(
+ thread_id="my-thread-id",
+ assistant_id="agent",
+ schedule="27 15 * * *",
+ input={"messages": [{"role": "user", "content": "hello!"}]},
+ metadata={"name":"my_run"},
+ context={"model_name": "openai"},
+ interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
+ interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
+ webhook="https://my.fake.webhook.com",
+ multitask_strategy="interrupt",
+ enabled=True
+ )
+ ```
+ """
+ if checkpoint_during is not None:
+ warnings.warn(
+ "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+ payload = {
+ "schedule": schedule,
+ "input": input,
+ "config": config,
+ "metadata": metadata,
+ "context": context,
+ "assistant_id": assistant_id,
+ "interrupt_before": interrupt_before,
+ "interrupt_after": interrupt_after,
+ "checkpoint_during": checkpoint_during,
+ "webhook": webhook,
+ "multitask_strategy": multitask_strategy,
+ "end_time": end_time.isoformat() if end_time else None,
+ "enabled": enabled,
+ "timezone": _resolve_timezone(timezone),
+ "stream_mode": stream_mode,
+ "stream_subgraphs": stream_subgraphs,
+ "stream_resumable": stream_resumable,
+ "durability": durability,
+ }
+ payload = {k: v for k, v in payload.items() if v is not None}
+ return self.http.post(
+ f"/threads/{_quote_path_param(thread_id)}/runs/crons",
+ json=payload,
+ headers=headers,
+ params=params,
+ )
+
+ def create(
+ self,
+ assistant_id: str,
+ *,
+ schedule: str,
+ input: Input | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint_during: bool | None = None, # deprecated
+ interrupt_before: All | list[str] | None = None,
+ interrupt_after: All | list[str] | None = None,
+ webhook: str | None = None,
+ on_run_completed: OnCompletionBehavior | None = None,
+ multitask_strategy: str | None = None,
+ end_time: datetime | None = None,
+ enabled: bool | None = None,
+ timezone: str | tzinfo | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ stream_subgraphs: bool | None = None,
+ stream_resumable: bool | None = None,
+ durability: Durability | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Run:
+ """Create a cron run.
+
+ Args:
+ assistant_id: The assistant ID or graph name to use for the cron job.
+ If using graph name, will default to first assistant created from that graph.
+ schedule: The cron schedule to execute this job on.
+ Schedules are interpreted in UTC unless a timezone is specified.
+ input: The input to the graph.
+ metadata: Metadata to assign to the cron job runs.
+ config: The configuration for the assistant.
+ context: Static context to add to the assistant.
+ !!! version-added "Added in version 0.6.0"
+ checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
+ interrupt_before: Nodes to interrupt immediately before they get executed.
+ interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
+ webhook: Webhook to call after LangGraph API call is done.
+ on_run_completed: What to do with the thread after the run completes.
+ Must be one of 'delete' (default) or 'keep'. 'delete' removes the thread
+ after execution. 'keep' creates a new thread for each execution but does not
+ clean them up. Clients are responsible for cleaning up kept threads.
+ multitask_strategy: Multitask strategy to use.
+ Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
+ end_time: The time to stop running the cron job. If not provided, the cron job will run indefinitely.
+ enabled: Whether the cron job is enabled. By default, it is considered enabled.
+ timezone: IANA timezone for the cron schedule. Accepts a string (e.g. 'America/New_York') or a ``datetime.tzinfo`` instance (e.g. ``ZoneInfo("America/New_York")``).
+ stream_mode: The stream mode(s) to use.
+ stream_subgraphs: Whether to stream output from subgraphs.
+ stream_resumable: Whether to persist the stream chunks in order to resume the stream later.
+ durability: Durability level for the run. Must be one of 'sync', 'async', or 'exit'.
+ "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
+ "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
+ "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ The cron `Run`.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ cron_run = client.crons.create(
+ assistant_id="agent",
+ schedule="27 15 * * *",
+ input={"messages": [{"role": "user", "content": "hello!"}]},
+ metadata={"name":"my_run"},
+ context={"model_name": "openai"},
+ checkpoint_during=True,
+ interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
+ interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
+ webhook="https://my.fake.webhook.com",
+ multitask_strategy="interrupt",
+ enabled=True
+ )
+ ```
+
+ """
+ if checkpoint_during is not None:
+ warnings.warn(
+ "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+ payload = {
+ "schedule": schedule,
+ "input": input,
+ "config": config,
+ "metadata": metadata,
+ "context": context,
+ "assistant_id": assistant_id,
+ "interrupt_before": interrupt_before,
+ "interrupt_after": interrupt_after,
+ "webhook": webhook,
+ "checkpoint_during": checkpoint_during,
+ "on_run_completed": on_run_completed,
+ "multitask_strategy": multitask_strategy,
+ "end_time": end_time.isoformat() if end_time else None,
+ "enabled": enabled,
+ "timezone": _resolve_timezone(timezone),
+ "stream_mode": stream_mode,
+ "stream_subgraphs": stream_subgraphs,
+ "stream_resumable": stream_resumable,
+ "durability": durability,
+ }
+ payload = {k: v for k, v in payload.items() if v is not None}
+ return self.http.post(
+ "/runs/crons", json=payload, headers=headers, params=params
+ )
+
+ def delete(
+ self,
+ cron_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Delete a cron.
+
+ Args:
+ cron_id: The cron ID to delete.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ client.crons.delete(
+ cron_id="cron_to_delete"
+ )
+ ```
+
+ """
+ self.http.delete(
+ f"/runs/crons/{_quote_path_param(cron_id)}", headers=headers, params=params
+ )
+
+ def update(
+ self,
+ cron_id: str,
+ *,
+ schedule: str | None = None,
+ end_time: datetime | None = None,
+ input: Input | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ webhook: str | None = None,
+ interrupt_before: All | list[str] | None = None,
+ interrupt_after: All | list[str] | None = None,
+ on_run_completed: OnCompletionBehavior | None = None,
+ enabled: bool | None = None,
+ timezone: str | tzinfo | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ stream_subgraphs: bool | None = None,
+ stream_resumable: bool | None = None,
+ durability: Durability | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Cron:
+ """Update a cron job by ID.
+
+ Args:
+ cron_id: The cron ID to update.
+ schedule: The cron schedule to execute this job on.
+ Schedules are interpreted in UTC unless a timezone is specified.
+ end_time: The end date to stop running the cron.
+ input: The input to the graph.
+ metadata: Metadata to assign to the cron job runs.
+ config: The configuration for the assistant.
+ context: Static context added to the assistant.
+ webhook: Webhook to call after LangGraph API call is done.
+ interrupt_before: Nodes to interrupt immediately before they get executed.
+ interrupt_after: Nodes to interrupt immediately after they get executed.
+ on_run_completed: What to do with the thread after the run completes.
+ Must be one of 'delete' or 'keep'. 'delete' removes the thread
+ after execution. 'keep' creates a new thread for each execution but does not
+ clean them up.
+ enabled: Enable or disable the cron job.
+ timezone: IANA timezone for the cron schedule. Accepts a string (e.g. 'America/New_York') or a ``datetime.tzinfo`` instance (e.g. ``ZoneInfo("America/New_York")``).
+ stream_mode: The stream mode(s) to use.
+ stream_subgraphs: Whether to stream output from subgraphs.
+ stream_resumable: Whether to persist the stream chunks in order to resume the stream later.
+ durability: Durability level for the run. Must be one of 'sync', 'async', or 'exit'.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The updated cron job.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ updated_cron = client.crons.update(
+ cron_id="1ef3cefa-4c09-6926-96d0-3dc97fd5e39b",
+ schedule="0 10 * * *",
+ enabled=False,
+ )
+ ```
+
+ """
+ payload = {
+ "schedule": schedule,
+ "end_time": end_time.isoformat() if end_time else None,
+ "input": input,
+ "metadata": metadata,
+ "config": config,
+ "context": context,
+ "webhook": webhook,
+ "interrupt_before": interrupt_before,
+ "interrupt_after": interrupt_after,
+ "on_run_completed": on_run_completed,
+ "enabled": enabled,
+ "timezone": _resolve_timezone(timezone),
+ "stream_mode": stream_mode,
+ "stream_subgraphs": stream_subgraphs,
+ "stream_resumable": stream_resumable,
+ "durability": durability,
+ }
+ payload = {k: v for k, v in payload.items() if v is not None}
+ return self.http.patch(
+ f"/runs/crons/{_quote_path_param(cron_id)}",
+ json=payload,
+ headers=headers,
+ params=params,
+ )
+
+ def search(
+ self,
+ *,
+ assistant_id: str | None = None,
+ thread_id: str | None = None,
+ enabled: bool | None = None,
+ metadata: Json = None,
+ limit: int = 10,
+ offset: int = 0,
+ sort_by: CronSortBy | None = None,
+ sort_order: SortOrder | None = None,
+ select: list[CronSelectField] | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> list[Cron]:
+ """Get a list of cron jobs.
+
+ Args:
+ assistant_id: The assistant ID or graph name to search for.
+ thread_id: the thread ID to search for.
+ enabled: Whether the cron job is enabled.
+ metadata: Metadata to filter by. Exact match filter for each KV pair.
+ !!! version-added "Added in Agent Server version 0.9.0"
+ limit: The maximum number of results to return.
+ offset: The number of results to skip.
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ The list of cron jobs returned by the search,
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ cron_jobs = client.crons.search(
+ assistant_id="my_assistant_id",
+ thread_id="my_thread_id",
+ enabled=True,
+ limit=5,
+ offset=5,
+ )
+ print(cron_jobs)
+ ```
+
+ ```shell
+ ----------------------------------------------------------
+
+ [
+ {
+ 'cron_id': '1ef3cefa-4c09-6926-96d0-3dc97fd5e39b',
+ 'assistant_id': 'my_assistant_id',
+ 'thread_id': 'my_thread_id',
+ 'user_id': None,
+ 'payload':
+ {
+ 'input': {'start_time': ''},
+ 'schedule': '4 * * * *',
+ 'assistant_id': 'my_assistant_id'
+ },
+ 'schedule': '4 * * * *',
+ 'next_run_date': '2024-07-25T17:04:00+00:00',
+ 'end_time': None,
+ 'created_at': '2024-07-08T06:02:23.073257+00:00',
+ 'updated_at': '2024-07-08T06:02:23.073257+00:00'
+ }
+ ]
+ ```
+ """
+ payload: dict[str, Any] = {
+ "assistant_id": assistant_id,
+ "thread_id": thread_id,
+ "enabled": enabled,
+ "limit": limit,
+ "offset": offset,
+ }
+ if metadata:
+ payload["metadata"] = metadata
+ if sort_by:
+ payload["sort_by"] = sort_by
+ if sort_order:
+ payload["sort_order"] = sort_order
+ if select:
+ payload["select"] = select
+ payload = {k: v for k, v in payload.items() if v is not None}
+ return self.http.post(
+ "/runs/crons/search", json=payload, headers=headers, params=params
+ )
+
+ def count(
+ self,
+ *,
+ assistant_id: str | None = None,
+ thread_id: str | None = None,
+ metadata: Json = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> int:
+ """Count cron jobs matching filters.
+
+ Args:
+ assistant_id: Assistant ID to filter by.
+ thread_id: Thread ID to filter by.
+ metadata: Metadata to filter by. Exact match filter for each KV pair.
+ !!! version-added "Added in Agent Server version 0.9.0"
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ int: Number of crons matching the criteria.
+ """
+ payload: dict[str, Any] = {}
+ if assistant_id:
+ payload["assistant_id"] = assistant_id
+ if thread_id:
+ payload["thread_id"] = thread_id
+ if metadata:
+ payload["metadata"] = metadata
+ return self.http.post(
+ "/runs/crons/count", json=payload, headers=headers, params=params
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/http.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/http.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba56543be0cc30b157f5afe4aaa3c5ab8288ea16
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/http.py
@@ -0,0 +1,303 @@
+"""Synchronous HTTP client for LangGraph API."""
+
+from __future__ import annotations
+
+import logging
+import sys
+import warnings
+from collections.abc import Callable, Iterator, Mapping
+from typing import Any, cast
+
+import httpx
+import orjson
+
+from langgraph_sdk._shared.utilities import (
+ _orjson_default,
+ _validate_reconnect_location,
+)
+from langgraph_sdk.errors import _raise_for_status_typed
+from langgraph_sdk.schema import QueryParamTypes, StreamPart
+from langgraph_sdk.sse import SSEDecoder, iter_lines_raw
+
+logger = logging.getLogger(__name__)
+
+
+class SyncHttpClient:
+ """Handle synchronous requests to the LangGraph API.
+
+ Provides error messaging and content handling enhancements above the
+ underlying httpx client, mirroring the interface of [HttpClient](#HttpClient)
+ but for sync usage.
+
+ Attributes:
+ client (httpx.Client): Underlying HTTPX sync client.
+ """
+
+ def __init__(self, client: httpx.Client) -> None:
+ self.client = client
+
+ def get(
+ self,
+ path: str,
+ *,
+ params: QueryParamTypes | None = None,
+ headers: Mapping[str, str] | None = None,
+ on_response: Callable[[httpx.Response], None] | None = None,
+ ) -> Any:
+ """Send a `GET` request."""
+ r = self.client.get(path, params=params, headers=headers)
+ if on_response:
+ on_response(r)
+ _raise_for_status_typed(r)
+ return _decode_json(r)
+
+ def post(
+ self,
+ path: str,
+ *,
+ json: dict[str, Any] | list | None,
+ params: QueryParamTypes | None = None,
+ headers: Mapping[str, str] | None = None,
+ on_response: Callable[[httpx.Response], None] | None = None,
+ ) -> Any:
+ """Send a `POST` request."""
+ if json is not None:
+ request_headers, content = _encode_json(json)
+ else:
+ request_headers, content = {}, b""
+ if headers:
+ request_headers.update(headers)
+ r = self.client.post(
+ path, headers=request_headers, content=content, params=params
+ )
+ if on_response:
+ on_response(r)
+ _raise_for_status_typed(r)
+ return _decode_json(r)
+
+ def put(
+ self,
+ path: str,
+ *,
+ json: dict,
+ params: QueryParamTypes | None = None,
+ headers: Mapping[str, str] | None = None,
+ on_response: Callable[[httpx.Response], None] | None = None,
+ ) -> Any:
+ """Send a `PUT` request."""
+ request_headers, content = _encode_json(json)
+ if headers:
+ request_headers.update(headers)
+
+ r = self.client.put(
+ path, headers=request_headers, content=content, params=params
+ )
+ if on_response:
+ on_response(r)
+ _raise_for_status_typed(r)
+ return _decode_json(r)
+
+ def patch(
+ self,
+ path: str,
+ *,
+ json: dict,
+ params: QueryParamTypes | None = None,
+ headers: Mapping[str, str] | None = None,
+ on_response: Callable[[httpx.Response], None] | None = None,
+ ) -> Any:
+ """Send a `PATCH` request."""
+ request_headers, content = _encode_json(json)
+ if headers:
+ request_headers.update(headers)
+ r = self.client.patch(
+ path, headers=request_headers, content=content, params=params
+ )
+ if on_response:
+ on_response(r)
+ _raise_for_status_typed(r)
+ return _decode_json(r)
+
+ def delete(
+ self,
+ path: str,
+ *,
+ json: Any | None = None,
+ params: QueryParamTypes | None = None,
+ headers: Mapping[str, str] | None = None,
+ on_response: Callable[[httpx.Response], None] | None = None,
+ ) -> None:
+ """Send a `DELETE` request."""
+ r = self.client.request(
+ "DELETE", path, json=json, params=params, headers=headers
+ )
+ if on_response:
+ on_response(r)
+ _raise_for_status_typed(r)
+
+ def request_reconnect(
+ self,
+ path: str,
+ method: str,
+ *,
+ json: dict[str, Any] | None = None,
+ params: QueryParamTypes | None = None,
+ headers: Mapping[str, str] | None = None,
+ on_response: Callable[[httpx.Response], None] | None = None,
+ reconnect_limit: int = 5,
+ ) -> Any:
+ """Send a request that automatically reconnects to Location header."""
+ request_headers, content = _encode_json(json)
+ if headers:
+ request_headers.update(headers)
+ with self.client.stream(
+ method, path, headers=request_headers, content=content, params=params
+ ) as r:
+ if on_response:
+ on_response(r)
+ try:
+ r.raise_for_status()
+ except httpx.HTTPStatusError as e:
+ body = r.read().decode()
+ if sys.version_info >= (3, 11):
+ e.add_note(body)
+ else:
+ logger.error(f"Error from langgraph-api: {body}", exc_info=e)
+ raise e
+ loc = r.headers.get("location")
+ if reconnect_limit <= 0 or not loc:
+ return _decode_json(r)
+ _validate_reconnect_location(self.client.base_url, loc)
+ try:
+ return _decode_json(r)
+ except httpx.HTTPError:
+ warnings.warn(
+ f"Request failed, attempting reconnect to Location: {loc}",
+ stacklevel=2,
+ )
+ r.close()
+ return self.request_reconnect(
+ loc,
+ "GET",
+ headers=request_headers,
+ # don't pass on_response so it's only called once
+ reconnect_limit=reconnect_limit - 1,
+ )
+
+ def stream(
+ self,
+ path: str,
+ method: str,
+ *,
+ json: dict[str, Any] | None = None,
+ params: QueryParamTypes | None = None,
+ headers: Mapping[str, str] | None = None,
+ on_response: Callable[[httpx.Response], None] | None = None,
+ ) -> Iterator[StreamPart]:
+ """Stream the results of a request using SSE."""
+ if json is not None:
+ request_headers, content = _encode_json(json)
+ else:
+ request_headers, content = {}, None
+ request_headers["Accept"] = "text/event-stream"
+ request_headers["Cache-Control"] = "no-store"
+ if headers:
+ request_headers.update(headers)
+
+ reconnect_headers = {
+ key: value
+ for key, value in request_headers.items()
+ if key.lower() not in {"content-length", "content-type"}
+ }
+
+ last_event_id: str | None = None
+ reconnect_path: str | None = None
+ reconnect_attempts = 0
+ max_reconnect_attempts = 5
+
+ while True:
+ current_headers = dict(
+ request_headers if reconnect_path is None else reconnect_headers
+ )
+ if last_event_id is not None:
+ current_headers["Last-Event-ID"] = last_event_id
+
+ current_method = method if reconnect_path is None else "GET"
+ current_content = content if reconnect_path is None else None
+ current_params = params if reconnect_path is None else None
+
+ retry = False
+ with self.client.stream(
+ current_method,
+ reconnect_path or path,
+ headers=current_headers,
+ content=current_content,
+ params=current_params,
+ ) as res:
+ if reconnect_path is None and on_response:
+ on_response(res)
+ # check status
+ _raise_for_status_typed(res)
+ # check content type
+ content_type = res.headers.get("content-type", "").partition(";")[0]
+ if "text/event-stream" not in content_type:
+ raise httpx.TransportError(
+ "Expected response header Content-Type to contain 'text/event-stream', "
+ f"got {content_type!r}"
+ )
+
+ reconnect_location = res.headers.get("location")
+ if reconnect_location:
+ _validate_reconnect_location(
+ self.client.base_url, reconnect_location
+ )
+ reconnect_path = reconnect_location
+
+ decoder = SSEDecoder()
+ try:
+ for line in iter_lines_raw(res):
+ sse = decoder.decode(cast(bytes, line).rstrip(b"\n"))
+ if sse is not None:
+ if decoder.last_event_id is not None:
+ last_event_id = decoder.last_event_id
+ if sse.event or sse.data is not None:
+ yield sse
+ except httpx.HTTPError:
+ # httpx.TransportError inherits from HTTPError, so transient
+ # disconnects during streaming land here.
+ if reconnect_path is None:
+ raise
+ retry = True
+ else:
+ if sse := decoder.decode(b""):
+ if decoder.last_event_id is not None:
+ last_event_id = decoder.last_event_id
+ if sse.event or sse.data is not None:
+ # See async stream implementation for rationale on
+ # skipping empty flush events.
+ yield sse
+ if retry:
+ reconnect_attempts += 1
+ if reconnect_attempts > max_reconnect_attempts:
+ raise httpx.TransportError(
+ "Exceeded maximum SSE reconnection attempts"
+ )
+ continue
+ break
+
+
+def _encode_json(json: Any) -> tuple[dict[str, str], bytes]:
+ body = orjson.dumps(
+ json,
+ _orjson_default,
+ orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_NON_STR_KEYS,
+ )
+ content_length = str(len(body))
+ content_type = "application/json"
+ headers = {"Content-Length": content_length, "Content-Type": content_type}
+ return headers, body
+
+
+def _decode_json(r: httpx.Response) -> Any:
+ body = r.read()
+ return orjson.loads(body) if body else None
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/runs.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/runs.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d2d1708609970ff3870c7713715daab14549657
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/runs.py
@@ -0,0 +1,1171 @@
+"""Synchronous client for managing runs in LangGraph."""
+
+from __future__ import annotations
+
+import builtins
+import warnings
+from collections.abc import Callable, Iterator, Mapping, Sequence
+from typing import Any, Literal, overload
+
+import httpx
+
+from langgraph_sdk._shared.utilities import (
+ _get_run_metadata_from_response,
+ _quote_path_param,
+ _sse_to_v2_dict,
+)
+from langgraph_sdk._sync.http import SyncHttpClient
+from langgraph_sdk.schema import (
+ All,
+ BulkCancelRunsStatus,
+ CancelAction,
+ Checkpoint,
+ Command,
+ Config,
+ Context,
+ DisconnectMode,
+ Durability,
+ IfNotExists,
+ Input,
+ LangSmithTracing,
+ MultitaskStrategy,
+ OnCompletionBehavior,
+ QueryParamTypes,
+ Run,
+ RunCreate,
+ RunCreateMetadata,
+ RunSelectField,
+ RunStatus,
+ StreamMode,
+ StreamPart,
+ StreamPartV2,
+ StreamVersion,
+)
+
+
+def _wrap_stream_v2_sync(
+ raw: Iterator[StreamPart],
+) -> Iterator[StreamPartV2]:
+ """Wrap a raw SSE stream, converting each event to a v2 dict."""
+ for part in raw:
+ v2 = _sse_to_v2_dict(part.event, part.data)
+ if v2 is not None:
+ yield v2 # ty: ignore[invalid-yield]
+
+
+class SyncRunsClient:
+ """Synchronous client for managing runs in LangGraph.
+
+ This class provides methods to create, retrieve, and manage runs, which represent
+ individual executions of graphs.
+
+ ???+ example "Example"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ run = client.runs.create(thread_id="thread_123", assistant_id="asst_456")
+ ```
+ """
+
+ def __init__(self, http: SyncHttpClient) -> None:
+ self.http = http
+
+ @overload
+ def stream(
+ self,
+ thread_id: str,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ feedback_keys: Sequence[str] | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ webhook: str | None = None,
+ multitask_strategy: MultitaskStrategy | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ version: Literal["v1"] = "v1",
+ ) -> Iterator[StreamPart]: ...
+
+ @overload
+ def stream(
+ self,
+ thread_id: str,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ feedback_keys: Sequence[str] | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ webhook: str | None = None,
+ multitask_strategy: MultitaskStrategy | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ version: Literal["v2"],
+ ) -> Iterator[StreamPartV2]: ...
+
+ @overload
+ def stream(
+ self,
+ thread_id: None,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ stream_resumable: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ feedback_keys: Sequence[str] | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ on_completion: OnCompletionBehavior | None = None,
+ if_not_exists: IfNotExists | None = None,
+ webhook: str | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ version: Literal["v1"] = "v1",
+ ) -> Iterator[StreamPart]: ...
+
+ @overload
+ def stream(
+ self,
+ thread_id: None,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ stream_resumable: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ feedback_keys: Sequence[str] | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ on_completion: OnCompletionBehavior | None = None,
+ if_not_exists: IfNotExists | None = None,
+ webhook: str | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ version: Literal["v2"],
+ ) -> Iterator[StreamPartV2]: ...
+
+ def stream(
+ self,
+ thread_id: str | None,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ stream_resumable: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None,
+ checkpoint_during: bool | None = None, # deprecated
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ feedback_keys: Sequence[str] | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ on_completion: OnCompletionBehavior | None = None,
+ webhook: str | None = None,
+ multitask_strategy: MultitaskStrategy | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ durability: Durability | None = None,
+ version: StreamVersion = "v1",
+ ) -> Iterator[StreamPart | StreamPartV2]:
+ """Create a run and stream the results.
+
+ Args:
+ thread_id: the thread ID to assign to the thread.
+ If `None` will create a stateless run.
+ assistant_id: The assistant ID or graph name to stream from.
+ If using graph name, will default to first assistant created from that graph.
+ input: The input to the graph.
+ command: The command to execute.
+ stream_mode: The stream mode(s) to use.
+ stream_subgraphs: Whether to stream output from subgraphs.
+ stream_resumable: Whether the stream is considered resumable.
+ If true, the stream can be resumed and replayed in its entirety even after disconnection.
+ metadata: Metadata to assign to the run.
+ config: The configuration for the assistant.
+ context: Static context to add to the assistant.
+ !!! version-added "Added in version 0.6.0"
+ checkpoint: The checkpoint to resume from.
+ checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
+ interrupt_before: Nodes to interrupt immediately before they get executed.
+ interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
+ feedback_keys: Feedback keys to assign to run.
+ on_disconnect: The disconnect mode to use.
+ Must be one of 'cancel' or 'continue'.
+ on_completion: Whether to delete or keep the thread created for a stateless run.
+ Must be one of 'delete' or 'keep'.
+ webhook: Webhook to call after LangGraph API call is done.
+ multitask_strategy: Multitask strategy to use.
+ Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
+ if_not_exists: How to handle missing thread. Defaults to 'reject'.
+ Must be either 'reject' (raise error if missing), or 'create' (create new thread).
+ after_seconds: The number of seconds to wait before starting the run.
+ Use to schedule future runs.
+ langsmith_tracing: LangSmith tracing configuration. Allows routing traces
+ to a specific project or associating with a dataset example.
+ headers: Optional custom headers to include with the request.
+ on_run_created: Optional callback to call when a run is created.
+ durability: The durability to use for the run. Values are "sync", "async", or "exit".
+ "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
+ "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
+ "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
+ version: Stream format version. "v1" (default) returns raw SSE StreamPart
+ NamedTuples. "v2" returns typed dicts with `type`, `ns`, and `data` keys.
+
+ Returns:
+ Iterator of stream results.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ async for chunk in client.runs.stream(
+ thread_id=None,
+ assistant_id="agent",
+ input={"messages": [{"role": "user", "content": "how are you?"}]},
+ stream_mode=["values","debug"],
+ metadata={"name":"my_run"},
+ context={"model_name": "anthropic"},
+ interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
+ interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
+ feedback_keys=["my_feedback_key_1","my_feedback_key_2"],
+ webhook="https://my.fake.webhook.com",
+ multitask_strategy="interrupt"
+ ):
+ print(chunk)
+ ```
+ ```shell
+ ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+
+ StreamPart(event='metadata', data={'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2'})
+ StreamPart(event='values', data={'messages': [{'content': 'how are you?', 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'human', 'name': None, 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10', 'example': False}]})
+ StreamPart(event='values', data={'messages': [{'content': 'how are you?', 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'human', 'name': None, 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10', 'example': False}, {'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.", 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'ai', 'name': None, 'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b', 'example': False, 'tool_calls': [], 'invalid_tool_calls': [], 'usage_metadata': None}]})
+ StreamPart(event='end', data=None)
+ ```
+ """
+ if checkpoint_during is not None:
+ warnings.warn(
+ "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ payload: dict[str, Any] = {
+ "input": input,
+ "command": (
+ {k: v for k, v in command.items() if v is not None} if command else None
+ ),
+ "config": config,
+ "context": context,
+ "metadata": metadata,
+ "stream_mode": stream_mode,
+ "stream_subgraphs": stream_subgraphs,
+ "stream_resumable": stream_resumable,
+ "assistant_id": assistant_id,
+ "interrupt_before": interrupt_before,
+ "interrupt_after": interrupt_after,
+ "feedback_keys": feedback_keys,
+ "webhook": webhook,
+ "checkpoint": checkpoint,
+ "checkpoint_id": checkpoint_id,
+ "checkpoint_during": checkpoint_during,
+ "multitask_strategy": multitask_strategy,
+ "if_not_exists": if_not_exists,
+ "on_disconnect": on_disconnect,
+ "on_completion": on_completion,
+ "after_seconds": after_seconds,
+ "durability": durability,
+ "langsmith_tracer": langsmith_tracing,
+ }
+ endpoint = (
+ f"/threads/{_quote_path_param(thread_id)}/runs/stream"
+ if thread_id is not None
+ else "/runs/stream"
+ )
+
+ def on_response(res: httpx.Response):
+ """Callback function to handle the response."""
+ if on_run_created and (metadata := _get_run_metadata_from_response(res)):
+ on_run_created(metadata)
+
+ raw = self.http.stream(
+ endpoint,
+ "POST",
+ json={k: v for k, v in payload.items() if v is not None},
+ params=params,
+ headers=headers,
+ on_response=on_response if on_run_created else None,
+ )
+ if version == "v2":
+ return _wrap_stream_v2_sync(raw)
+ return raw
+
+ @overload
+ def create(
+ self,
+ thread_id: None,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ stream_resumable: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ webhook: str | None = None,
+ on_completion: OnCompletionBehavior | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ ) -> Run: ...
+
+ @overload
+ def create(
+ self,
+ thread_id: str,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ stream_resumable: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ webhook: str | None = None,
+ multitask_strategy: MultitaskStrategy | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ ) -> Run: ...
+
+ def create(
+ self,
+ thread_id: str | None,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ stream_mode: StreamMode | Sequence[StreamMode] = "values",
+ stream_subgraphs: bool = False,
+ stream_resumable: bool = False,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None,
+ checkpoint_during: bool | None = None, # deprecated
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ webhook: str | None = None,
+ multitask_strategy: MultitaskStrategy | None = None,
+ if_not_exists: IfNotExists | None = None,
+ on_completion: OnCompletionBehavior | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ durability: Durability | None = None,
+ ) -> Run:
+ """Create a background run.
+
+ Args:
+ thread_id: the thread ID to assign to the thread.
+ If `None` will create a stateless run.
+ assistant_id: The assistant ID or graph name to stream from.
+ If using graph name, will default to first assistant created from that graph.
+ input: The input to the graph.
+ command: The command to execute.
+ stream_mode: The stream mode(s) to use.
+ stream_subgraphs: Whether to stream output from subgraphs.
+ stream_resumable: Whether the stream is considered resumable.
+ If true, the stream can be resumed and replayed in its entirety even after disconnection.
+ metadata: Metadata to assign to the run.
+ config: The configuration for the assistant.
+ context: Static context to add to the assistant.
+ !!! version-added "Added in version 0.6.0"
+ checkpoint: The checkpoint to resume from.
+ checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
+ interrupt_before: Nodes to interrupt immediately before they get executed.
+ interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
+ webhook: Webhook to call after LangGraph API call is done.
+ multitask_strategy: Multitask strategy to use.
+ Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
+ on_completion: Whether to delete or keep the thread created for a stateless run.
+ Must be one of 'delete' or 'keep'.
+ if_not_exists: How to handle missing thread. Defaults to 'reject'.
+ Must be either 'reject' (raise error if missing), or 'create' (create new thread).
+ after_seconds: The number of seconds to wait before starting the run.
+ Use to schedule future runs.
+ langsmith_tracing: LangSmith tracing configuration. Allows routing traces
+ to a specific project or associating with a dataset example.
+ headers: Optional custom headers to include with the request.
+ on_run_created: Optional callback to call when a run is created.
+ durability: The durability to use for the run. Values are "sync", "async", or "exit".
+ "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
+ "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
+ "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
+
+ Returns:
+ The created background `Run`.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ background_run = client.runs.create(
+ thread_id="my_thread_id",
+ assistant_id="my_assistant_id",
+ input={"messages": [{"role": "user", "content": "hello!"}]},
+ metadata={"name":"my_run"},
+ context={"model_name": "openai"},
+ interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
+ interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
+ webhook="https://my.fake.webhook.com",
+ multitask_strategy="interrupt"
+ )
+ print(background_run)
+ ```
+
+ ```shell
+ --------------------------------------------------------------------------------
+
+ {
+ 'run_id': 'my_run_id',
+ 'thread_id': 'my_thread_id',
+ 'assistant_id': 'my_assistant_id',
+ 'created_at': '2024-07-25T15:35:42.598503+00:00',
+ 'updated_at': '2024-07-25T15:35:42.598503+00:00',
+ 'metadata': {},
+ 'status': 'pending',
+ 'kwargs':
+ {
+ 'input':
+ {
+ 'messages': [
+ {
+ 'role': 'user',
+ 'content': 'how are you?'
+ }
+ ]
+ },
+ 'config':
+ {
+ 'metadata':
+ {
+ 'created_by': 'system'
+ },
+ 'configurable':
+ {
+ 'run_id': 'my_run_id',
+ 'user_id': None,
+ 'graph_id': 'agent',
+ 'thread_id': 'my_thread_id',
+ 'checkpoint_id': None,
+ 'assistant_id': 'my_assistant_id'
+ }
+ },
+ 'context':
+ {
+ 'model_name': 'openai'
+ },
+ 'webhook': "https://my.fake.webhook.com",
+ 'temporary': False,
+ 'stream_mode': ['values'],
+ 'feedback_keys': None,
+ 'interrupt_after': ["node_to_stop_after_1","node_to_stop_after_2"],
+ 'interrupt_before': ["node_to_stop_before_1","node_to_stop_before_2"]
+ },
+ 'multitask_strategy': 'interrupt'
+ }
+ ```
+ """
+ if checkpoint_during is not None:
+ warnings.warn(
+ "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ payload = {
+ "input": input,
+ "command": (
+ {k: v for k, v in command.items() if v is not None} if command else None
+ ),
+ "stream_mode": stream_mode,
+ "stream_subgraphs": stream_subgraphs,
+ "stream_resumable": stream_resumable,
+ "config": config,
+ "context": context,
+ "metadata": metadata,
+ "assistant_id": assistant_id,
+ "interrupt_before": interrupt_before,
+ "interrupt_after": interrupt_after,
+ "webhook": webhook,
+ "checkpoint": checkpoint,
+ "checkpoint_id": checkpoint_id,
+ "checkpoint_during": checkpoint_during,
+ "multitask_strategy": multitask_strategy,
+ "if_not_exists": if_not_exists,
+ "on_completion": on_completion,
+ "after_seconds": after_seconds,
+ "durability": durability,
+ "langsmith_tracer": langsmith_tracing,
+ }
+ payload = {k: v for k, v in payload.items() if v is not None}
+
+ def on_response(res: httpx.Response):
+ """Callback function to handle the response."""
+ if on_run_created and (metadata := _get_run_metadata_from_response(res)):
+ on_run_created(metadata)
+
+ return self.http.post(
+ f"/threads/{_quote_path_param(thread_id)}/runs" if thread_id else "/runs",
+ json=payload,
+ params=params,
+ headers=headers,
+ on_response=on_response if on_run_created else None,
+ )
+
+ def create_batch(
+ self,
+ payloads: builtins.list[RunCreate],
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> builtins.list[Run]:
+ """Create a batch of stateless background runs."""
+
+ def filter_payload(payload: RunCreate):
+ return {k: v for k, v in payload.items() if v is not None}
+
+ filtered = [filter_payload(payload) for payload in payloads]
+ return self.http.post(
+ "/runs/batch", json=filtered, headers=headers, params=params
+ )
+
+ @overload
+ def wait(
+ self,
+ thread_id: str,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ webhook: str | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ multitask_strategy: MultitaskStrategy | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ raise_error: bool = True,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ ) -> builtins.list[dict] | dict[str, Any]: ...
+
+ @overload
+ def wait(
+ self,
+ thread_id: None,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint_during: bool | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ webhook: str | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ on_completion: OnCompletionBehavior | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ raise_error: bool = True,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ ) -> builtins.list[dict] | dict[str, Any]: ...
+
+ def wait(
+ self,
+ thread_id: str | None,
+ assistant_id: str,
+ *,
+ input: Input | None = None,
+ command: Command | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ config: Config | None = None,
+ context: Context | None = None,
+ checkpoint_during: bool | None = None, # deprecated
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None,
+ interrupt_before: All | Sequence[str] | None = None,
+ interrupt_after: All | Sequence[str] | None = None,
+ webhook: str | None = None,
+ on_disconnect: DisconnectMode | None = None,
+ on_completion: OnCompletionBehavior | None = None,
+ multitask_strategy: MultitaskStrategy | None = None,
+ if_not_exists: IfNotExists | None = None,
+ after_seconds: int | None = None,
+ langsmith_tracing: LangSmithTracing | None = None,
+ raise_error: bool = True,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ on_run_created: Callable[[RunCreateMetadata], None] | None = None,
+ durability: Durability | None = None,
+ ) -> builtins.list[dict] | dict[str, Any]:
+ """Create a run, wait until it finishes and return the final state.
+
+ Args:
+ thread_id: the thread ID to create the run on.
+ If `None` will create a stateless run.
+ assistant_id: The assistant ID or graph name to run.
+ If using graph name, will default to first assistant created from that graph.
+ input: The input to the graph.
+ command: The command to execute.
+ metadata: Metadata to assign to the run.
+ config: The configuration for the assistant.
+ context: Static context to add to the assistant.
+ !!! version-added "Added in version 0.6.0"
+ checkpoint: The checkpoint to resume from.
+ checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
+ interrupt_before: Nodes to interrupt immediately before they get executed.
+ interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
+ webhook: Webhook to call after LangGraph API call is done.
+ on_disconnect: The disconnect mode to use.
+ Must be one of 'cancel' or 'continue'.
+ on_completion: Whether to delete or keep the thread created for a stateless run.
+ Must be one of 'delete' or 'keep'.
+ multitask_strategy: Multitask strategy to use.
+ Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
+ if_not_exists: How to handle missing thread. Defaults to 'reject'.
+ Must be either 'reject' (raise error if missing), or 'create' (create new thread).
+ after_seconds: The number of seconds to wait before starting the run.
+ Use to schedule future runs.
+ langsmith_tracing: LangSmith tracing configuration. Allows routing traces
+ to a specific project or associating with a dataset example.
+ raise_error: Whether to raise an error if the run fails.
+ headers: Optional custom headers to include with the request.
+ on_run_created: Optional callback to call when a run is created.
+ durability: The durability to use for the run. Values are "sync", "async", or "exit".
+ "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
+ "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
+ "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
+
+ Returns:
+ The output of the `Run`.
+
+ ???+ example "Example Usage"
+
+ ```python
+
+ final_state_of_run = client.runs.wait(
+ thread_id=None,
+ assistant_id="agent",
+ input={"messages": [{"role": "user", "content": "how are you?"}]},
+ metadata={"name":"my_run"},
+ context={"model_name": "anthropic"},
+ interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
+ interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
+ webhook="https://my.fake.webhook.com",
+ multitask_strategy="interrupt"
+ )
+ print(final_state_of_run)
+ ```
+
+ ```shell
+
+ -------------------------------------------------------------------------------------------------------------------------------------------
+
+ {
+ 'messages': [
+ {
+ 'content': 'how are you?',
+ 'additional_kwargs': {},
+ 'response_metadata': {},
+ 'type': 'human',
+ 'name': None,
+ 'id': 'f51a862c-62fe-4866-863b-b0863e8ad78a',
+ 'example': False
+ },
+ {
+ 'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
+ 'additional_kwargs': {},
+ 'response_metadata': {},
+ 'type': 'ai',
+ 'name': None,
+ 'id': 'run-bf1cd3c6-768f-4c16-b62d-ba6f17ad8b36',
+ 'example': False,
+ 'tool_calls': [],
+ 'invalid_tool_calls': [],
+ 'usage_metadata': None
+ }
+ ]
+ }
+ ```
+
+ """
+ if checkpoint_during is not None:
+ warnings.warn(
+ "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ payload = {
+ "input": input,
+ "command": (
+ {k: v for k, v in command.items() if v is not None} if command else None
+ ),
+ "config": config,
+ "context": context,
+ "metadata": metadata,
+ "assistant_id": assistant_id,
+ "interrupt_before": interrupt_before,
+ "interrupt_after": interrupt_after,
+ "webhook": webhook,
+ "checkpoint": checkpoint,
+ "checkpoint_id": checkpoint_id,
+ "multitask_strategy": multitask_strategy,
+ "if_not_exists": if_not_exists,
+ "on_disconnect": on_disconnect,
+ "checkpoint_during": checkpoint_during,
+ "on_completion": on_completion,
+ "after_seconds": after_seconds,
+ "raise_error": raise_error,
+ "durability": durability,
+ "langsmith_tracer": langsmith_tracing,
+ }
+
+ def on_response(res: httpx.Response):
+ """Callback function to handle the response."""
+ if on_run_created and (metadata := _get_run_metadata_from_response(res)):
+ on_run_created(metadata)
+
+ endpoint = (
+ f"/threads/{_quote_path_param(thread_id)}/runs/wait"
+ if thread_id is not None
+ else "/runs/wait"
+ )
+ return self.http.request_reconnect(
+ endpoint,
+ "POST",
+ json={k: v for k, v in payload.items() if v is not None},
+ params=params,
+ headers=headers,
+ on_response=on_response if on_run_created else None,
+ )
+
+ def list(
+ self,
+ thread_id: str,
+ *,
+ limit: int = 10,
+ offset: int = 0,
+ status: RunStatus | None = None,
+ select: builtins.list[RunSelectField] | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> builtins.list[Run]:
+ """List runs.
+
+ Args:
+ thread_id: The thread ID to list runs for.
+ limit: The maximum number of results to return.
+ offset: The number of results to skip.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The runs for the thread.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ client.runs.list(
+ thread_id="thread_id",
+ limit=5,
+ offset=5,
+ )
+ ```
+
+ """
+ query_params: dict[str, Any] = {"limit": limit, "offset": offset}
+ if status is not None:
+ query_params["status"] = status
+ if select:
+ query_params["select"] = select
+ if params:
+ query_params.update(params)
+ return self.http.get(
+ f"/threads/{_quote_path_param(thread_id)}/runs",
+ params=query_params,
+ headers=headers,
+ )
+
+ def get(
+ self,
+ thread_id: str,
+ run_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Run:
+ """Get a run.
+
+ Args:
+ thread_id: The thread ID to get.
+ run_id: The run ID to get.
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ `Run` object.
+
+ ???+ example "Example Usage"
+
+ ```python
+
+ run = client.runs.get(
+ thread_id="thread_id_to_delete",
+ run_id="run_id_to_delete",
+ )
+ ```
+ """
+
+ return self.http.get(
+ f"/threads/{_quote_path_param(thread_id)}/runs/{_quote_path_param(run_id)}",
+ headers=headers,
+ params=params,
+ )
+
+ def cancel(
+ self,
+ thread_id: str,
+ run_id: str,
+ *,
+ wait: bool = False,
+ action: CancelAction = "interrupt",
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Get a run.
+
+ Args:
+ thread_id: The thread ID to cancel.
+ run_id: The run ID to cancel.
+ wait: Whether to wait until run has completed.
+ action: Action to take when cancelling the run. Possible values
+ are `interrupt` or `rollback`. Default is `interrupt`.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ client.runs.cancel(
+ thread_id="thread_id_to_cancel",
+ run_id="run_id_to_cancel",
+ wait=True,
+ action="interrupt"
+ )
+ ```
+
+ """
+ query_params = {
+ "wait": 1 if wait else 0,
+ "action": action,
+ }
+ if params:
+ query_params.update(params)
+ if wait:
+ return self.http.request_reconnect(
+ f"/threads/{_quote_path_param(thread_id)}/runs/{_quote_path_param(run_id)}/cancel",
+ "POST",
+ json=None,
+ params=query_params,
+ headers=headers,
+ )
+ return self.http.post(
+ f"/threads/{_quote_path_param(thread_id)}/runs/{_quote_path_param(run_id)}/cancel",
+ json=None,
+ params=query_params,
+ headers=headers,
+ )
+
+ def cancel_many(
+ self,
+ *,
+ thread_id: str | None = None,
+ run_ids: Sequence[str] | None = None,
+ status: BulkCancelRunsStatus | None = None,
+ action: CancelAction = "interrupt",
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Cancel one or more runs.
+
+ Can cancel runs by thread ID and run IDs, or by status filter.
+
+ Args:
+ thread_id: The ID of the thread containing runs to cancel.
+ run_ids: List of run IDs to cancel.
+ status: Filter runs by status to cancel. Must be one of
+ `"pending"`, `"running"`, or `"all"`.
+ action: Action to take when cancelling the run. Possible values
+ are `"interrupt"` or `"rollback"`. Default is `"interrupt"`.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ # Cancel all pending runs
+ client.runs.cancel_many(status="pending")
+ # Cancel specific runs on a thread
+ client.runs.cancel_many(
+ thread_id="my_thread_id",
+ run_ids=["run_1", "run_2"],
+ action="rollback",
+ )
+ ```
+
+ """
+ payload: dict[str, Any] = {}
+ if thread_id:
+ payload["thread_id"] = thread_id
+ if run_ids:
+ payload["run_ids"] = run_ids
+ if status:
+ payload["status"] = status
+ query_params: dict[str, Any] = {"action": action}
+ if params:
+ query_params.update(params)
+ self.http.post(
+ "/runs/cancel",
+ json=payload,
+ headers=headers,
+ params=query_params,
+ )
+
+ def join(
+ self,
+ thread_id: str,
+ run_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> dict:
+ """Block until a run is done. Returns the final state of the thread.
+
+ Args:
+ thread_id: The thread ID to join.
+ run_id: The run ID to join.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ client.runs.join(
+ thread_id="thread_id_to_join",
+ run_id="run_id_to_join"
+ )
+ ```
+
+ """
+ return self.http.request_reconnect(
+ f"/threads/{_quote_path_param(thread_id)}/runs/{_quote_path_param(run_id)}/join",
+ "GET",
+ headers=headers,
+ params=params,
+ )
+
+ def join_stream(
+ self,
+ thread_id: str,
+ run_id: str,
+ *,
+ cancel_on_disconnect: bool = False,
+ stream_mode: StreamMode | Sequence[StreamMode] | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ last_event_id: str | None = None,
+ ) -> Iterator[StreamPart]:
+ """Stream output from a run in real-time, until the run is done.
+ Output is not buffered, so any output produced before this call will
+ not be received here.
+
+ Args:
+ thread_id: The thread ID to join.
+ run_id: The run ID to join.
+ stream_mode: The stream mode(s) to use. Must be a subset of the stream modes passed
+ when creating the run. Background runs default to having the union of all
+ stream modes.
+ cancel_on_disconnect: Whether to cancel the run when the stream is disconnected.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+ last_event_id: The last event ID to use for the stream.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ client.runs.join_stream(
+ thread_id="thread_id_to_join",
+ run_id="run_id_to_join",
+ stream_mode=["values", "debug"]
+ )
+ ```
+
+ """
+ query_params = {
+ "stream_mode": stream_mode,
+ "cancel_on_disconnect": cancel_on_disconnect,
+ }
+ if params:
+ query_params.update(params)
+ return self.http.stream(
+ f"/threads/{_quote_path_param(thread_id)}/runs/{_quote_path_param(run_id)}/stream",
+ "GET",
+ params=query_params,
+ headers={
+ **({"Last-Event-ID": last_event_id} if last_event_id else {}),
+ **(headers or {}),
+ }
+ or None,
+ )
+
+ def delete(
+ self,
+ thread_id: str,
+ run_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Delete a run.
+
+ Args:
+ thread_id: The thread ID to delete.
+ run_id: The run ID to delete.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ client.runs.delete(
+ thread_id="thread_id_to_delete",
+ run_id="run_id_to_delete"
+ )
+ ```
+
+ """
+ self.http.delete(
+ f"/threads/{_quote_path_param(thread_id)}/runs/{_quote_path_param(run_id)}",
+ headers=headers,
+ params=params,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/store.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/store.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e698fe70d3130976c80244e66278c65d49ca29b
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/store.py
@@ -0,0 +1,313 @@
+"""Synchronous store client for LangGraph SDK."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping, Sequence
+from typing import Any, Literal
+
+from langgraph_sdk._shared.utilities import _provided_vals
+from langgraph_sdk._sync.http import SyncHttpClient
+from langgraph_sdk.schema import (
+ Item,
+ ListNamespaceResponse,
+ QueryParamTypes,
+ SearchItemsResponse,
+)
+
+
+class SyncStoreClient:
+ """A client for synchronous operations on a key-value store.
+
+ Provides methods to interact with a remote key-value store, allowing
+ storage and retrieval of items within namespaced hierarchies.
+
+ ???+ example "Example"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024"))
+ client.store.put_item(["users", "profiles"], "user123", {"name": "Alice", "age": 30})
+ ```
+ """
+
+ def __init__(self, http: SyncHttpClient) -> None:
+ self.http = http
+
+ def put_item(
+ self,
+ namespace: Sequence[str],
+ /,
+ key: str,
+ value: Mapping[str, Any],
+ index: Literal[False] | list[str] | None = None,
+ ttl: int | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Store or update an item.
+
+ Args:
+ namespace: A list of strings representing the namespace path.
+ key: The unique identifier for the item within the namespace.
+ value: A dictionary containing the item's data.
+ index: Controls search indexing - None (use defaults), False (disable), or list of field paths to index.
+ ttl: Optional time-to-live in minutes for the item, or None for no expiration.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ client.store.put_item(
+ ["documents", "user123"],
+ key="item456",
+ value={"title": "My Document", "content": "Hello World"}
+ )
+ ```
+ """
+ for label in namespace:
+ if "." in label:
+ raise ValueError(
+ f"Invalid namespace label '{label}'. Namespace labels cannot contain periods ('.')."
+ )
+ payload = {
+ "namespace": namespace,
+ "key": key,
+ "value": value,
+ "index": index,
+ "ttl": ttl,
+ }
+ self.http.put(
+ "/store/items", json=_provided_vals(payload), headers=headers, params=params
+ )
+
+ def get_item(
+ self,
+ namespace: Sequence[str],
+ /,
+ key: str,
+ *,
+ refresh_ttl: bool | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Item:
+ """Retrieve a single item.
+
+ Args:
+ key: The unique identifier for the item.
+ namespace: Optional list of strings representing the namespace path.
+ refresh_ttl: Whether to refresh the TTL on this read operation. If `None`, uses the store's default behavior.
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ The retrieved item.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ item = client.store.get_item(
+ ["documents", "user123"],
+ key="item456",
+ )
+ print(item)
+ ```
+
+ ```shell
+ ----------------------------------------------------------------
+
+ {
+ 'namespace': ['documents', 'user123'],
+ 'key': 'item456',
+ 'value': {'title': 'My Document', 'content': 'Hello World'},
+ 'created_at': '2024-07-30T12:00:00Z',
+ 'updated_at': '2024-07-30T12:00:00Z'
+ }
+ ```
+ """
+ for label in namespace:
+ if "." in label:
+ raise ValueError(
+ f"Invalid namespace label '{label}'. Namespace labels cannot contain periods ('.')."
+ )
+
+ query_params: dict[str, Any] = {"key": key, "namespace": ".".join(namespace)}
+ if refresh_ttl is not None:
+ query_params["refresh_ttl"] = refresh_ttl
+ if params:
+ query_params.update(params)
+ return self.http.get("/store/items", params=query_params, headers=headers)
+
+ def delete_item(
+ self,
+ namespace: Sequence[str],
+ /,
+ key: str,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Delete an item.
+
+ Args:
+ key: The unique identifier for the item.
+ namespace: Optional list of strings representing the namespace path.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ client.store.delete_item(
+ ["documents", "user123"],
+ key="item456",
+ )
+ ```
+ """
+ self.http.delete(
+ "/store/items",
+ json={"key": key, "namespace": namespace},
+ headers=headers,
+ params=params,
+ )
+
+ def search_items(
+ self,
+ namespace_prefix: Sequence[str],
+ /,
+ filter: Mapping[str, Any] | None = None,
+ limit: int = 10,
+ offset: int = 0,
+ query: str | None = None,
+ refresh_ttl: bool | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> SearchItemsResponse:
+ """Search for items within a namespace prefix.
+
+ Args:
+ namespace_prefix: List of strings representing the namespace prefix.
+ filter: Optional dictionary of key-value pairs to filter results.
+ limit: Maximum number of items to return (default is 10).
+ offset: Number of items to skip before returning results (default is 0).
+ query: Optional query for natural language search.
+ refresh_ttl: Whether to refresh the TTL on items returned by this search. If `None`, uses the store's default behavior.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ A list of items matching the search criteria.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ items = client.store.search_items(
+ ["documents"],
+ filter={"author": "John Doe"},
+ limit=5,
+ offset=0
+ )
+ print(items)
+ ```
+ ```shell
+ ----------------------------------------------------------------
+
+ {
+ "items": [
+ {
+ "namespace": ["documents", "user123"],
+ "key": "item789",
+ "value": {
+ "title": "Another Document",
+ "author": "John Doe"
+ },
+ "created_at": "2024-07-30T12:00:00Z",
+ "updated_at": "2024-07-30T12:00:00Z"
+ },
+ # ... additional items ...
+ ]
+ }
+ ```
+ """
+ payload = {
+ "namespace_prefix": namespace_prefix,
+ "filter": filter,
+ "limit": limit,
+ "offset": offset,
+ "query": query,
+ "refresh_ttl": refresh_ttl,
+ }
+ return self.http.post(
+ "/store/items/search",
+ json=_provided_vals(payload),
+ headers=headers,
+ params=params,
+ )
+
+ def list_namespaces(
+ self,
+ prefix: list[str] | None = None,
+ suffix: list[str] | None = None,
+ max_depth: int | None = None,
+ limit: int = 100,
+ offset: int = 0,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> ListNamespaceResponse:
+ """List namespaces with optional match conditions.
+
+ Args:
+ prefix: Optional list of strings representing the prefix to filter namespaces.
+ suffix: Optional list of strings representing the suffix to filter namespaces.
+ max_depth: Optional integer specifying the maximum depth of namespaces to return.
+ limit: Maximum number of namespaces to return (default is 100).
+ offset: Number of namespaces to skip before returning results (default is 0).
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ A list of namespaces matching the criteria.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:8123")
+ namespaces = client.store.list_namespaces(
+ prefix=["documents"],
+ max_depth=3,
+ limit=10,
+ offset=0
+ )
+ print(namespaces)
+ ```
+
+ ```shell
+ ----------------------------------------------------------------
+
+ [
+ ["documents", "user123", "reports"],
+ ["documents", "user456", "invoices"],
+ ...
+ ]
+ ```
+ """
+ payload = {
+ "prefix": prefix,
+ "suffix": suffix,
+ "max_depth": max_depth,
+ "limit": limit,
+ "offset": offset,
+ }
+ return self.http.post(
+ "/store/namespaces",
+ json=_provided_vals(payload),
+ headers=headers,
+ params=params,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/threads.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/threads.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7c2ddf5bbb7e49418f84b26dbb9f7efc41030ce
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/_sync/threads.py
@@ -0,0 +1,771 @@
+"""Synchronous client for managing threads in LangGraph."""
+
+from __future__ import annotations
+
+from collections.abc import Iterator, Mapping, Sequence
+from typing import Any, Literal, overload
+
+from langgraph_sdk._shared.utilities import _quote_path_param
+from langgraph_sdk._sync.http import SyncHttpClient
+from langgraph_sdk.schema import (
+ Checkpoint,
+ Json,
+ OnConflictBehavior,
+ PruneStrategy,
+ QueryParamTypes,
+ SortOrder,
+ StreamPart,
+ Thread,
+ ThreadSelectField,
+ ThreadSortBy,
+ ThreadState,
+ ThreadStatus,
+ ThreadStreamMode,
+ ThreadUpdateStateResponse,
+)
+
+
+class SyncThreadsClient:
+ """Synchronous client for managing threads in LangGraph.
+
+ This class provides methods to create, retrieve, and manage threads,
+ which represent conversations or stateful interactions.
+
+ ???+ example "Example"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ thread = client.threads.create(metadata={"user_id": "123"})
+ ```
+ """
+
+ def __init__(self, http: SyncHttpClient) -> None:
+ self.http = http
+
+ def get(
+ self,
+ thread_id: str,
+ *,
+ include: Sequence[str] | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Thread:
+ """Get a thread by ID.
+
+ Args:
+ thread_id: The ID of the thread to get.
+ include: Additional fields to include in the response.
+ Supported values: `"ttl"`.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `Thread` object.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ thread = client.threads.get(
+ thread_id="my_thread_id"
+ )
+ print(thread)
+ ```
+ ```shell
+ -----------------------------------------------------
+
+ {
+ 'thread_id': 'my_thread_id',
+ 'created_at': '2024-07-18T18:35:15.540834+00:00',
+ 'updated_at': '2024-07-18T18:35:15.540834+00:00',
+ 'metadata': {'graph_id': 'agent'}
+ }
+ ```
+
+ """
+ query_params: dict[str, Any] = {}
+ if include:
+ query_params["include"] = ",".join(include)
+ if params:
+ query_params.update(params)
+ return self.http.get(
+ f"/threads/{_quote_path_param(thread_id)}",
+ headers=headers,
+ params=query_params or None,
+ )
+
+ def create(
+ self,
+ *,
+ metadata: Json = None,
+ thread_id: str | None = None,
+ if_exists: OnConflictBehavior | None = None,
+ supersteps: Sequence[dict[str, Sequence[dict[str, Any]]]] | None = None,
+ graph_id: str | None = None,
+ ttl: int | Mapping[str, Any] | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Thread:
+ """Create a new thread.
+
+ Args:
+ metadata: Metadata to add to thread.
+ thread_id: ID of thread.
+ If `None`, ID will be a randomly generated UUID.
+ if_exists: How to handle duplicate creation. Defaults to 'raise' under the hood.
+ Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing thread).
+ supersteps: Apply a list of supersteps when creating a thread, each containing a sequence of updates.
+ Each update has `values` or `command` and `as_node`. Used for copying a thread between deployments.
+ graph_id: Optional graph ID to associate with the thread.
+ ttl: Optional time-to-live in minutes for the thread. You can pass an
+ integer (minutes) or a mapping with keys `ttl` and optional
+ `strategy` (defaults to "delete").
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ The created `Thread`.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ thread = client.threads.create(
+ metadata={"number":1},
+ thread_id="my-thread-id",
+ if_exists="raise"
+ )
+ ```
+ )
+ """
+ payload: dict[str, Any] = {}
+ if thread_id:
+ payload["thread_id"] = thread_id
+ if metadata or graph_id:
+ payload["metadata"] = {
+ **(metadata or {}),
+ **({"graph_id": graph_id} if graph_id else {}),
+ }
+ if if_exists:
+ payload["if_exists"] = if_exists
+ if supersteps:
+ payload["supersteps"] = [
+ {
+ "updates": [
+ {
+ "values": u["values"],
+ "command": u.get("command"),
+ "as_node": u["as_node"],
+ }
+ for u in s["updates"]
+ ]
+ }
+ for s in supersteps
+ ]
+ if ttl is not None:
+ if isinstance(ttl, (int, float)):
+ payload["ttl"] = {"ttl": ttl, "strategy": "delete"}
+ else:
+ payload["ttl"] = ttl
+
+ return self.http.post("/threads", json=payload, headers=headers, params=params)
+
+ @overload
+ def update(
+ self,
+ thread_id: str,
+ *,
+ metadata: Mapping[str, Any],
+ ttl: int | Mapping[str, Any] | None = None,
+ return_minimal: Literal[False] = False,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Thread: ...
+
+ @overload
+ def update(
+ self,
+ thread_id: str,
+ *,
+ metadata: Mapping[str, Any],
+ ttl: int | Mapping[str, Any] | None = None,
+ return_minimal: Literal[True],
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None: ...
+
+ @overload
+ def update(
+ self,
+ thread_id: str,
+ *,
+ metadata: Mapping[str, Any],
+ ttl: int | Mapping[str, Any] | None = None,
+ return_minimal: bool,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Thread | None: ...
+
+ def update(
+ self,
+ thread_id: str,
+ *,
+ metadata: Mapping[str, Any],
+ ttl: int | Mapping[str, Any] | None = None,
+ return_minimal: bool = False,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Thread | None:
+ """Update a thread.
+
+ Args:
+ thread_id: ID of thread to update.
+ metadata: Metadata to merge with existing thread metadata.
+ ttl: Optional time-to-live in minutes for the thread. You can pass an
+ integer (minutes) or a mapping with keys `ttl` and optional
+ `strategy` (defaults to "delete").
+ return_minimal: If `True`, request a 204 response with no body.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ The updated `Thread`, or `None` when `return_minimal=True`.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ thread = client.threads.update(
+ thread_id="my-thread-id",
+ metadata={"number":1},
+ ttl=43_200,
+ )
+ ```
+ """
+ payload: dict[str, Any] = {"metadata": metadata}
+ if ttl is not None:
+ if isinstance(ttl, (int, float)):
+ payload["ttl"] = {"ttl": ttl, "strategy": "delete"}
+ else:
+ payload["ttl"] = ttl
+ request_headers = dict(headers or {})
+ if return_minimal:
+ request_headers["Prefer"] = "return=minimal"
+ return self.http.patch(
+ f"/threads/{_quote_path_param(thread_id)}",
+ json=payload,
+ headers=request_headers or None,
+ params=params,
+ )
+
+ def delete(
+ self,
+ thread_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Delete a thread.
+
+ Args:
+ thread_id: The ID of the thread to delete.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client.threads.delete(
+ thread_id="my_thread_id"
+ )
+ ```
+
+ """
+ self.http.delete(
+ f"/threads/{_quote_path_param(thread_id)}", headers=headers, params=params
+ )
+
+ def search(
+ self,
+ *,
+ metadata: Json = None,
+ values: Json = None,
+ ids: Sequence[str] | None = None,
+ status: ThreadStatus | None = None,
+ limit: int = 10,
+ offset: int = 0,
+ sort_by: ThreadSortBy | None = None,
+ sort_order: SortOrder | None = None,
+ select: list[ThreadSelectField] | None = None,
+ extract: dict[str, str] | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> list[Thread]:
+ """Search for threads.
+
+ Args:
+ metadata: Thread metadata to filter on.
+ values: State values to filter on.
+ ids: List of thread IDs to filter by.
+ status: Thread status to filter on.
+ Must be one of 'idle', 'busy', 'interrupted' or 'error'.
+ limit: Limit on number of threads to return.
+ offset: Offset in threads table to start search from.
+ sort_by: Sort by field.
+ sort_order: Sort order.
+ select: List of fields to include in the response.
+ extract: Dictionary mapping aliases to JSONB paths to extract
+ from thread data. Paths use dot notation for nested keys and
+ bracket notation for array indices (e.g.,
+ `{"last_msg": "values.messages[-1]"}`). Extracted values are
+ returned in an `extracted` field on each thread. Maximum 10
+ paths per request.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ List of the threads matching the search parameters.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ threads = client.threads.search(
+ metadata={"number":1},
+ status="interrupted",
+ limit=15,
+ offset=5
+ )
+ ```
+ """
+ payload: dict[str, Any] = {
+ "limit": limit,
+ "offset": offset,
+ }
+ if metadata:
+ payload["metadata"] = metadata
+ if values:
+ payload["values"] = values
+ if ids:
+ payload["ids"] = ids
+ if status:
+ payload["status"] = status
+ if sort_by:
+ payload["sort_by"] = sort_by
+ if sort_order:
+ payload["sort_order"] = sort_order
+ if select:
+ payload["select"] = select
+ if extract:
+ payload["extract"] = extract
+ return self.http.post(
+ "/threads/search", json=payload, headers=headers, params=params
+ )
+
+ def count(
+ self,
+ *,
+ metadata: Json = None,
+ values: Json = None,
+ status: ThreadStatus | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> int:
+ """Count threads matching filters.
+
+ Args:
+ metadata: Thread metadata to filter on.
+ values: State values to filter on.
+ status: Thread status to filter on.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ int: Number of threads matching the criteria.
+ """
+ payload: dict[str, Any] = {}
+ if metadata:
+ payload["metadata"] = metadata
+ if values:
+ payload["values"] = values
+ if status:
+ payload["status"] = status
+ return self.http.post(
+ "/threads/count", json=payload, headers=headers, params=params
+ )
+
+ def copy(
+ self,
+ thread_id: str,
+ *,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> None:
+ """Copy a thread.
+
+ Args:
+ thread_id: The ID of the thread to copy.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ `None`
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ client.threads.copy(
+ thread_id="my_thread_id"
+ )
+ ```
+
+ """
+ return self.http.post(
+ f"/threads/{_quote_path_param(thread_id)}/copy",
+ json=None,
+ headers=headers,
+ params=params,
+ )
+
+ def prune(
+ self,
+ thread_ids: Sequence[str],
+ *,
+ strategy: PruneStrategy = "delete",
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> dict[str, Any]:
+ """Prune threads by ID.
+
+ Args:
+ thread_ids: List of thread IDs to prune.
+ strategy: The prune strategy. `"delete"` removes threads entirely.
+ `"keep_latest"` prunes old checkpoints but keeps threads and their
+ latest state. Defaults to `"delete"`.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ A dict containing `pruned_count` (number of threads pruned).
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ result = client.threads.prune(
+ thread_ids=["thread_1", "thread_2"],
+ )
+ print(result) # {'pruned_count': 2}
+ ```
+
+ """
+ payload: dict[str, Any] = {
+ "thread_ids": thread_ids,
+ }
+ if strategy != "delete":
+ payload["strategy"] = strategy
+ return self.http.post(
+ "/threads/prune", json=payload, headers=headers, params=params
+ )
+
+ def get_state(
+ self,
+ thread_id: str,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None, # deprecated
+ *,
+ subgraphs: bool = False,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> ThreadState:
+ """Get the state of a thread.
+
+ Args:
+ thread_id: The ID of the thread to get the state of.
+ checkpoint: The checkpoint to get the state of.
+ subgraphs: Include subgraphs states.
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ The thread of the state.
+
+ ???+ example "Example Usage"
+
+ ```python
+ client = get_sync_client(url="http://localhost:2024")
+ thread_state = client.threads.get_state(
+ thread_id="my_thread_id",
+ checkpoint_id="my_checkpoint_id"
+ )
+ print(thread_state)
+ ```
+
+ ```shell
+ ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
+
+ {
+ 'values': {
+ 'messages': [
+ {
+ 'content': 'how are you?',
+ 'additional_kwargs': {},
+ 'response_metadata': {},
+ 'type': 'human',
+ 'name': None,
+ 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10',
+ 'example': False
+ },
+ {
+ 'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
+ 'additional_kwargs': {},
+ 'response_metadata': {},
+ 'type': 'ai',
+ 'name': None,
+ 'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
+ 'example': False,
+ 'tool_calls': [],
+ 'invalid_tool_calls': [],
+ 'usage_metadata': None
+ }
+ ]
+ },
+ 'next': [],
+ 'checkpoint':
+ {
+ 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
+ 'checkpoint_ns': '',
+ 'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1'
+ }
+ 'metadata':
+ {
+ 'step': 1,
+ 'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2',
+ 'source': 'loop',
+ 'writes':
+ {
+ 'agent':
+ {
+ 'messages': [
+ {
+ 'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
+ 'name': None,
+ 'type': 'ai',
+ 'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
+ 'example': False,
+ 'tool_calls': [],
+ 'usage_metadata': None,
+ 'additional_kwargs': {},
+ 'response_metadata': {},
+ 'invalid_tool_calls': []
+ }
+ ]
+ }
+ },
+ 'user_id': None,
+ 'graph_id': 'agent',
+ 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
+ 'created_by': 'system',
+ 'assistant_id': 'fe096781-5601-53d2-b2f6-0d3403f7e9ca'},
+ 'created_at': '2024-07-25T15:35:44.184703+00:00',
+ 'parent_config':
+ {
+ 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
+ 'checkpoint_ns': '',
+ 'checkpoint_id': '1ef4a9b8-d80d-6fa7-8000-9300467fad0f'
+ }
+ }
+ ```
+
+ """
+ if checkpoint:
+ return self.http.post(
+ f"/threads/{_quote_path_param(thread_id)}/state/checkpoint",
+ json={"checkpoint": checkpoint, "subgraphs": subgraphs},
+ headers=headers,
+ params=params,
+ )
+ elif checkpoint_id:
+ get_params = {"subgraphs": subgraphs}
+ if params:
+ get_params = {**get_params, **dict(params)}
+ return self.http.get(
+ f"/threads/{_quote_path_param(thread_id)}/state/{_quote_path_param(checkpoint_id)}",
+ params=get_params,
+ headers=headers,
+ )
+ else:
+ get_params = {"subgraphs": subgraphs}
+ if params:
+ get_params = {**get_params, **dict(params)}
+ return self.http.get(
+ f"/threads/{_quote_path_param(thread_id)}/state",
+ params=get_params,
+ headers=headers,
+ )
+
+ def update_state(
+ self,
+ thread_id: str,
+ values: dict[str, Any] | Sequence[dict] | None,
+ *,
+ as_node: str | None = None,
+ checkpoint: Checkpoint | None = None,
+ checkpoint_id: str | None = None, # deprecated
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> ThreadUpdateStateResponse:
+ """Update the state of a thread.
+
+ Args:
+ thread_id: The ID of the thread to update.
+ values: The values to update the state with.
+ as_node: Update the state as if this node had just executed.
+ checkpoint: The checkpoint to update the state of.
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ Response after updating a thread's state.
+
+ ???+ example "Example Usage"
+
+ ```python
+
+ response = await client.threads.update_state(
+ thread_id="my_thread_id",
+ values={"messages":[{"role": "user", "content": "hello!"}]},
+ as_node="my_node",
+ )
+ print(response)
+
+ ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
+
+ {
+ 'checkpoint': {
+ 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
+ 'checkpoint_ns': '',
+ 'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1',
+ 'checkpoint_map': {}
+ }
+ }
+ ```
+
+ """
+ payload: dict[str, Any] = {
+ "values": values,
+ }
+ if checkpoint_id:
+ payload["checkpoint_id"] = checkpoint_id
+ if checkpoint:
+ payload["checkpoint"] = checkpoint
+ if as_node:
+ payload["as_node"] = as_node
+ return self.http.post(
+ f"/threads/{_quote_path_param(thread_id)}/state",
+ json=payload,
+ headers=headers,
+ params=params,
+ )
+
+ def get_history(
+ self,
+ thread_id: str,
+ *,
+ limit: int = 10,
+ before: str | Checkpoint | None = None,
+ metadata: Mapping[str, Any] | None = None,
+ checkpoint: Checkpoint | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> list[ThreadState]:
+ """Get the state history of a thread.
+
+ Args:
+ thread_id: The ID of the thread to get the state history for.
+ checkpoint: Return states for this subgraph. If empty defaults to root.
+ limit: The maximum number of states to return.
+ before: Return states before this checkpoint.
+ metadata: Filter states by metadata key-value pairs.
+ headers: Optional custom headers to include with the request.
+
+ Returns:
+ The state history of the `Thread`.
+
+ ???+ example "Example Usage"
+
+ ```python
+
+ thread_state = client.threads.get_history(
+ thread_id="my_thread_id",
+ limit=5,
+ before="my_timestamp",
+ metadata={"name":"my_name"}
+ )
+ ```
+
+ """
+ payload: dict[str, Any] = {
+ "limit": limit,
+ }
+ if before:
+ payload["before"] = before
+ if metadata:
+ payload["metadata"] = metadata
+ if checkpoint:
+ payload["checkpoint"] = checkpoint
+ return self.http.post(
+ f"/threads/{_quote_path_param(thread_id)}/history",
+ json=payload,
+ headers=headers,
+ params=params,
+ )
+
+ def join_stream(
+ self,
+ thread_id: str,
+ *,
+ stream_mode: ThreadStreamMode | Sequence[ThreadStreamMode] = "run_modes",
+ last_event_id: str | None = None,
+ headers: Mapping[str, str] | None = None,
+ params: QueryParamTypes | None = None,
+ ) -> Iterator[StreamPart]:
+ """Get a stream of events for a thread.
+
+ Args:
+ thread_id: The ID of the thread to get the stream for.
+ last_event_id: The ID of the last event to get.
+ headers: Optional custom headers to include with the request.
+ params: Optional query parameters to include with the request.
+
+ Returns:
+ An iterator of stream parts.
+
+ ???+ example "Example Usage"
+
+ ```python
+
+ for chunk in client.threads.join_stream(
+ thread_id="my_thread_id",
+ last_event_id="my_event_id",
+ stream_mode="run_modes",
+ ):
+ print(chunk)
+ ```
+
+ """
+ query_params = {
+ "stream_mode": stream_mode,
+ }
+ if params:
+ query_params.update(params)
+ return self.http.stream(
+ f"/threads/{_quote_path_param(thread_id)}/stream",
+ "GET",
+ headers={
+ **({"Last-Event-ID": last_event_id} if last_event_id else {}),
+ **(headers or {}),
+ },
+ params=query_params,
+ )
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/auth/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/auth/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d627c5f4d544d28c6abddd6a85d945258ac650e2
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/auth/__init__.py
@@ -0,0 +1,876 @@
+from __future__ import annotations
+
+import inspect
+import typing
+from collections.abc import Callable, Sequence
+
+from langgraph_sdk.auth import exceptions, types
+
+TH = typing.TypeVar("TH", bound=types.Handler)
+AH = typing.TypeVar("AH", bound=types.Authenticator)
+
+
+class Auth:
+ """Add custom authentication and authorization management to your LangGraph application.
+
+ The Auth class provides a unified system for handling authentication and
+ authorization in LangGraph applications. It supports custom user authentication
+ protocols and fine-grained authorization rules for different resources and
+ actions.
+
+ To use, create a separate python file and add the path to the file to your
+ LangGraph API configuration file (`langgraph.json`). Within that file, create
+ an instance of the Auth class and register authentication and authorization
+ handlers as needed.
+
+ Example `langgraph.json` file:
+
+ ```json
+ {
+ "dependencies": ["."],
+ "graphs": {
+ "agent": "./my_agent/agent.py:graph"
+ },
+ "env": ".env",
+ "auth": {
+ "path": "./auth.py:my_auth"
+ }
+ ```
+
+ Then the LangGraph server will load your auth file and run it server-side whenever a request comes in.
+
+ ???+ example "Basic Usage"
+
+ ```python
+ from langgraph_sdk import Auth
+
+ my_auth = Auth()
+
+ @my_auth.authenticate
+ async def authenticate(authorization: str) -> Auth.types.MinimalUserDict:
+ user = await verify_token(authorization) # Your token verification logic
+ if not user:
+ raise Auth.exceptions.HTTPException(
+ status_code=401, detail="Unauthorized"
+ )
+ return {
+ "identity": user["id"],
+ "permissions": user.get("permissions", []),
+ }
+
+ # Default deny: reject all requests that don't have a specific handler
+ @my_auth.on
+ async def deny_all(ctx: Auth.types.AuthContext, value: Any) -> False:
+ return False
+
+ # Allow users to create threads with their own identity as owner
+ @my_auth.on.threads.create
+ async def allow_thread_create(
+ ctx: Auth.types.AuthContext, value: Auth.types.on.threads.create.value
+ ):
+ metadata = value.setdefault("metadata", {})
+ metadata["owner"] = ctx.user.identity
+
+ # Allow users to read and search their own threads
+ @my_auth.on.threads.read
+ async def allow_thread_read(
+ ctx: Auth.types.AuthContext, value: Auth.types.on.threads.read.value
+ ) -> Auth.types.FilterType:
+ return {"owner": ctx.user.identity}
+
+ @my_auth.on.threads.search
+ async def allow_thread_search(
+ ctx: Auth.types.AuthContext, value: Auth.types.on.threads.search.value
+ ) -> Auth.types.FilterType:
+ return {"owner": ctx.user.identity}
+
+ # Scope all store operations to the user's namespace
+ @my_auth.on.store
+ async def scope_store(ctx: Auth.types.AuthContext, value: Auth.types.on.store.value):
+ namespace = tuple(value["namespace"]) if value.get("namespace") else ()
+ if not namespace or namespace[0] != ctx.user.identity:
+ namespace = (ctx.user.identity, *namespace)
+ value["namespace"] = namespace
+ ```
+
+ ???+ note "Request Processing Flow"
+
+ 1. Authentication (your `@auth.authenticate` handler) is performed first on **every request**
+ 2. For authorization, the most specific matching handler is called:
+ * If a handler exists for the exact resource and action, it is used (e.g., `@auth.on.threads.create`)
+ * Otherwise, if a handler exists for the resource with any action, it is used (e.g., `@auth.on.threads`)
+ * Finally, if no specific handlers match, the global handler is used (e.g., `@auth.on`)
+ * If no global handler is set, the request is accepted
+
+ This allows you to set default behavior with a global handler while
+ overriding specific routes as needed.
+ """
+
+ __slots__ = (
+ "_authenticate_handler",
+ "_global_handlers",
+ "_handler_cache",
+ "_handlers",
+ "on",
+ )
+ types = types
+ """Reference to auth type definitions.
+
+ Provides access to all type definitions used in the auth system,
+ like ThreadsCreate, AssistantsRead, etc."""
+
+ exceptions = exceptions
+ """Reference to auth exception definitions.
+
+ Provides access to all exception definitions used in the auth system,
+ like HTTPException, etc.
+ """
+
+ def __init__(self) -> None:
+ self.on = _On(self)
+ """Entry point for authorization handlers that control access to specific resources.
+
+ The on class provides a flexible way to define authorization rules for different
+ resources and actions in your application. It supports three main usage patterns:
+
+ 1. Global handlers that run for all resources and actions
+ 2. Resource-specific handlers that run for all actions on a resource
+ 3. Resource and action specific handlers for fine-grained control
+
+ Each handler must be an async function that accepts two parameters:
+ - ctx (AuthContext): Contains request context and authenticated user info
+ - value: The data being authorized (type varies by endpoint)
+
+ The handler should return one of:
+
+ - None or True: Accept the request
+ - False: Reject with 403 error
+ - FilterType: Apply filtering rules to the response
+
+ ???+ example "Examples"
+
+ Start by denying all requests by default, then add specific handlers
+ to allow access:
+
+ ```python
+ # Default deny: reject all unhandled requests
+ @auth.on
+ async def deny_all(ctx: AuthContext, value: Any) -> False:
+ return False
+ ```
+
+ Resource-specific handler. This takes precedence over the global handler
+ for all actions on the `threads` resource:
+
+ ```python
+ @auth.on.threads
+ async def allow_thread_access(ctx: AuthContext, value: Any) -> Auth.types.FilterType:
+ # Only allow access to threads owned by the user
+ return {"owner": ctx.user.identity}
+ ```
+
+ Resource and action specific handler:
+
+ ```python
+ @auth.on.threads.delete
+ async def allow_admin_thread_deletion(ctx: AuthContext, value: Any) -> bool:
+ # Only admins can delete threads
+ return "admin" in ctx.user.permissions
+ ```
+
+ Multiple resources or actions:
+
+ ```python
+ @auth.on(resources=["threads", "assistants"], actions=["read", "search"])
+ async def allow_reads(ctx: AuthContext, value: Any) -> Auth.types.FilterType:
+ # Allow read/search access to resources owned by the user
+ return {"owner": ctx.user.identity}
+ ```
+
+ Auth for the `store` resource is a bit different since its structure is developer defined.
+ You typically want to scope store operations by rewriting the namespace to include the user's identity.
+ The `value` dict is mutable — changes to `value["namespace"]` are used by the server for the actual operation.
+
+ ```python
+ @auth.on.store
+ async def scope_store(ctx: AuthContext, value: Auth.types.on.store.value):
+ # Allow store access but scope to user's namespace
+ namespace = tuple(value["namespace"]) if value.get("namespace") else ()
+ if not namespace or namespace[0] != ctx.user.identity:
+ namespace = (ctx.user.identity, *namespace)
+ value["namespace"] = namespace
+ ```
+
+ You can also register handlers for specific store actions:
+
+ ```python
+ @auth.on.store.put
+ async def allow_put(ctx: AuthContext, value: Auth.types.on.store.put.value):
+ # Allow puts, scoped to user's namespace
+ value["namespace"] = (ctx.user.identity, *value["namespace"])
+
+ @auth.on.store.get
+ async def allow_get(ctx: AuthContext, value: Auth.types.on.store.get.value):
+ # Allow gets, scoped to user's namespace
+ value["namespace"] = (ctx.user.identity, *value["namespace"])
+ ```
+ """
+ # These are accessed by the API. Changes to their names or types is
+ # will be considered a breaking change.
+ self._handlers: dict[tuple[str, str], list[types.Handler]] = {}
+ self._global_handlers: list[types.Handler] = []
+ self._authenticate_handler: types.Authenticator | None = None
+ self._handler_cache: dict[tuple[str, str], types.Handler] = {}
+
+ def authenticate(self, fn: AH) -> AH:
+ """Register an authentication handler function.
+
+ The authentication handler is responsible for verifying credentials
+ and returning user scopes. It can accept any of the following parameters
+ by name:
+
+ - request (Request): The raw ASGI request object
+ - path (str): The request path, e.g., "/threads/abcd-1234-abcd-1234/runs/abcd-1234-abcd-1234/stream"
+ - method (str): The HTTP method, e.g., "GET"
+ - path_params (dict[str, str]): URL path parameters, e.g., {"thread_id": "abcd-1234-abcd-1234", "run_id": "abcd-1234-abcd-1234"}
+ - query_params (dict[str, str]): URL query parameters, e.g., {"stream": "true"}
+ - headers (dict[bytes, bytes]): Request headers
+ - authorization (str | None): The Authorization header value (e.g., "Bearer ")
+
+ Args:
+ fn: The authentication handler function to register.
+ Must return a representation of the user. This could be a:
+ - string (the user id)
+ - dict containing {"identity": str, "permissions": list[str]}
+ - or an object with identity and permissions properties
+ Permissions can be optionally used by your handlers downstream.
+
+ Returns:
+ The registered handler function.
+
+ Raises:
+ ValueError: If an authentication handler is already registered.
+
+ ???+ example "Examples"
+
+ Basic token authentication:
+
+ ```python
+ @auth.authenticate
+ async def authenticate(authorization: str) -> str:
+ user_id = verify_token(authorization)
+ return user_id
+ ```
+
+ Accept the full request context:
+
+ ```python
+ @auth.authenticate
+ async def authenticate(
+ method: str,
+ path: str,
+ headers: dict[str, bytes]
+ ) -> str:
+ user = await verify_request(method, path, headers)
+ return user
+ ```
+
+ Return user name and permissions:
+
+ ```python
+ @auth.authenticate
+ async def authenticate(
+ method: str,
+ path: str,
+ headers: dict[str, bytes]
+ ) -> Auth.types.MinimalUserDict:
+ permissions, user = await verify_request(method, path, headers)
+ # Permissions could be things like ["runs:read", "runs:write", "threads:read", "threads:write"]
+ return {
+ "identity": user["id"],
+ "permissions": permissions,
+ "display_name": user["name"],
+ }
+ ```
+ """
+ if self._authenticate_handler is not None:
+ raise ValueError(
+ f"Authentication handler already set as {self._authenticate_handler}."
+ )
+ self._authenticate_handler = fn
+ return fn
+
+
+## Helper types & utilities
+
+V = typing.TypeVar("V", contravariant=True)
+
+
+class _ActionHandler(typing.Protocol[V]):
+ async def __call__(
+ self, *, ctx: types.AuthContext, value: V
+ ) -> types.HandlerResult: ...
+
+
+T = typing.TypeVar("T", covariant=True)
+
+
+class _ResourceActionOn(typing.Generic[T]):
+ def __init__(
+ self,
+ auth: Auth,
+ resource: typing.Literal["threads", "crons", "assistants"],
+ action: typing.Literal[
+ "create", "read", "update", "delete", "search", "create_run"
+ ],
+ value: type[T],
+ ) -> None:
+ self.auth = auth
+ self.resource = resource
+ self.action = action
+ self.value = value
+
+ def __call__(self, fn: _ActionHandler[T]) -> _ActionHandler[T]:
+ _validate_handler(fn)
+ _register_handler(self.auth, self.resource, self.action, fn)
+ return fn
+
+
+VCreate = typing.TypeVar("VCreate", covariant=True)
+VUpdate = typing.TypeVar("VUpdate", covariant=True)
+VRead = typing.TypeVar("VRead", covariant=True)
+VDelete = typing.TypeVar("VDelete", covariant=True)
+VSearch = typing.TypeVar("VSearch", covariant=True)
+
+
+class _ResourceOn(typing.Generic[VCreate, VRead, VUpdate, VDelete, VSearch]):
+ """
+ Generic base class for resource-specific handlers.
+ """
+
+ value: type[VCreate | VUpdate | VRead | VDelete | VSearch]
+
+ Create: type[VCreate]
+ Read: type[VRead]
+ Update: type[VUpdate]
+ Delete: type[VDelete]
+ Search: type[VSearch]
+
+ def __init__(
+ self,
+ auth: Auth,
+ resource: typing.Literal["threads", "crons", "assistants"],
+ ) -> None:
+ self.auth = auth
+ self.resource = resource
+ self.create: _ResourceActionOn[VCreate] = _ResourceActionOn(
+ auth, resource, "create", self.Create
+ )
+ self.read: _ResourceActionOn[VRead] = _ResourceActionOn(
+ auth, resource, "read", self.Read
+ )
+ self.update: _ResourceActionOn[VUpdate] = _ResourceActionOn(
+ auth, resource, "update", self.Update
+ )
+ self.delete: _ResourceActionOn[VDelete] = _ResourceActionOn(
+ auth, resource, "delete", self.Delete
+ )
+ self.search: _ResourceActionOn[VSearch] = _ResourceActionOn(
+ auth, resource, "search", self.Search
+ )
+
+ @typing.overload
+ def __call__(
+ self,
+ fn: (
+ _ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]
+ | _ActionHandler[dict[str, typing.Any]]
+ ),
+ ) -> _ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]: ...
+
+ @typing.overload
+ def __call__(
+ self,
+ *,
+ resources: str | Sequence[str],
+ actions: str | Sequence[str] | None = None,
+ ) -> Callable[
+ [_ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]],
+ _ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch],
+ ]: ...
+
+ def __call__(
+ self,
+ fn: (
+ _ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]
+ | _ActionHandler[dict[str, typing.Any]]
+ | None
+ ) = None,
+ *,
+ resources: str | Sequence[str] | None = None,
+ actions: str | Sequence[str] | None = None,
+ ) -> (
+ _ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]
+ | Callable[
+ [_ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]],
+ _ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch],
+ ]
+ ):
+ if fn is not None:
+ _validate_handler(fn)
+ return typing.cast(
+ "_ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]",
+ _register_handler(self.auth, self.resource, "*", fn),
+ )
+
+ def decorator(
+ handler: _ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch],
+ ) -> _ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]:
+ _validate_handler(handler)
+ return typing.cast(
+ "_ActionHandler[VCreate | VUpdate | VRead | VDelete | VSearch]",
+ _register_handler(self.auth, self.resource, "*", handler),
+ )
+
+ # Accept keyword-only parameters for future filtering behavior; referenced to satisfy linters.
+ _ = resources, actions
+ return decorator
+
+
+class _AssistantsOn(
+ _ResourceOn[
+ types.AssistantsCreate,
+ types.AssistantsRead,
+ types.AssistantsUpdate,
+ types.AssistantsDelete,
+ types.AssistantsSearch,
+ ]
+):
+ value = (
+ types.AssistantsCreate
+ | types.AssistantsRead
+ | types.AssistantsUpdate
+ | types.AssistantsDelete
+ | types.AssistantsSearch
+ )
+ Create = types.AssistantsCreate
+ Read = types.AssistantsRead
+ Update = types.AssistantsUpdate
+ Delete = types.AssistantsDelete
+ Search = types.AssistantsSearch
+
+
+class _ThreadsOn(
+ _ResourceOn[
+ types.ThreadsCreate,
+ types.ThreadsRead,
+ types.ThreadsUpdate,
+ types.ThreadsDelete,
+ types.ThreadsSearch,
+ ]
+):
+ value = (
+ types.ThreadsCreate
+ | types.ThreadsRead
+ | types.ThreadsUpdate
+ | types.ThreadsDelete
+ | types.ThreadsSearch
+ | types.RunsCreate
+ )
+ Create = types.ThreadsCreate
+ Read = types.ThreadsRead
+ Update = types.ThreadsUpdate
+ Delete = types.ThreadsDelete
+ Search = types.ThreadsSearch
+ CreateRun = types.RunsCreate
+
+ def __init__(
+ self,
+ auth: Auth,
+ resource: typing.Literal["threads", "crons", "assistants"],
+ ) -> None:
+ super().__init__(auth, resource)
+ self.create_run: _ResourceActionOn[types.RunsCreate] = _ResourceActionOn(
+ auth, resource, "create_run", self.CreateRun
+ )
+
+
+class _CronsOn(
+ _ResourceOn[
+ types.CronsCreate,
+ types.CronsRead,
+ types.CronsUpdate,
+ types.CronsDelete,
+ types.CronsSearch,
+ ]
+):
+ value = type[
+ types.CronsCreate
+ | types.CronsRead
+ | types.CronsUpdate
+ | types.CronsDelete
+ | types.CronsSearch
+ ]
+
+ Create = types.CronsCreate
+ Read = types.CronsRead
+ Update = types.CronsUpdate
+ Delete = types.CronsDelete
+ Search = types.CronsSearch
+
+
+class _StoreActionOn(typing.Generic[T]):
+ """Decorator for registering a handler for a specific store action."""
+
+ def __init__(
+ self,
+ auth: Auth,
+ action: typing.Literal["put", "get", "search", "delete", "list_namespaces"],
+ value: type[T],
+ ) -> None:
+ self.auth = auth
+ self.action = action
+ self.value = value
+
+ def __call__(self, fn: _ActionHandler[T]) -> _ActionHandler[T]:
+ _validate_handler(fn)
+ _register_handler(self.auth, "store", self.action, fn)
+ return fn
+
+
+class _StoreOn:
+ def __init__(self, auth: Auth) -> None:
+ self._auth = auth
+ self.put = _StoreActionOn(auth, "put", types.StorePut)
+ """Register a handler for store put operations.
+
+ ???+ example "Example"
+ If using `@auth.on` to deny by default, register this handler to allow
+ put operations (scoped to the user's namespace):
+
+ ```python
+ @auth.on.store.put
+ async def allow_store_put(ctx: Auth.types.AuthContext, value: Auth.types.on.store.put.value):
+ # Allow puts, scoped to user's namespace
+ value["namespace"] = (ctx.user.identity, *value["namespace"])
+ ```
+ """
+ self.get = _StoreActionOn(auth, "get", types.StoreGet)
+ """Register a handler for store get operations.
+
+ ???+ example "Example"
+ If using `@auth.on` to deny by default, register this handler to allow
+ get operations (scoped to the user's namespace):
+
+ ```python
+ @auth.on.store.get
+ async def allow_store_get(ctx: Auth.types.AuthContext, value: Auth.types.on.store.get.value):
+ # Allow gets, scoped to user's namespace
+ value["namespace"] = (ctx.user.identity, *value["namespace"])
+ ```
+ """
+ self.search = _StoreActionOn(auth, "search", types.StoreSearch)
+ """Register a handler for store search operations.
+
+ ???+ example "Example"
+ If using `@auth.on` to deny by default, register this handler to allow
+ search operations (scoped to the user's namespace):
+
+ ```python
+ @auth.on.store.search
+ async def allow_store_search(ctx: Auth.types.AuthContext, value: Auth.types.on.store.search.value):
+ # Allow searches, scoped to user's namespace
+ value["namespace"] = (ctx.user.identity, *value["namespace"])
+ ```
+ """
+ self.delete = _StoreActionOn(auth, "delete", types.StoreDelete)
+ """Register a handler for store delete operations.
+
+ ???+ example "Example"
+ If using `@auth.on` to deny by default, register this handler to allow
+ delete operations (scoped to the user's namespace):
+
+ ```python
+ @auth.on.store.delete
+ async def allow_store_delete(ctx: Auth.types.AuthContext, value: Auth.types.on.store.delete.value):
+ # Allow deletes, scoped to user's namespace
+ value["namespace"] = (ctx.user.identity, *value["namespace"])
+ ```
+ """
+ self.list_namespaces = _StoreActionOn(
+ auth, "list_namespaces", types.StoreListNamespaces
+ )
+ """Register a handler for store list_namespaces operations.
+
+ ???+ example "Example"
+ If using `@auth.on` to deny by default, register this handler to allow
+ namespace listing (scoped to the user's prefix):
+
+ ```python
+ @auth.on.store.list_namespaces
+ async def allow_list_ns(ctx: Auth.types.AuthContext, value: Auth.types.on.store.list_namespaces.value):
+ # Allow listing, scoped to user's namespace prefix
+ value["namespace"] = (ctx.user.identity,)
+ ```
+ """
+
+ @typing.overload
+ def __call__(
+ self,
+ *,
+ actions: (
+ typing.Literal["put", "get", "search", "list_namespaces", "delete"]
+ | Sequence[
+ typing.Literal["put", "get", "search", "list_namespaces", "delete"]
+ ]
+ | None
+ ) = None,
+ ) -> Callable[[AHO], AHO]: ...
+
+ @typing.overload
+ def __call__(self, fn: AHO) -> AHO: ...
+
+ def __call__(
+ self,
+ fn: AHO | None = None,
+ *,
+ actions: (
+ typing.Literal["put", "get", "search", "list_namespaces", "delete"]
+ | Sequence[
+ typing.Literal["put", "get", "search", "list_namespaces", "delete"]
+ ]
+ | None
+ ) = None,
+ ) -> AHO | Callable[[AHO], AHO]:
+ """Register a handler for specific resources and actions.
+
+ Can be used as a decorator or with explicit resource/action parameters:
+
+ @auth.on.store
+ async def handler(): ... # Handle all store ops
+
+ @auth.on.store(actions=("put", "get", "search", "delete"))
+ async def handler(): ... # Handle specific store ops
+
+ @auth.on.store.put
+ async def handler(): ... # Handle store.put ops
+ """
+ if fn is not None:
+ # Used as a plain decorator
+ _register_handler(self._auth, "store", None, fn)
+ return fn
+
+ # Used with parameters, return a decorator
+ def decorator(
+ handler: AHO,
+ ) -> AHO:
+ if isinstance(actions, str):
+ action_list = [actions]
+ else:
+ action_list = list(actions) if actions is not None else ["*"]
+ for action in action_list:
+ _register_handler(self._auth, "store", action, handler)
+ return handler
+
+ return decorator
+
+
+AHO = typing.TypeVar("AHO", bound=_ActionHandler[dict[str, typing.Any]])
+
+
+class _On:
+ """Entry point for authorization handlers that control access to specific resources.
+
+ The _On class provides a flexible way to define authorization rules for different resources
+ and actions in your application. It supports three main usage patterns:
+
+ 1. Global handlers that run for all resources and actions
+ 2. Resource-specific handlers that run for all actions on a resource
+ 3. Resource and action specific handlers for fine-grained control
+
+ Each handler must be an async function that accepts two parameters:
+ - ctx (AuthContext): Contains request context and authenticated user info
+ - value: The data being authorized (type varies by endpoint)
+
+ The handler should return one of:
+ - None or True: Accept the request
+ - False: Reject with 403 error
+ - FilterType: Apply filtering rules to the response
+
+ ???+ example "Examples"
+
+ Start by denying all requests by default with a global handler,
+ then add specific handlers to allow access:
+
+ ```python
+ # Default deny: reject all requests without a specific handler
+ @auth.on
+ async def deny_all(ctx: AuthContext, value: Any) -> False:
+ return False
+ ```
+
+ Resource-specific handler to allow access (takes precedence
+ over the global deny handler):
+
+ ```python
+ @auth.on.threads
+ async def allow_thread_access(ctx: AuthContext, value: Any) -> Auth.types.FilterType:
+ # Allow access only to threads owned by the user
+ return {"owner": ctx.user.identity}
+ ```
+
+ Resource and action specific handler:
+
+ ```python
+ @auth.on.threads.create
+ async def allow_thread_create(ctx: AuthContext, value: Any) -> None:
+ # Allow thread creation, stamping the owner
+ value.setdefault("metadata", {})["owner"] = ctx.user.identity
+ ```
+
+ Multiple resources or actions:
+
+ ```python
+ @auth.on(resources=["threads", "assistants"], actions=["read", "search"])
+ async def allow_reads(ctx: AuthContext, value: Any) -> Auth.types.FilterType:
+ # Allow read/search, scoped to user's resources
+ return {"owner": ctx.user.identity}
+ ```
+ """
+
+ __slots__ = (
+ "_auth",
+ "assistants",
+ "crons",
+ "runs",
+ "store",
+ "threads",
+ "value",
+ )
+
+ def __init__(self, auth: Auth) -> None:
+ self._auth = auth
+ self.assistants = _AssistantsOn(auth, "assistants")
+ self.threads = _ThreadsOn(auth, "threads")
+ self.crons = _CronsOn(auth, "crons")
+ self.store = _StoreOn(auth)
+ self.value = dict[str, typing.Any]
+
+ @typing.overload
+ def __call__(
+ self,
+ *,
+ resources: str | Sequence[str],
+ actions: str | Sequence[str] | None = None,
+ ) -> Callable[[AHO], AHO]: ...
+
+ @typing.overload
+ def __call__(self, fn: AHO) -> AHO: ...
+
+ def __call__(
+ self,
+ fn: AHO | None = None,
+ *,
+ resources: str | Sequence[str] | None = None,
+ actions: str | Sequence[str] | None = None,
+ ) -> AHO | Callable[[AHO], AHO]:
+ """Register a handler for specific resources and actions.
+
+ Can be used as a decorator or with explicit resource/action parameters:
+
+ @auth.on
+ async def handler(): ... # Global handler
+
+ @auth.on(resources="threads")
+ async def handler(): ... # types.Handler for all thread actions
+
+ @auth.on(resources="threads", actions="create")
+ async def handler(): ... # types.Handler for thread creation
+ """
+ if fn is not None:
+ # Used as a plain decorator
+ _register_handler(self._auth, None, None, fn)
+ return fn
+
+ # Used with parameters, return a decorator
+ def decorator(
+ handler: AHO,
+ ) -> AHO:
+ if isinstance(resources, str):
+ resource_list = [resources]
+ else:
+ resource_list = list(resources) if resources is not None else ["*"]
+
+ if isinstance(actions, str):
+ action_list = [actions]
+ else:
+ action_list = list(actions) if actions is not None else ["*"]
+ for resource in resource_list:
+ for action in action_list:
+ _register_handler(self._auth, resource, action, handler)
+ return handler
+
+ return decorator
+
+
+def _register_handler(
+ auth: Auth,
+ resource: str | None,
+ action: str | None,
+ fn: types.Handler,
+) -> types.Handler:
+ _validate_handler(fn)
+ resource = resource or "*"
+ action = action or "*"
+ if resource == "*" and action == "*":
+ if auth._global_handlers:
+ raise ValueError("Global handler already set.")
+ auth._global_handlers.append(fn)
+ else:
+ r = resource if resource is not None else "*"
+ a = action if action is not None else "*"
+ if (r, a) in auth._handlers:
+ raise ValueError(f"types.Handler already set for {r}, {a}.")
+ auth._handlers[(r, a)] = [fn]
+ return fn
+
+
+def _validate_handler(fn: Callable[..., typing.Any]) -> None:
+ """Validates that an auth handler function meets the required signature.
+
+ Auth handlers must:
+ 1. Be async functions
+ 2. Accept a ctx parameter of type AuthContext
+ 3. Accept a value parameter for the data being authorized
+ """
+ if not inspect.iscoroutinefunction(fn):
+ raise ValueError(
+ f"Auth handler '{getattr(fn, '__name__', fn)}' must be an async function. "
+ "Add 'async' before 'def' to make it asynchronous and ensure"
+ " any IO operations are non-blocking."
+ )
+
+ sig = inspect.signature(fn)
+ if "ctx" not in sig.parameters:
+ raise ValueError(
+ f"Auth handler '{getattr(fn, '__name__', fn)}' must have a 'ctx: AuthContext' parameter. "
+ "Update the function signature to include this required parameter."
+ )
+ if "value" not in sig.parameters:
+ raise ValueError(
+ f"Auth handler '{getattr(fn, '__name__', fn)}' must have a 'value' parameter. "
+ " The value contains the mutable data being sent to the endpoint."
+ "Update the function signature to include this required parameter."
+ )
+
+
+def is_studio_user(
+ user: types.MinimalUser | types.BaseUser | types.MinimalUserDict,
+) -> bool:
+ return (
+ isinstance(user, types.StudioUser)
+ or (isinstance(user, dict) and user.get("kind") == "StudioUser") # ty: ignore[invalid-argument-type]
+ )
+
+
+__all__ = ["Auth", "exceptions", "types"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/auth/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/auth/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b47592945275ce7c172d9f3f8b6b483a5b8f2957
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/auth/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/auth/__pycache__/exceptions.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/auth/__pycache__/exceptions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..713d9483d8b5db5f4b77e8bb93232f3d3c699fd4
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/auth/__pycache__/exceptions.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/auth/__pycache__/types.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/auth/__pycache__/types.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7919f1b011fd3035f4fac441f2509a821e5cd06e
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/auth/__pycache__/types.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/auth/exceptions.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/auth/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..594939e752d1c3d218cf7284d5eda55600a84891
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/auth/exceptions.py
@@ -0,0 +1,59 @@
+"""Exceptions used in the auth system."""
+
+from __future__ import annotations
+
+import http
+from collections.abc import Mapping
+
+
+class HTTPException(Exception):
+ """HTTP exception that you can raise to return a specific HTTP error response.
+
+ Since this is defined in the auth module, we default to a 401 status code.
+
+ Args:
+ status_code: HTTP status code for the error. Defaults to 401 "Unauthorized".
+ detail: Detailed error message. If `None`, uses a default
+ message based on the status code.
+ headers: Additional HTTP headers to include in the error response.
+
+ Example:
+ Default:
+ ```python
+ raise HTTPException()
+ # HTTPException(status_code=401, detail='Unauthorized')
+ ```
+
+ Add headers:
+ ```python
+ raise HTTPException(headers={"X-Custom-Header": "Custom Value"})
+ # HTTPException(status_code=401, detail='Unauthorized', headers={"WWW-Authenticate": "Bearer"})
+ ```
+
+ Custom error:
+ ```python
+ raise HTTPException(status_code=404, detail="Not found")
+ ```
+ """
+
+ def __init__(
+ self,
+ status_code: int = 401,
+ detail: str | None = None,
+ headers: Mapping[str, str] | None = None,
+ ) -> None:
+ if detail is None:
+ detail = http.HTTPStatus(status_code).phrase
+ self.status_code = status_code
+ self.detail = detail
+ self.headers = headers
+
+ def __str__(self) -> str:
+ return f"{self.status_code}: {self.detail}"
+
+ def __repr__(self) -> str:
+ class_name = self.__class__.__name__
+ return f"{class_name}(status_code={self.status_code!r}, detail={self.detail!r})"
+
+
+__all__ = ["HTTPException"]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/auth/types.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/auth/types.py
new file mode 100644
index 0000000000000000000000000000000000000000..84211878d919fdc3bfd62a472f123ca32f0735fe
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/auth/types.py
@@ -0,0 +1,1162 @@
+"""Authentication and authorization types for LangGraph.
+
+This module defines the core types used for authentication, authorization, and
+request handling in LangGraph. It includes user protocols, authentication contexts,
+and typed dictionaries for various API operations.
+
+Note:
+ All typing.TypedDict classes use total=False to make all fields typing.Optional by default.
+"""
+
+from __future__ import annotations
+
+import typing
+from collections.abc import Awaitable, Callable, Sequence
+from dataclasses import dataclass
+from datetime import datetime
+from uuid import UUID
+
+import typing_extensions
+
+RunStatus = typing.Literal["pending", "error", "success", "timeout", "interrupted"]
+"""Status of a run execution.
+
+Values:
+ - pending: Run is queued or in progress
+ - error: Run failed with an error
+ - success: Run completed successfully
+ - timeout: Run exceeded time limit
+ - interrupted: Run was manually interrupted
+"""
+
+MultitaskStrategy = typing.Literal["reject", "rollback", "interrupt", "enqueue"]
+"""Strategy for handling multiple concurrent tasks.
+
+Values:
+ - reject: Reject new tasks while one is in progress
+ - rollback: Cancel current task and start new one
+ - interrupt: Interrupt current task and start new one
+ - enqueue: Queue new tasks to run after current one
+"""
+
+OnConflictBehavior = typing.Literal["raise", "do_nothing"]
+"""Behavior when encountering conflicts.
+
+Values:
+ - raise: Raise an exception on conflict
+ - do_nothing: Silently ignore conflicts
+"""
+
+IfNotExists = typing.Literal["create", "reject"]
+"""Behavior when an entity doesn't exist.
+
+Values:
+ - create: Create the entity
+ - reject: Reject the operation
+"""
+
+FilterType = (
+ dict[
+ str,
+ str
+ | dict[typing.Literal["$eq", "$contains"], str]
+ | dict[typing.Literal["$contains"], list[str]],
+ ]
+ | dict[str, str]
+)
+"""Response type for authorization handlers.
+
+Supports exact matches and operators:
+ - Exact match shorthand: {"field": "value"}
+ - Exact match: {"field": {"$eq": "value"}}
+ - Contains (membership): {"field": {"$contains": "value"}}
+ - Contains (subset containment): {"field": {"$contains": ["value1", "value2"]}}
+
+Subset containment is only supported by newer versions of the LangGraph dev server;
+install langgraph-runtime-inmem >= 0.14.1 to use this filter variant.
+
+???+ example "Examples"
+
+ Simple exact match filter for the resource owner:
+
+ ```python
+ filter = {"owner": "user-abcd123"}
+ ```
+
+ Explicit version of the exact match filter:
+
+ ```python
+ filter = {"owner": {"$eq": "user-abcd123"}}
+ ```
+
+ Containment (membership of a single element):
+
+ ```python
+ filter = {"participants": {"$contains": "user-abcd123"}}
+ ```
+
+ Containment (subset containment; all values must be present, but order doesn't matter):
+
+ ```python
+ filter = {"participants": {"$contains": ["user-abcd123", "user-efgh456"]}}
+ ```
+
+ Combining filters (treated as a logical `AND`):
+
+ ```python
+ filter = {"owner": "user-abcd123", "participants": {"$contains": "user-efgh456"}}
+ ```
+"""
+
+ThreadStatus = typing.Literal["idle", "busy", "interrupted", "error"]
+"""Status of a thread.
+
+Values:
+ - idle: Thread is available for work
+ - busy: Thread is currently processing
+ - interrupted: Thread was interrupted
+ - error: Thread encountered an error
+"""
+
+MetadataInput = dict[str, typing.Any]
+"""Type for arbitrary metadata attached to entities.
+
+Allows storing custom key-value pairs with any entity.
+Keys must be strings, values can be any JSON-serializable type.
+
+???+ example "Examples"
+
+ ```python
+ metadata = {
+ "created_by": "user123",
+ "priority": 1,
+ "tags": ["important", "urgent"]
+ }
+ ```
+"""
+
+HandlerResult = None | bool | FilterType
+"""The result of a handler can be:
+ * None | True: accept the request.
+ * False: reject the request with a 403 error
+ * FilterType: filter to apply
+"""
+
+Handler = Callable[..., Awaitable[HandlerResult]]
+
+T = typing.TypeVar("T")
+
+
+@typing.runtime_checkable
+class MinimalUser(typing.Protocol):
+ """User objects must at least expose the identity property."""
+
+ @property
+ def identity(self) -> str:
+ """The unique identifier for the user.
+
+ This could be a username, email, or any other unique identifier used
+ to distinguish between different users in the system.
+ """
+ ...
+
+
+class MinimalUserDict(typing.TypedDict, total=False):
+ """The dictionary representation of a user."""
+
+ identity: typing_extensions.Required[str]
+ """The required unique identifier for the user."""
+ display_name: str
+ """The typing.Optional display name for the user."""
+ is_authenticated: bool
+ """Whether the user is authenticated. Defaults to True."""
+ permissions: Sequence[str]
+ """A list of permissions associated with the user.
+
+ You can use these in your `@auth.on` authorization logic to determine
+ access permissions to different resources.
+ """
+
+
+@typing.runtime_checkable
+class BaseUser(typing.Protocol):
+ """The base ASGI user protocol"""
+
+ @property
+ def is_authenticated(self) -> bool:
+ """Whether the user is authenticated."""
+ ...
+
+ @property
+ def display_name(self) -> str:
+ """The display name of the user."""
+ ...
+
+ @property
+ def identity(self) -> str:
+ """The unique identifier for the user."""
+ ...
+
+ @property
+ def permissions(self) -> Sequence[str]:
+ """The permissions associated with the user."""
+ ...
+
+ def __getitem__(self, key):
+ """Get a key from your minimal user dict."""
+ ...
+
+ def __contains__(self, key):
+ """Check if a property exists."""
+ ...
+
+ def __iter__(self):
+ """Iterate over the keys of the user."""
+ ...
+
+
+class StudioUser:
+ """A user object that's populated from authenticated requests from the LangGraph studio.
+
+ Note: Studio auth can be disabled in your `langgraph.json` config.
+
+ ```json
+ {
+ "auth": {
+ "disable_studio_auth": true
+ }
+ }
+ ```
+
+ You can use `isinstance` checks in your authorization handlers (`@auth.on`) to control access specifically
+ for developers accessing the instance from the LangGraph Studio UI.
+
+ ???+ example "Examples"
+
+ Use `@auth.on` to deny by default, but allow Studio users through:
+
+ ```python
+ @auth.on
+ async def deny_all_except_studio(ctx: Auth.types.AuthContext, value: Any) -> bool:
+ # Allow Studio users, deny everyone else by default
+ if isinstance(ctx.user, Auth.types.StudioUser):
+ return True
+ return False
+
+ # Then add specific handlers to allow access for non-Studio users
+ @auth.on.threads
+ async def allow_thread_access(ctx: Auth.types.AuthContext, value: Any) -> Auth.types.FilterType:
+ return {"owner": ctx.user.identity}
+ ```
+ """
+
+ __slots__ = ("_is_authenticated", "_permissions", "username")
+
+ def __init__(self, username: str, is_authenticated: bool = False) -> None:
+ self.username = username
+ self._is_authenticated = is_authenticated
+ self._permissions = ["authenticated"] if is_authenticated else []
+
+ @property
+ def is_authenticated(self) -> bool:
+ return self._is_authenticated
+
+ @property
+ def display_name(self) -> str:
+ return self.username
+
+ @property
+ def identity(self) -> str:
+ return self.username
+
+ @property
+ def permissions(self) -> Sequence[str]:
+ return self._permissions
+
+
+Authenticator = Callable[
+ ...,
+ Awaitable[
+ MinimalUser
+ | str
+ | BaseUser
+ | MinimalUserDict
+ | typing.Mapping[str, typing.Any],
+ ],
+]
+"""Type for authentication functions.
+
+An authenticator can return either:
+1. A string (user_id)
+2. A dict containing {"identity": str, "permissions": list[str]}
+3. An object with identity and permissions properties
+
+Permissions can be used downstream by your authorization logic to determine
+access permissions to different resources.
+
+The authenticate decorator will automatically inject any of the following parameters
+by name if they are included in your function signature:
+
+Parameters:
+ request (Request): The raw ASGI request object
+ body (dict): The parsed request body
+ path (str): The request path
+ method (str): The HTTP method (GET, POST, etc.)
+ path_params (dict[str, str] | None): URL path parameters
+ query_params (dict[str, str] | None): URL query parameters
+ headers (dict[str, bytes] | None): Request headers
+ authorization (str | None): The Authorization header value (e.g. "Bearer ")
+
+???+ example "Examples"
+
+ Basic authentication with token:
+
+ ```python
+ from langgraph_sdk import Auth
+
+ auth = Auth()
+
+ @auth.authenticate
+ async def authenticate1(authorization: str) -> Auth.types.MinimalUserDict:
+ return await get_user(authorization)
+ ```
+
+ Authentication with multiple parameters:
+
+ ```
+ @auth.authenticate
+ async def authenticate2(
+ method: str,
+ path: str,
+ headers: dict[str, bytes]
+ ) -> Auth.types.MinimalUserDict:
+ # Custom auth logic using method, path and headers
+ user = verify_request(method, path, headers)
+ return user
+ ```
+
+ Accepting the raw ASGI request:
+
+ ```python
+ MY_SECRET = "my-secret-key"
+ @auth.authenticate
+ async def get_current_user(request: Request) -> Auth.types.MinimalUserDict:
+ try:
+ token = (request.headers.get("authorization") or "").split(" ", 1)[1]
+ payload = jwt.decode(token, MY_SECRET, algorithms=["HS256"])
+ except (IndexError, InvalidTokenError):
+ raise HTTPException(
+ status_code=401,
+ detail="Invalid token",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+
+ async with httpx.AsyncClient() as client:
+ response = await client.get(
+ f"https://api.myauth-provider.com/auth/v1/user",
+ headers={"Authorization": f"Bearer {MY_SECRET}"}
+ )
+ if response.status_code != 200:
+ raise HTTPException(status_code=401, detail="User not found")
+
+ user_data = response.json()
+ return {
+ "identity": user_data["id"],
+ "display_name": user_data.get("name"),
+ "permissions": user_data.get("permissions", []),
+ "is_authenticated": True,
+ }
+ ```
+"""
+
+
+@dataclass(slots=True)
+class BaseAuthContext:
+ """Base class for authentication context.
+
+ Provides the fundamental authentication information needed for
+ authorization decisions.
+ """
+
+ permissions: Sequence[str]
+ """The permissions granted to the authenticated user."""
+
+ user: BaseUser
+ """The authenticated user."""
+
+
+@typing.final
+@dataclass(slots=True)
+class AuthContext(BaseAuthContext):
+ """Complete authentication context with resource and action information.
+
+ Extends BaseAuthContext with specific resource and action being accessed,
+ allowing for fine-grained access control decisions.
+ """
+
+ resource: typing.Literal["runs", "threads", "crons", "assistants", "store"]
+ """The resource being accessed."""
+
+ action: typing.Literal[
+ "create",
+ "read",
+ "update",
+ "delete",
+ "search",
+ "create_run",
+ "put",
+ "get",
+ "list_namespaces",
+ ]
+ """The action being performed on the resource.
+
+ Most resources support the following actions:
+ - create: Create a new resource
+ - read: Read information about a resource
+ - update: Update an existing resource
+ - delete: Delete a resource
+ - search: Search for resources
+
+ The store supports the following actions:
+ - put: Add or update an item in the store
+ - get: Get an item from the store
+ - search: Search for items within a namespace prefix
+ - delete: Delete an item from the store
+ - list_namespaces: List the namespaces in the store
+ """
+
+
+class ThreadTTL(typing.TypedDict, total=False):
+ """Time-to-live configuration for a thread.
+
+ Matches the OpenAPI schema where TTL is represented as an object with
+ an optional strategy and a time value in minutes.
+ """
+
+ strategy: typing.Literal["delete"]
+ """TTL strategy. Currently only 'delete' is supported."""
+
+ ttl: int
+ """Time-to-live in minutes from now until the thread should be swept."""
+
+
+class ThreadsCreate(typing.TypedDict, total=False):
+ """Parameters for creating a new thread.
+
+ ???+ example "Examples"
+
+ ```python
+ create_params = {
+ "thread_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
+ "metadata": {"owner": "user123"},
+ "if_exists": "do_nothing"
+ }
+ ```
+ """
+
+ thread_id: UUID
+ """Unique identifier for the thread."""
+
+ metadata: MetadataInput
+ """typing.Optional metadata to attach to the thread."""
+
+ if_exists: OnConflictBehavior
+ """Behavior when a thread with the same ID already exists."""
+
+ ttl: ThreadTTL
+ """Optional TTL configuration for the thread."""
+
+
+class ThreadsRead(typing.TypedDict, total=False):
+ """Parameters for reading thread state or run information.
+
+ This type is used in three contexts:
+ 1. Reading thread, thread version, or thread state information: Only thread_id is provided
+ 2. Reading run information: Both thread_id and run_id are provided
+ """
+
+ thread_id: UUID
+ """Unique identifier for the thread."""
+
+ run_id: UUID | None
+ """Run ID to filter by. Only used when reading run information within a thread."""
+
+
+class ThreadsUpdate(typing.TypedDict, total=False):
+ """Parameters for updating a thread or run.
+
+ Called for updates to a thread, thread version, or run
+ cancellation.
+ """
+
+ thread_id: UUID
+ """Unique identifier for the thread."""
+
+ metadata: MetadataInput
+ """typing.Optional metadata to update."""
+
+ action: typing.Literal["interrupt", "rollback"] | None
+ """typing.Optional action to perform on the thread."""
+
+
+class ThreadsDelete(typing.TypedDict, total=False):
+ """Parameters for deleting a thread.
+
+ Called for deletes to a thread, thread version, or run
+ """
+
+ thread_id: UUID
+ """Unique identifier for the thread."""
+
+ run_id: UUID | None
+ """typing.Optional run ID to filter by."""
+
+
+class ThreadsSearch(typing.TypedDict, total=False):
+ """Parameters for searching threads.
+
+ Called for searches to threads or runs.
+ """
+
+ metadata: MetadataInput
+ """typing.Optional metadata to filter by."""
+
+ values: MetadataInput
+ """typing.Optional values to filter by."""
+
+ status: ThreadStatus | None
+ """typing.Optional status to filter by."""
+
+ limit: int
+ """Maximum number of results to return."""
+
+ offset: int
+ """Offset for pagination."""
+
+ ids: Sequence[UUID] | None
+ """typing.Optional list of thread IDs to filter by."""
+
+ thread_id: UUID | None
+ """typing.Optional thread ID to filter by."""
+
+
+class RunsCreate(typing.TypedDict, total=False):
+ """Payload for creating a run.
+
+ ???+ example "Examples"
+
+ ```python
+ create_params = {
+ "assistant_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
+ "thread_id": UUID("123e4567-e89b-12d3-a456-426614174001"),
+ "run_id": UUID("123e4567-e89b-12d3-a456-426614174002"),
+ "status": "pending",
+ "metadata": {"owner": "user123"},
+ "prevent_insert_if_inflight": True,
+ "multitask_strategy": "reject",
+ "if_not_exists": "create",
+ "after_seconds": 10,
+ "kwargs": {"key": "value"},
+ "action": "interrupt"
+ }
+ ```
+ """
+
+ assistant_id: UUID | None
+ """typing.Optional assistant ID to use for this run."""
+
+ thread_id: UUID | None
+ """typing.Optional thread ID to use for this run."""
+
+ run_id: UUID | None
+ """typing.Optional run ID to use for this run."""
+
+ status: RunStatus | None
+ """typing.Optional status for this run."""
+
+ metadata: MetadataInput
+ """typing.Optional metadata for the run."""
+
+ prevent_insert_if_inflight: bool
+ """Prevent inserting a new run if one is already in flight."""
+
+ multitask_strategy: MultitaskStrategy
+ """Multitask strategy for this run."""
+
+ if_not_exists: IfNotExists
+ """IfNotExists for this run."""
+
+ after_seconds: int
+ """Number of seconds to wait before creating the run."""
+
+ kwargs: dict[str, typing.Any]
+ """Keyword arguments to pass to the run."""
+
+ action: typing.Literal["interrupt", "rollback"] | None
+ """Action to take if updating an existing run."""
+
+
+class AssistantsCreate(typing.TypedDict, total=False):
+ """Payload for creating an assistant.
+
+ ???+ example "Examples"
+
+ ```python
+ create_params = {
+ "assistant_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
+ "graph_id": "graph123",
+ "config": {"tags": ["tag1", "tag2"]},
+ "context": {"key": "value"},
+ "metadata": {"owner": "user123"},
+ "if_exists": "do_nothing",
+ "name": "Assistant 1"
+ }
+ ```
+ """
+
+ assistant_id: UUID
+ """Unique identifier for the assistant."""
+
+ graph_id: str
+ """Graph ID to use for this assistant."""
+
+ config: dict[str, typing.Any]
+ """typing.Optional configuration for the assistant."""
+
+ context: dict[str, typing.Any]
+
+ metadata: MetadataInput
+ """typing.Optional metadata to attach to the assistant."""
+
+ if_exists: OnConflictBehavior
+ """Behavior when an assistant with the same ID already exists."""
+
+ name: str
+ """Name of the assistant."""
+
+
+class AssistantsRead(typing.TypedDict, total=False):
+ """Payload for reading an assistant.
+
+ ???+ example "Examples"
+
+ ```python
+ read_params = {
+ "assistant_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
+ "metadata": {"owner": "user123"}
+ }
+ ```
+ """
+
+ assistant_id: UUID
+ """Unique identifier for the assistant."""
+
+ metadata: MetadataInput
+ """typing.Optional metadata to filter by."""
+
+
+class AssistantsUpdate(typing.TypedDict, total=False):
+ """Payload for updating an assistant.
+
+ ???+ example "Examples"
+
+ ```python
+ update_params = {
+ "assistant_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
+ "graph_id": "graph123",
+ "config": {"tags": ["tag1", "tag2"]},
+ "context": {"key": "value"},
+ "metadata": {"owner": "user123"},
+ "name": "Assistant 1",
+ "version": 1
+ }
+ ```
+ """
+
+ assistant_id: UUID
+ """Unique identifier for the assistant."""
+
+ graph_id: str | None
+ """typing.Optional graph ID to update."""
+
+ config: dict[str, typing.Any]
+ """typing.Optional configuration to update."""
+
+ context: dict[str, typing.Any]
+ """The static context of the assistant."""
+
+ metadata: MetadataInput
+ """typing.Optional metadata to update."""
+
+ name: str | None
+ """typing.Optional name to update."""
+
+ version: int | None
+ """typing.Optional version to update."""
+
+
+class AssistantsDelete(typing.TypedDict):
+ """Payload for deleting an assistant.
+
+ ???+ example "Examples"
+
+ ```python
+ delete_params = {
+ "assistant_id": UUID("123e4567-e89b-12d3-a456-426614174000")
+ }
+ ```
+ """
+
+ assistant_id: UUID
+ """Unique identifier for the assistant."""
+
+
+class AssistantsSearch(typing.TypedDict):
+ """Payload for searching assistants.
+
+ ???+ example "Examples"
+
+ ```python
+ search_params = {
+ "graph_id": "graph123",
+ "metadata": {"owner": "user123"},
+ "limit": 10,
+ "offset": 0
+ }
+ ```
+ """
+
+ graph_id: str | None
+ """typing.Optional graph ID to filter by."""
+
+ metadata: MetadataInput
+ """typing.Optional metadata to filter by."""
+
+ limit: int
+ """Maximum number of results to return."""
+
+ offset: int
+ """Offset for pagination."""
+
+
+class CronsCreate(typing.TypedDict, total=False):
+ """Payload for creating a cron job.
+
+ ???+ example "Examples"
+
+ ```python
+ create_params = {
+ "payload": {"key": "value"},
+ "schedule": "0 0 * * *",
+ "cron_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
+ "thread_id": UUID("123e4567-e89b-12d3-a456-426614174001"),
+ "user_id": "user123",
+ "end_time": datetime(2024, 3, 16, 10, 0, 0)
+ }
+ ```
+ """
+
+ payload: dict[str, typing.Any]
+ """Payload for the cron job."""
+
+ schedule: str
+ """Schedule for the cron job."""
+
+ cron_id: UUID | None
+ """typing.Optional unique identifier for the cron job."""
+
+ thread_id: UUID | None
+ """typing.Optional thread ID to use for this cron job."""
+
+ user_id: str | None
+ """typing.Optional user ID to use for this cron job."""
+
+ end_time: datetime | None
+ """typing.Optional end time for the cron job."""
+
+
+class CronsDelete(typing.TypedDict):
+ """Payload for deleting a cron job.
+
+ ???+ example "Examples"
+
+ ```python
+ delete_params = {
+ "cron_id": UUID("123e4567-e89b-12d3-a456-426614174000")
+ }
+ ```
+ """
+
+ cron_id: UUID
+ """Unique identifier for the cron job."""
+
+
+class CronsRead(typing.TypedDict):
+ """Payload for reading a cron job.
+
+ ???+ example "Examples"
+
+ ```python
+ read_params = {
+ "cron_id": UUID("123e4567-e89b-12d3-a456-426614174000")
+ }
+ ```
+ """
+
+ cron_id: UUID
+ """Unique identifier for the cron job."""
+
+
+class CronsUpdate(typing.TypedDict, total=False):
+ """Payload for updating a cron job.
+
+ ???+ example "Examples"
+
+ ```python
+ update_params = {
+ "cron_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
+ "payload": {"key": "value"},
+ "schedule": "0 0 * * *"
+ }
+ ```
+ """
+
+ cron_id: UUID
+ """Unique identifier for the cron job."""
+
+ payload: dict[str, typing.Any] | None
+ """typing.Optional payload to update."""
+
+ schedule: str | None
+ """typing.Optional schedule to update."""
+
+
+class CronsSearch(typing.TypedDict, total=False):
+ """Payload for searching cron jobs.
+
+ ???+ example "Examples"
+
+ ```python
+ search_params = {
+ "assistant_id": UUID("123e4567-e89b-12d3-a456-426614174000"),
+ "thread_id": UUID("123e4567-e89b-12d3-a456-426614174001"),
+ "limit": 10,
+ "offset": 0
+ }
+ ```
+ """
+
+ assistant_id: UUID | None
+ """typing.Optional assistant ID to filter by."""
+
+ thread_id: UUID | None
+ """typing.Optional thread ID to filter by."""
+
+ limit: int
+ """Maximum number of results to return."""
+
+ offset: int
+ """Offset for pagination."""
+
+
+class StoreGet(typing.TypedDict):
+ """Operation to retrieve a specific item by its namespace and key.
+
+ This dict is mutable — auth handlers can modify `namespace` to enforce
+ access scoping (e.g., prepending the user's identity).
+ """
+
+ namespace: tuple[str, ...]
+ """Hierarchical path that uniquely identifies the item's location.
+
+ Auth handlers can modify this to enforce per-user scoping.
+ """
+
+ key: str
+ """Unique identifier for the item within its specific namespace."""
+
+
+class StoreSearch(typing.TypedDict):
+ """Operation to search for items within a specified namespace hierarchy.
+
+ This dict is mutable — auth handlers can modify `namespace` to enforce
+ access scoping (e.g., prepending the user's identity).
+ """
+
+ namespace: tuple[str, ...]
+ """Prefix filter for defining the search scope.
+
+ Auth handlers can modify this to enforce per-user scoping.
+ """
+
+ filter: dict[str, typing.Any] | None
+ """Key-value pairs for filtering results based on exact matches or comparison operators."""
+
+ limit: int
+ """Maximum number of items to return in the search results."""
+
+ offset: int
+ """Number of matching items to skip for pagination."""
+
+ query: str | None
+ """Natural language search query for semantic search capabilities."""
+
+
+class StoreListNamespaces(typing.TypedDict):
+ """Operation to list and filter namespaces in the store.
+
+ This dict is mutable — auth handlers can modify `namespace` (the prefix)
+ to enforce access scoping (e.g., prepending the user's identity).
+ """
+
+ namespace: tuple[str, ...] | None
+ """Prefix filter for namespaces. Can be `None` if no prefix was provided.
+
+ Auth handlers can modify this to enforce per-user scoping. When `None`,
+ handlers should set it to `(user_id,)` to scope listing to the user's namespaces.
+ """
+
+ suffix: tuple[str, ...] | None
+ """Optional conditions for filtering namespaces."""
+
+ max_depth: int | None
+ """Maximum depth of namespace hierarchy to return.
+
+ Note:
+ Namespaces deeper than this level will be truncated.
+ """
+
+ limit: int
+ """Maximum number of namespaces to return."""
+
+ offset: int
+ """Number of namespaces to skip for pagination."""
+
+
+class StorePut(typing.TypedDict):
+ """Operation to store, update, or delete an item in the store.
+
+ This dict is mutable — auth handlers can modify `namespace` to enforce
+ access scoping (e.g., prepending the user's identity).
+ """
+
+ namespace: tuple[str, ...]
+ """Hierarchical path that identifies the location of the item.
+
+ Auth handlers can modify this to enforce per-user scoping.
+ """
+
+ key: str
+ """Unique identifier for the item within its namespace."""
+
+ value: dict[str, typing.Any] | None
+ """The data to store, or `None` to mark the item for deletion."""
+
+ index: typing.Literal[False] | list[str] | None
+ """Optional index configuration for full-text search."""
+
+
+class StoreDelete(typing.TypedDict):
+ """Operation to delete an item from the store.
+
+ This dict is mutable — auth handlers can modify `namespace` to enforce
+ access scoping (e.g., prepending the user's identity).
+ """
+
+ namespace: tuple[str, ...]
+ """Hierarchical path that uniquely identifies the item's location.
+
+ Auth handlers can modify this to enforce per-user scoping.
+ """
+
+ key: str
+ """Unique identifier for the item within its specific namespace."""
+
+
+class on:
+ """Namespace for type definitions of different API operations.
+
+ This class organizes type definitions for create, read, update, delete,
+ and search operations across different resources (threads, assistants, crons).
+
+ ???+ note "Usage"
+ Start by denying all requests by default, then add handlers to allow access:
+
+ ```python
+ from langgraph_sdk import Auth
+
+ auth = Auth()
+
+ # Default deny: reject all requests without a specific handler
+ @auth.on
+ async def deny_all(ctx: Auth.types.AuthContext, value: Auth.on.value):
+ return False
+
+ # Allow thread creation, stamping the owner
+ @auth.on.threads.create
+ async def allow_thread_create(ctx: Auth.types.AuthContext, value: Auth.on.threads.create.value):
+ value.setdefault("metadata", {})["owner"] = ctx.user.identity
+
+ # Allow assistant search, scoped to user's resources
+ @auth.on.assistants.search
+ async def allow_assistant_search(ctx: Auth.types.AuthContext, value: Auth.on.assistants.search.value):
+ return {"owner": ctx.user.identity}
+ ```
+ """
+
+ value = dict[str, typing.Any]
+
+ class threads:
+ """Types for thread-related operations."""
+
+ value = (
+ ThreadsCreate | ThreadsRead | ThreadsUpdate | ThreadsDelete | ThreadsSearch
+ )
+
+ class create:
+ """Type for thread creation parameters."""
+
+ value = ThreadsCreate
+
+ class create_run:
+ """Type for creating or streaming a run."""
+
+ value = RunsCreate
+
+ class read:
+ """Type for thread read parameters."""
+
+ value = ThreadsRead
+
+ class update:
+ """Type for thread update parameters."""
+
+ value = ThreadsUpdate
+
+ class delete:
+ """Type for thread deletion parameters."""
+
+ value = ThreadsDelete
+
+ class search:
+ """Type for thread search parameters."""
+
+ value = ThreadsSearch
+
+ class assistants:
+ """Types for assistant-related operations."""
+
+ value = (
+ AssistantsCreate
+ | AssistantsRead
+ | AssistantsUpdate
+ | AssistantsDelete
+ | AssistantsSearch
+ )
+
+ class create:
+ """Type for assistant creation parameters."""
+
+ value = AssistantsCreate
+
+ class read:
+ """Type for assistant read parameters."""
+
+ value = AssistantsRead
+
+ class update:
+ """Type for assistant update parameters."""
+
+ value = AssistantsUpdate
+
+ class delete:
+ """Type for assistant deletion parameters."""
+
+ value = AssistantsDelete
+
+ class search:
+ """Type for assistant search parameters."""
+
+ value = AssistantsSearch
+
+ class crons:
+ """Types for cron-related operations."""
+
+ value = CronsCreate | CronsRead | CronsUpdate | CronsDelete | CronsSearch
+
+ class create:
+ """Type for cron creation parameters."""
+
+ value = CronsCreate
+
+ class read:
+ """Type for cron read parameters."""
+
+ value = CronsRead
+
+ class update:
+ """Type for cron update parameters."""
+
+ value = CronsUpdate
+
+ class delete:
+ """Type for cron deletion parameters."""
+
+ value = CronsDelete
+
+ class search:
+ """Type for cron search parameters."""
+
+ value = CronsSearch
+
+ class store:
+ """Types for store-related operations."""
+
+ value = StoreGet | StoreSearch | StoreListNamespaces | StorePut | StoreDelete
+
+ class put:
+ """Type for store put parameters."""
+
+ value = StorePut
+
+ class get:
+ """Type for store get parameters."""
+
+ value = StoreGet
+
+ class search:
+ """Type for store search parameters."""
+
+ value = StoreSearch
+
+ class delete:
+ """Type for store delete parameters."""
+
+ value = StoreDelete
+
+ class list_namespaces:
+ """Type for store list namespaces parameters."""
+
+ value = StoreListNamespaces
+
+
+__all__ = [
+ "AssistantsCreate",
+ "AssistantsDelete",
+ "AssistantsRead",
+ "AssistantsSearch",
+ "AssistantsUpdate",
+ "MetadataInput",
+ "RunsCreate",
+ "StoreDelete",
+ "StoreGet",
+ "StoreListNamespaces",
+ "StorePut",
+ "StoreSearch",
+ "ThreadsCreate",
+ "ThreadsDelete",
+ "ThreadsRead",
+ "ThreadsSearch",
+ "ThreadsUpdate",
+ "on",
+]
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/encryption/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/encryption/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..79611de059d28126b7a2c18d113443f1330347ca
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/encryption/__init__.py
@@ -0,0 +1,466 @@
+"""Custom encryption support for LangGraph.
+
+.. warning::
+ This API is in beta and may change in future versions.
+
+This module provides a framework for implementing custom at-rest encryption
+in LangGraph applications. Similar to the Auth system, it allows developers
+to define custom encryption and decryption handlers that are executed
+server-side.
+"""
+
+from __future__ import annotations
+
+import functools
+import inspect
+import typing
+import warnings
+
+from langgraph_sdk.encryption import types
+
+
+class LangGraphBetaWarning(UserWarning):
+ """Warning for beta features in LangGraph SDK."""
+
+
+@functools.lru_cache(maxsize=1)
+def _warn_encryption_beta() -> None:
+ warnings.warn(
+ "The Encryption API is in beta and may change in future versions.",
+ LangGraphBetaWarning,
+ stacklevel=4,
+ )
+
+
+class DuplicateHandlerError(Exception):
+ """Raised when attempting to register a duplicate encryption/decryption handler."""
+
+ pass
+
+
+def _validate_handler(fn: typing.Callable, handler_type: str) -> None:
+ """Validate that a handler function has the correct signature.
+
+ Args:
+ fn: The handler function to validate
+ handler_type: Description of the handler for error messages
+
+ Raises:
+ TypeError: If the handler is not an async function or has wrong parameter count
+ """
+ if not inspect.iscoroutinefunction(fn):
+ raise TypeError(f"{handler_type} must be an async function, got {type(fn)}")
+
+ sig = inspect.signature(fn)
+ params = [
+ p
+ for p in sig.parameters.values()
+ if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)
+ ]
+ if len(params) != 2:
+ raise TypeError(
+ f"{handler_type} must accept exactly 2 parameters "
+ f"(ctx, data), got {len(params)}"
+ )
+
+
+class _EncryptDecorators:
+ """Decorators for encryption handlers.
+
+ Provides @encryption.encrypt.blob and @encryption.encrypt.json decorators for
+ registering encryption functions.
+ """
+
+ def __init__(self, parent: Encryption):
+ self._parent = parent
+
+ def blob(self, fn: types.BlobEncryptor) -> types.BlobEncryptor:
+ """Register a blob encryption handler.
+
+ The handler will be called to encrypt opaque data like checkpoint blobs.
+
+ Example:
+ ```python
+ @encryption.encrypt.blob
+ async def encrypt_blob(ctx: EncryptionContext, blob: bytes) -> bytes:
+ # Encrypt the blob using your encryption service
+ return encrypted_blob
+ ```
+
+ Args:
+ fn: The encryption handler function
+
+ Returns:
+ The registered handler function
+
+ Raises:
+ DuplicateHandlerError: If blob encryptor already registered
+ TypeError: If handler has invalid signature
+ """
+ if self._parent._blob_encryptor is not None:
+ raise DuplicateHandlerError("Blob encryptor already registered")
+ _validate_handler(fn, "Blob encryptor")
+ self._parent._blob_encryptor = fn
+ return fn
+
+ def json(self, fn: types.JsonEncryptor) -> types.JsonEncryptor:
+ """Register the JSON encryption handler.
+
+ Example:
+ ```python
+ @encryption.encrypt.json
+ async def encrypt_json(ctx: EncryptionContext, data: dict) -> dict:
+ # Encrypt the data
+ return encrypt_data(data)
+ ```
+
+ Args:
+ fn: The encryption handler function
+
+ Returns:
+ The registered handler function
+
+ Raises:
+ DuplicateHandlerError: If JSON encryptor already registered
+ TypeError: If handler has invalid signature
+ """
+ if self._parent._json_encryptor is not None:
+ raise DuplicateHandlerError("JSON encryptor already registered")
+ _validate_handler(fn, "JSON encryptor")
+ self._parent._json_encryptor = fn
+ return fn
+
+
+class _DecryptDecorators:
+ """Decorators for decryption handlers.
+
+ Provides @encryption.decrypt.blob and @encryption.decrypt.json decorators for
+ registering decryption functions.
+ """
+
+ def __init__(self, parent: Encryption):
+ self._parent = parent
+
+ def blob(self, fn: types.BlobDecryptor) -> types.BlobDecryptor:
+ """Register a blob decryption handler.
+
+ The handler will be called to decrypt opaque data like checkpoint blobs.
+
+ Example:
+ ```python
+ @encryption.decrypt.blob
+ async def decrypt_blob(ctx: EncryptionContext, blob: bytes) -> bytes:
+ # Decrypt the blob using your encryption service
+ return decrypted_blob
+ ```
+
+ Args:
+ fn: The decryption handler function
+
+ Returns:
+ The registered handler function
+
+ Raises:
+ DuplicateHandlerError: If blob decryptor already registered
+ TypeError: If handler has invalid signature
+ """
+ if self._parent._blob_decryptor is not None:
+ raise DuplicateHandlerError("Blob decryptor already registered")
+ _validate_handler(fn, "Blob decryptor")
+ self._parent._blob_decryptor = fn
+ return fn
+
+ def json(self, fn: types.JsonDecryptor) -> types.JsonDecryptor:
+ """Register the JSON decryption handler.
+
+ Example:
+ ```python
+ @encryption.decrypt.json
+ async def decrypt_json(ctx: EncryptionContext, data: dict) -> dict:
+ # Decrypt the data
+ return decrypt_data(data)
+ ```
+
+ Args:
+ fn: The decryption handler function
+
+ Returns:
+ The registered handler function
+
+ Raises:
+ DuplicateHandlerError: If JSON decryptor already registered
+ TypeError: If handler has invalid signature
+ """
+ if self._parent._json_decryptor is not None:
+ raise DuplicateHandlerError("JSON decryptor already registered")
+ _validate_handler(fn, "JSON decryptor")
+ self._parent._json_decryptor = fn
+ return fn
+
+
+class Encryption:
+ """Add custom at-rest encryption to your LangGraph application.
+
+ .. warning::
+ This API is in beta and may change in future versions.
+
+ The Encryption class provides a system for implementing custom encryption
+ of data at rest in LangGraph applications. It supports encryption of
+ both opaque blobs (like checkpoints) and structured JSON data (like
+ metadata, context, kwargs, values, etc.).
+
+ To use, create a separate Python file and add the path to the file to your
+ LangGraph API configuration file (`langgraph.json`). Within that file, create
+ an instance of the Encryption class and register encryption and decryption
+ handlers as needed.
+
+ Example `langgraph.json` file:
+
+ ```json
+ {
+ "dependencies": ["."],
+ "graphs": {
+ "agent": "./my_agent/agent.py:graph"
+ },
+ "env": ".env",
+ "encryption": {
+ "path": "./encryption.py:my_encryption"
+ }
+ }
+ ```
+
+ Then the LangGraph server will load your encryption file and use it to
+ encrypt/decrypt data at rest.
+
+ !!! warning "JSON Encryptors Must Preserve Keys"
+
+ JSON encryptors **must not add or remove keys** from the input dict.
+ Only values may be transformed. This constraint is **enforced at runtime
+ by the server** and exists because SQL JSONB merge operations (used for
+ partial updates) work at the key level.
+
+ **Correct (per-key encryption):**
+ ```python
+ # Input: {"secret": "value", "plain": "x"}
+ # Output: {"secret": "", "plain": "x"} ✓ Keys preserved
+ ```
+
+ **Incorrect (key consolidation):**
+ ```python
+ # Input: {"secret": "value", "plain": "x"}
+ # Output: {"__encrypted__": "", "plain": "x"} ✗ Key changed
+ ```
+
+ If your encryptor needs to store auxiliary data (DEK, IV, etc.), embed it
+ within the encrypted value itself, not as separate keys.
+
+ ???+ example "Basic Usage"
+
+ ```python
+ from langgraph_sdk import Encryption, EncryptionContext
+
+ my_encryption = Encryption()
+
+ SKIP_FIELDS = {"tenant_id", "owner", "thread_id", "assistant_id"}
+ ENCRYPTED_PREFIX = "encrypted:"
+
+ @my_encryption.encrypt.blob
+ async def encrypt_blob(ctx: EncryptionContext, blob: bytes) -> bytes:
+ return your_encrypt_bytes(blob)
+
+ @my_encryption.decrypt.blob
+ async def decrypt_blob(ctx: EncryptionContext, blob: bytes) -> bytes:
+ return your_decrypt_bytes(blob)
+
+ @my_encryption.encrypt.json
+ async def encrypt_json(ctx: EncryptionContext, data: dict) -> dict:
+ result = {}
+ for k, v in data.items():
+ if k in SKIP_FIELDS or v is None:
+ result[k] = v
+ else:
+ result[k] = ENCRYPTED_PREFIX + your_encrypt_string(v)
+ return result
+
+ @my_encryption.decrypt.json
+ async def decrypt_json(ctx: EncryptionContext, data: dict) -> dict:
+ result = {}
+ for k, v in data.items():
+ if isinstance(v, str) and v.startswith(ENCRYPTED_PREFIX):
+ result[k] = your_decrypt_string(v[len(ENCRYPTED_PREFIX):])
+ else:
+ result[k] = v
+ return result
+ ```
+
+ ???+ example "Field-Specific Logic"
+
+ The `ctx.model` and `ctx.field` attributes tell you which model type and
+ specific field is being encrypted, allowing different logic:
+
+ ```python
+ @my_encryption.encrypt.json
+ async def encrypt_json(ctx: EncryptionContext, data: dict) -> dict:
+ if ctx.field == "metadata":
+ # Metadata - standard encryption
+ return encrypt_standard(data)
+ elif ctx.field == "values":
+ # Thread values - more sensitive, use stronger encryption
+ return encrypt_sensitive(data)
+ else:
+ return encrypt_standard(data)
+ ```
+
+ !!! warning "Model/Field May Differ Between Encrypt and Decrypt"
+
+ Data encrypted with one `(model, field)` pair is **not guaranteed**
+ to be decrypted with the same pair. The server performs SQL JSONB
+ merges that can move encrypted values between models (e.g., cron
+ metadata → run metadata). Your decryption logic must handle data
+ regardless of the `ctx.model` or `ctx.field` values at decrypt time.
+
+ **Safe:** Use `ctx.model`/`ctx.field` for logging or metrics only.
+
+ **Safe:** Encrypt different keys based on `ctx.field`, but use a
+ single decrypt handler that decrypts any value with the encrypted
+ prefix (and passes through plaintext unchanged):
+
+ ```python
+ ENCRYPTED_PREFIX = "enc:"
+
+ @my_encryption.encrypt.json
+ async def encrypt_json(ctx: EncryptionContext, data: dict) -> dict:
+ # Encrypt different keys depending on the field
+ if ctx.field == "context":
+ keys_to_encrypt = {"api_key", "secret_token"}
+ else:
+ keys_to_encrypt = {"email", "ssn"}
+ return {
+ k: ENCRYPTED_PREFIX + encrypt(v) if k in keys_to_encrypt else v
+ for k, v in data.items()
+ }
+
+ @my_encryption.decrypt.json
+ async def decrypt_json(ctx: EncryptionContext, data: dict) -> dict:
+ # Decrypt ANY value with the prefix, regardless of model/field
+ return {
+ k: decrypt(v[len(ENCRYPTED_PREFIX):])
+ if isinstance(v, str) and v.startswith(ENCRYPTED_PREFIX)
+ else v
+ for k, v in data.items()
+ }
+ ```
+
+ **Unsafe:** Using different encryption keys or algorithms based on
+ `ctx.model`/`ctx.field` will cause decryption failures.
+ """
+
+ __slots__ = (
+ "_blob_decryptor",
+ "_blob_encryptor",
+ "_context_handler",
+ "_json_decryptor",
+ "_json_encryptor",
+ "decrypt",
+ "encrypt",
+ )
+
+ types = types
+ """Reference to encryption type definitions.
+
+ Provides access to all type definitions used in the encryption system,
+ including EncryptionContext, BlobEncryptor, BlobDecryptor,
+ JsonEncryptor, and JsonDecryptor.
+ """
+
+ def __init__(self) -> None:
+ """Initialize the Encryption instance."""
+ _warn_encryption_beta()
+ self.encrypt = _EncryptDecorators(self)
+ self.decrypt = _DecryptDecorators(self)
+ self._blob_encryptor: types.BlobEncryptor | None = None
+ self._blob_decryptor: types.BlobDecryptor | None = None
+ self._json_encryptor: types.JsonEncryptor | None = None
+ self._json_decryptor: types.JsonDecryptor | None = None
+ self._context_handler: types.ContextHandler | None = None
+
+ def context(self, fn: types.ContextHandler) -> types.ContextHandler:
+ """Register a context handler to derive encryption context from auth.
+
+ The handler receives the authenticated user and current EncryptionContext,
+ and returns a dict that becomes ctx.metadata for encrypt/decrypt handlers.
+
+ This allows encryption context to be derived from JWT claims or other
+ auth-derived data instead of requiring a separate X-Encryption-Context header.
+
+ Note: The context handler is called once per request in middleware,
+ so ctx.model and ctx.field will be None in the handler.
+
+ Example:
+ ```python
+ from langgraph_sdk import Encryption, EncryptionContext
+ from starlette.authentication import BaseUser
+
+ encryption = Encryption()
+
+ @encryption.context
+ async def get_context(user: BaseUser, ctx: EncryptionContext) -> dict:
+ # Derive encryption context from authenticated user
+ return {
+ **ctx.metadata, # preserve X-Encryption-Context header if present
+ "tenant_id": user.tenant_id,
+ }
+ ```
+
+ Args:
+ fn: The context handler function
+
+ Returns:
+ The registered handler function
+ """
+ self._context_handler = fn
+ return fn
+
+ def get_json_encryptor(
+ self,
+ _model: str | None = None, # kept for langgraph-api compat
+ ) -> types.JsonEncryptor | None:
+ """Get the JSON encryptor.
+
+ Args:
+ _model: Ignored. Kept for backwards compatibility with langgraph-api
+ which passes model_type to this method.
+
+ Returns:
+ The JSON encryptor, or None if not registered.
+ """
+ return self._json_encryptor
+
+ def get_json_decryptor(
+ self,
+ _model: str | None = None, # kept for langgraph-api compat
+ ) -> types.JsonDecryptor | None:
+ """Get the JSON decryptor.
+
+ Args:
+ _model: Ignored. Kept for backwards compatibility with langgraph-api
+ which passes model_type to this method.
+
+ Returns:
+ The JSON decryptor, or None if not registered.
+ """
+ return self._json_decryptor
+
+ def __repr__(self) -> str:
+ handlers = []
+ if self._blob_encryptor:
+ handlers.append("blob_encryptor")
+ if self._blob_decryptor:
+ handlers.append("blob_decryptor")
+ if self._json_encryptor:
+ handlers.append("json_encryptor")
+ if self._json_decryptor:
+ handlers.append("json_decryptor")
+ if self._context_handler:
+ handlers.append("context_handler")
+ return f"Encryption(handlers=[{', '.join(handlers)}])"
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/encryption/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/encryption/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c7e2037fc15f33c7b7e71c1200e12b0d63fa8b57
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/encryption/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/encryption/__pycache__/types.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/encryption/__pycache__/types.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..21d1e726537bc02f0d6a82077019ed7aa821fc5f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/encryption/__pycache__/types.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/encryption/types.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/encryption/types.py
new file mode 100644
index 0000000000000000000000000000000000000000..92e65a8c60f6908d58fe8efceb7b0f1d784a2cc9
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph_sdk/encryption/types.py
@@ -0,0 +1,147 @@
+"""Encryption and decryption types for LangGraph.
+
+This module defines the core types used for custom at-rest encryption
+in LangGraph. It includes context types and typed dictionaries for
+encryption operations.
+"""
+
+from __future__ import annotations
+
+import typing
+from collections.abc import Awaitable, Callable
+
+Json = dict[str, typing.Any]
+"""JSON-serializable dictionary type for structured data encryption."""
+
+
+class EncryptionContext:
+ """Context passed to encryption/decryption handlers.
+
+ Contains arbitrary non-secret key-values that will be stored on encrypt.
+ These key-values are intended to be sent to an external service that
+ manages keys and handles the actual encryption and decryption of data.
+
+ Attributes:
+ model: The model type being encrypted (e.g., "assistant", "thread", "run", "checkpoint")
+ field: The specific field being encrypted (e.g., "metadata", "context", "kwargs", "values")
+ metadata: Additional context metadata that can be used for encryption decisions
+ """
+
+ __slots__ = ("field", "metadata", "model")
+
+ def __init__(
+ self,
+ model: str | None = None,
+ metadata: dict[str, typing.Any] | None = None,
+ field: str | None = None,
+ ):
+ self.model = model
+ self.field = field
+ self.metadata = metadata or {}
+
+ def __repr__(self) -> str:
+ return f"EncryptionContext(model={self.model!r}, field={self.field!r}, metadata={self.metadata!r})"
+
+
+BlobEncryptor = Callable[[EncryptionContext, bytes], Awaitable[bytes]]
+"""Handler for encrypting opaque blob data like checkpoints.
+
+Note: Must be an async function. Encryption typically involves I/O operations
+(calling external KMS services), which should be async.
+
+Args:
+ ctx: Encryption context with model type and metadata
+ blob: The raw bytes to encrypt
+
+Returns:
+ Awaitable that resolves to encrypted bytes
+"""
+
+BlobDecryptor = Callable[[EncryptionContext, bytes], Awaitable[bytes]]
+"""Handler for decrypting opaque blob data like checkpoints.
+
+Note: Must be an async function. Decryption typically involves I/O operations
+(calling external KMS services), which should be async.
+
+Args:
+ ctx: Encryption context with model type and metadata
+ blob: The encrypted bytes to decrypt
+
+Returns:
+ Awaitable that resolves to decrypted bytes
+"""
+
+JsonEncryptor = Callable[[EncryptionContext, Json], Awaitable[Json]]
+"""Handler for encrypting structured JSON data.
+
+Note: Must be an async function. Encryption typically involves I/O operations
+(calling external KMS services), which should be async.
+
+Used for encrypting structured data like metadata, context, kwargs, values,
+and other JSON-serializable fields across different model types.
+
+Maps plaintext fields to encrypted fields. A practical approach:
+- Keep "owner" field unencrypted for search/filtering
+- Encrypt VALUES (not keys) for fields with specific prefix (e.g., "my.customer.org/")
+- Pass through all other fields unencrypted
+
+Example:
+ Input: {"owner": "user123", "my.customer.org/email": "john@example.com", "tenant_id": "t-456"}
+ Output: {"owner": "user123", "my.customer.org/email": "ENCRYPTED", "tenant_id": "t-456"}
+
+Note: Encrypted field VALUES cannot be reliably searched, as most real-world
+encryption implementations use nonces (non-deterministic encryption).
+Only unencrypted fields can be used in search queries.
+
+Args:
+ ctx: Encryption context with model type, field name, and metadata
+ data: The plaintext JSON dictionary
+
+Returns:
+ Awaitable that resolves to encrypted JSON dictionary
+"""
+
+JsonDecryptor = Callable[[EncryptionContext, Json], Awaitable[Json]]
+"""Handler for decrypting structured JSON data.
+
+Note: Must be an async function. Decryption typically involves I/O operations
+(calling external KMS services), which should be async.
+
+Inverse of JsonEncryptor. Must be able to decrypt data that
+was encrypted by the corresponding encryptor.
+
+Args:
+ ctx: Encryption context with model type, field name, and metadata
+ data: The encrypted JSON dictionary
+
+Returns:
+ Awaitable that resolves to decrypted JSON dictionary
+"""
+
+if typing.TYPE_CHECKING:
+ from starlette.authentication import BaseUser
+
+ContextHandler = Callable[
+ ["BaseUser", EncryptionContext], Awaitable[dict[str, typing.Any]]
+]
+"""Handler for deriving encryption context from authenticated user info.
+
+Note: Must be an async function as it may involve I/O operations.
+
+The context handler is called once per request in middleware (after auth),
+allowing encryption context to be derived from JWT claims, user properties,
+or other auth-derived data instead of requiring a separate X-Encryption-Context header.
+
+The return value becomes ctx.metadata for subsequent encrypt/decrypt operations
+and is persisted with encrypted data for later decryption.
+
+Note: ctx.model and ctx.field will be None in context handlers since
+the handler runs once per request before any specific model/field is known.
+
+Args:
+ user: The authenticated user (from Starlette's AuthenticationMiddleware)
+ ctx: Current encryption context with metadata from X-Encryption-Context header
+
+Returns:
+ Awaitable that resolves to dict that becomes the new ctx.metadata
+"""
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/lazy_loader-0.5.dist-info/licenses/LICENSE.md b/data/conda_envs/evalclaw/lib/python3.11/site-packages/lazy_loader-0.5.dist-info/licenses/LICENSE.md
new file mode 100644
index 0000000000000000000000000000000000000000..1008371325090268ee97059d9657ecdf41c3bba5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/lazy_loader-0.5.dist-info/licenses/LICENSE.md
@@ -0,0 +1,29 @@
+BSD 3-Clause License
+
+Copyright (c) 2022--2023, Scientific Python project
+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.
+
+3. Neither the name of the copyright holder 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 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.
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/msgpack-1.1.2.dist-info/licenses/COPYING b/data/conda_envs/evalclaw/lib/python3.11/site-packages/msgpack-1.1.2.dist-info/licenses/COPYING
new file mode 100644
index 0000000000000000000000000000000000000000..f067af3aae15a5b494f0eeb15a7064c176e30fd5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/msgpack-1.1.2.dist-info/licenses/COPYING
@@ -0,0 +1,14 @@
+Copyright (C) 2008-2011 INADA Naoki
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/multiprocess-0.70.19.dist-info/licenses/COPYING b/data/conda_envs/evalclaw/lib/python3.11/site-packages/multiprocess-0.70.19.dist-info/licenses/COPYING
new file mode 100644
index 0000000000000000000000000000000000000000..17f34bc3d8ae0889ae327ae0c16bf78870c41527
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/multiprocess-0.70.19.dist-info/licenses/COPYING
@@ -0,0 +1,28 @@
+Copyright (c) 2006-2008, R Oudkerk
+
+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.
+3. Neither the name of author nor the names of any contributors may be
+ used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/multiprocess-0.70.19.dist-info/licenses/LICENSE b/data/conda_envs/evalclaw/lib/python3.11/site-packages/multiprocess-0.70.19.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..444abd4a6b9d691fb95caf2e4c458860c0e623cf
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/multiprocess-0.70.19.dist-info/licenses/LICENSE
@@ -0,0 +1,38 @@
+Copyright (c) 2008-2016 California Institute of Technology.
+Copyright (c) 2016-2026 The Uncertainty Quantification Foundation.
+All rights reserved.
+
+This software forks the python package "multiprocessing". Licence and
+copyright information for multiprocessing can be found in "COPYING".
+
+This software is available subject to the conditions and terms laid
+out below. By downloading and using this software you are agreeing
+to the following conditions.
+
+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 names of the copyright holders nor the names of any of
+ the 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.
+
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pathlib_abc/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pathlib_abc/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..36614fbec311f689065e8fcd15971700a9326a7f
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pathlib_abc/__pycache__/__init__.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pathlib_abc/__pycache__/_fnmatch.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pathlib_abc/__pycache__/_fnmatch.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a83ce55ed3930be527caec431c114a4ae8a356c1
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pathlib_abc/__pycache__/_fnmatch.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pathlib_abc/__pycache__/_glob.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pathlib_abc/__pycache__/_glob.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a22bc5f490291ebf235c68968e441e626467da72
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pathlib_abc/__pycache__/_glob.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pathlib_abc/__pycache__/_os.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pathlib_abc/__pycache__/_os.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..936c98e0a5745c5c4b3a9b8b831313f2b5592749
Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pathlib_abc/__pycache__/_os.cpython-311.pyc differ
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/adapters/orc/adapter.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/adapters/orc/adapter.h
new file mode 100644
index 0000000000000000000000000000000000000000..4ffff81f355f1ddcdc19516746c61b8021477de4
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/adapters/orc/adapter.h
@@ -0,0 +1,323 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include
+#include
+#include
+
+#include "arrow/adapters/orc/options.h"
+#include "arrow/io/interfaces.h"
+#include "arrow/memory_pool.h"
+#include "arrow/record_batch.h"
+#include "arrow/status.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/util/macros.h"
+#include "arrow/util/visibility.h"
+
+namespace arrow {
+namespace adapters {
+namespace orc {
+
+/// \brief Information about an ORC stripe
+struct StripeInformation {
+ /// \brief Offset of the stripe from the start of the file, in bytes
+ int64_t offset;
+ /// \brief Length of the stripe, in bytes
+ int64_t length;
+ /// \brief Number of rows in the stripe
+ int64_t num_rows;
+ /// \brief Index of the first row of the stripe
+ int64_t first_row_id;
+};
+
+/// \class ORCFileReader
+/// \brief Read an Arrow Table or RecordBatch from an ORC file.
+class ARROW_EXPORT ORCFileReader {
+ public:
+ ~ORCFileReader();
+
+ /// \brief Creates a new ORC reader
+ ///
+ /// \param[in] file the data source
+ /// \param[in] pool a MemoryPool to use for buffer allocations
+ /// \return the returned reader object
+ static Result> Open(
+ const std::shared_ptr& file, MemoryPool* pool);
+
+ /// \brief Return the schema read from the ORC file
+ ///
+ /// \return the returned Schema object
+ Result> ReadSchema();
+
+ /// \brief Read the file as a Table
+ ///
+ /// The table will be composed of one record batch per stripe.
+ ///
+ /// \return the returned Table
+ Result> Read();
+
+ /// \brief Read the file as a Table
+ ///
+ /// The table will be composed of one record batch per stripe.
+ ///
+ /// \param[in] schema the Table schema
+ /// \return the returned Table
+ Result> Read(const std::shared_ptr& schema);
+
+ /// \brief Read the file as a Table
+ ///
+ /// The table will be composed of one record batch per stripe.
+ ///
+ /// \param[in] include_indices the selected field indices to read
+ /// \return the returned Table
+ Result> Read(const std::vector& include_indices);
+
+ /// \brief Read the file as a Table
+ ///
+ /// The table will be composed of one record batch per stripe.
+ ///
+ /// \param[in] include_names the selected field names to read
+ /// \return the returned Table
+ Result> Read(const std::vector& include_names);
+
+ /// \brief Read the file as a Table
+ ///
+ /// The table will be composed of one record batch per stripe.
+ ///
+ /// \param[in] schema the Table schema
+ /// \param[in] include_indices the selected field indices to read
+ /// \return the returned Table
+ Result> Read(const std::shared_ptr& schema,
+ const std::vector& include_indices);
+
+ /// \brief Read a single stripe as a RecordBatch
+ ///
+ /// \param[in] stripe the stripe index
+ /// \return the returned RecordBatch
+ Result> ReadStripe(int64_t stripe);
+
+ /// \brief Read a single stripe as a RecordBatch
+ ///
+ /// \param[in] stripe the stripe index
+ /// \param[in] include_indices the selected field indices to read
+ /// \return the returned RecordBatch
+ Result> ReadStripe(
+ int64_t stripe, const std::vector& include_indices);
+
+ /// \brief Read a single stripe as a RecordBatch
+ ///
+ /// \param[in] stripe the stripe index
+ /// \param[in] include_names the selected field names to read
+ /// \return the returned RecordBatch
+ Result> ReadStripe(
+ int64_t stripe, const std::vector& include_names);
+
+ /// \brief Seek to designated row. Invoke NextStripeReader() after seek
+ /// will return stripe reader starting from designated row.
+ ///
+ /// \param[in] row_number the rows number to seek
+ Status Seek(int64_t row_number);
+
+ /// \brief Get a stripe level record batch iterator.
+ ///
+ /// Each record batch will have up to `batch_size` rows.
+ /// NextStripeReader serves as a fine-grained alternative to ReadStripe
+ /// which may cause OOM issues by loading the whole stripe into memory.
+ ///
+ /// Note this will only read rows for the current stripe, not the entire
+ /// file.
+ ///
+ /// \param[in] batch_size the maximum number of rows in each record batch
+ /// \return the returned stripe reader
+ Result> NextStripeReader(int64_t batch_size);
+
+ /// \brief Get a stripe level record batch iterator.
+ ///
+ /// Each record batch will have up to `batch_size` rows.
+ /// NextStripeReader serves as a fine-grained alternative to ReadStripe
+ /// which may cause OOM issues by loading the whole stripe into memory.
+ ///
+ /// Note this will only read rows for the current stripe, not the entire
+ /// file.
+ ///
+ /// \param[in] batch_size the maximum number of rows in each record batch
+ /// \param[in] include_indices the selected field indices to read
+ /// \return the stripe reader
+ Result> NextStripeReader(
+ int64_t batch_size, const std::vector& include_indices);
+
+ /// \brief Get a record batch iterator for the entire file.
+ ///
+ /// Each record batch will have up to `batch_size` rows.
+ ///
+ /// \param[in] batch_size the maximum number of rows in each record batch
+ /// \param[in] include_names the selected field names to read, if not empty
+ /// (otherwise all fields are read)
+ /// \return the record batch iterator
+ Result> GetRecordBatchReader(
+ int64_t batch_size, const std::vector& include_names);
+
+ /// \brief The number of stripes in the file
+ int64_t NumberOfStripes();
+
+ /// \brief The number of rows in the file
+ int64_t NumberOfRows();
+
+ /// \brief StripeInformation for each stripe.
+ StripeInformation GetStripeInformation(int64_t stripe);
+
+ /// \brief Get the format version of the file.
+ /// Currently known values are 0.11 and 0.12.
+ ///
+ /// \return The FileVersion of the ORC file.
+ FileVersion GetFileVersion();
+
+ /// \brief Get the software instance and version that wrote this file.
+ ///
+ /// \return a user-facing string that specifies the software version
+ std::string GetSoftwareVersion();
+
+ /// \brief Get the compression kind of the file.
+ ///
+ /// \return The kind of compression in the ORC file.
+ Result GetCompression();
+
+ /// \brief Get the buffer size for the compression.
+ ///
+ /// \return Number of bytes to buffer for the compression codec.
+ int64_t GetCompressionSize();
+
+ /// \brief Get the number of rows per an entry in the row index.
+ /// \return the number of rows per an entry in the row index or 0 if there
+ /// is no row index.
+ int64_t GetRowIndexStride();
+
+ /// \brief Get ID of writer that generated the file.
+ ///
+ /// \return UNKNOWN_WRITER if the writer ID is undefined
+ WriterId GetWriterId();
+
+ /// \brief Get the writer id value when getWriterId() returns an unknown writer.
+ ///
+ /// \return the integer value of the writer ID.
+ int32_t GetWriterIdValue();
+
+ /// \brief Get the version of the writer.
+ ///
+ /// \return the version of the writer.
+
+ WriterVersion GetWriterVersion();
+
+ /// \brief Get the number of stripe statistics in the file.
+ ///
+ /// \return the number of stripe statistics
+ int64_t GetNumberOfStripeStatistics();
+
+ /// \brief Get the length of the data stripes in the file.
+ ///
+ /// \return return the number of bytes in stripes
+ int64_t GetContentLength();
+
+ /// \brief Get the length of the file stripe statistics.
+ ///
+ /// \return the number of compressed bytes in the file stripe statistics
+ int64_t GetStripeStatisticsLength();
+
+ /// \brief Get the length of the file footer.
+ ///
+ /// \return the number of compressed bytes in the file footer
+ int64_t GetFileFooterLength();
+
+ /// \brief Get the length of the file postscript.
+ ///
+ /// \return the number of bytes in the file postscript
+ int64_t GetFilePostscriptLength();
+
+ /// \brief Get the total length of the file.
+ ///
+ /// \return the number of bytes in the file
+ int64_t GetFileLength();
+
+ /// \brief Get the serialized file tail.
+ /// Useful if another reader of the same file wants to avoid re-reading
+ /// the file tail. See ReadOptions.SetSerializedFileTail().
+ ///
+ /// \return a string of bytes with the file tail
+ std::string GetSerializedFileTail();
+
+ /// \brief Return the metadata read from the ORC file
+ ///
+ /// \return A KeyValueMetadata object containing the ORC metadata
+ Result> ReadMetadata();
+
+ private:
+ class Impl;
+ std::unique_ptr impl_;
+ ORCFileReader();
+};
+
+/// \class ORCFileWriter
+/// \brief Write an Arrow Table or RecordBatch to an ORC file.
+class ARROW_EXPORT ORCFileWriter {
+ public:
+ ~ORCFileWriter();
+ /// \brief Creates a new ORC writer.
+ ///
+ /// \param[in] output_stream a pointer to the io::OutputStream to write into
+ /// \param[in] write_options the ORC writer options for Arrow
+ /// \return the returned writer object
+ static Result> Open(
+ io::OutputStream* output_stream,
+ const WriteOptions& write_options = WriteOptions());
+
+ /// \brief Write a table. This can be called multiple times.
+ ///
+ /// Tables passed in subsequent calls must match the schema of the table that was
+ /// written first.
+ ///
+ /// \param[in] table the Arrow table from which data is extracted.
+ /// \return Status
+ Status Write(const Table& table);
+
+ /// \brief Write a RecordBatch. This can be called multiple times.
+ ///
+ /// RecordBatches passed in subsequent calls must match the schema of the
+ /// RecordBatch that was written first.
+ ///
+ /// \param[in] record_batch the Arrow RecordBatch from which data is extracted.
+ /// \return Status
+ Status Write(const RecordBatch& record_batch);
+
+ /// \brief Close an ORC writer (orc::Writer)
+ ///
+ /// \return Status
+ Status Close();
+
+ private:
+ class Impl;
+ std::unique_ptr impl_;
+
+ private:
+ ORCFileWriter();
+};
+
+} // namespace orc
+} // namespace adapters
+} // namespace arrow
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/adapters/orc/options.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/adapters/orc/options.h
new file mode 100644
index 0000000000000000000000000000000000000000..3a300da678db98c24949203be7ab471a57502640
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/adapters/orc/options.h
@@ -0,0 +1,120 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include
+
+#include "arrow/io/interfaces.h"
+#include "arrow/status.h"
+#include "arrow/util/type_fwd.h"
+#include "arrow/util/visibility.h"
+
+namespace arrow {
+
+namespace adapters {
+
+namespace orc {
+
+enum class WriterId : int32_t {
+ kOrcJava = 0,
+ kOrcCpp = 1,
+ kPresto = 2,
+ kScritchleyGo = 3,
+ kTrino = 4,
+ kUnknown = INT32_MAX
+};
+
+enum class WriterVersion : int32_t {
+ kOriginal = 0,
+ kHive8732 = 1,
+ kHive4243 = 2,
+ kHive12055 = 3,
+ kHive13083 = 4,
+ kOrc101 = 5,
+ kOrc135 = 6,
+ kOrc517 = 7,
+ kOrc203 = 8,
+ kOrc14 = 9,
+ kMax = INT32_MAX
+};
+
+enum class CompressionStrategy : int32_t { kSpeed = 0, kCompression };
+
+class ARROW_EXPORT FileVersion {
+ private:
+ int32_t major_version_;
+ int32_t minor_version_;
+
+ public:
+ static const FileVersion& v_0_11();
+ static const FileVersion& v_0_12();
+
+ FileVersion(int32_t major, int32_t minor)
+ : major_version_(major), minor_version_(minor) {}
+
+ /**
+ * Get major version
+ */
+ int32_t major_version() const { return this->major_version_; }
+
+ /**
+ * Get minor version
+ */
+ int32_t minor_version() const { return this->minor_version_; }
+
+ bool operator==(const FileVersion& right) const {
+ return this->major_version() == right.major_version() &&
+ this->minor_version() == right.minor_version();
+ }
+
+ bool operator!=(const FileVersion& right) const { return !(*this == right); }
+
+ std::string ToString() const;
+};
+
+/// Options for the ORC Writer
+struct ARROW_EXPORT WriteOptions {
+ /// Number of rows the ORC writer writes at a time, default 1024
+ int64_t batch_size = 1024;
+ /// Which ORC file version to use, default FileVersion(0, 12)
+ FileVersion file_version = FileVersion(0, 12);
+ /// Size of each ORC stripe in bytes, default 64 MiB
+ int64_t stripe_size = 64 * 1024 * 1024;
+ /// The compression codec of the ORC file, there is no compression by default
+ Compression::type compression = Compression::UNCOMPRESSED;
+ /// The size of each compression block in bytes, default 64 KiB
+ int64_t compression_block_size = 64 * 1024;
+ /// The compression strategy i.e. speed vs size reduction, default
+ /// CompressionStrategy::kSpeed
+ CompressionStrategy compression_strategy = CompressionStrategy::kSpeed;
+ /// The number of rows per an entry in the row index, default 10000
+ int64_t row_index_stride = 10000;
+ /// The padding tolerance, default 0.0
+ double padding_tolerance = 0.0;
+ /// The dictionary key size threshold. 0 to disable dictionary encoding.
+ /// 1 to always enable dictionary encoding, default 0.0
+ double dictionary_key_size_threshold = 0.0;
+ /// The array of columns that use the bloom filter, default empty
+ std::vector bloom_filter_columns;
+ /// The upper limit of the false-positive rate of the bloom filter, default 0.05
+ double bloom_filter_fpp = 0.05;
+};
+
+} // namespace orc
+} // namespace adapters
+} // namespace arrow
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/adapters/tensorflow/convert.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/adapters/tensorflow/convert.h
new file mode 100644
index 0000000000000000000000000000000000000000..9d093eddf6b598150ddb55da0e84699a5b7ef4b8
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/adapters/tensorflow/convert.h
@@ -0,0 +1,128 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include
+
+#include "tensorflow/core/framework/op.h"
+
+#include "arrow/type.h"
+
+// These utilities are supposed to be included in TensorFlow operators
+// that need to be compiled separately from Arrow because of ABI issues.
+// They therefore need to be header-only.
+
+namespace arrow {
+
+namespace adapters {
+
+namespace tensorflow {
+
+Status GetArrowType(::tensorflow::DataType dtype, std::shared_ptr* out) {
+ switch (dtype) {
+ case ::tensorflow::DT_BOOL:
+ *out = arrow::boolean();
+ break;
+ case ::tensorflow::DT_FLOAT:
+ *out = arrow::float32();
+ break;
+ case ::tensorflow::DT_DOUBLE:
+ *out = arrow::float64();
+ break;
+ case ::tensorflow::DT_HALF:
+ *out = arrow::float16();
+ break;
+ case ::tensorflow::DT_INT8:
+ *out = arrow::int8();
+ break;
+ case ::tensorflow::DT_INT16:
+ *out = arrow::int16();
+ break;
+ case ::tensorflow::DT_INT32:
+ *out = arrow::int32();
+ break;
+ case ::tensorflow::DT_INT64:
+ *out = arrow::int64();
+ break;
+ case ::tensorflow::DT_UINT8:
+ *out = arrow::uint8();
+ break;
+ case ::tensorflow::DT_UINT16:
+ *out = arrow::uint16();
+ break;
+ case ::tensorflow::DT_UINT32:
+ *out = arrow::uint32();
+ break;
+ case ::tensorflow::DT_UINT64:
+ *out = arrow::uint64();
+ break;
+ default:
+ return Status::TypeError("TensorFlow data type is not supported");
+ }
+ return Status::OK();
+}
+
+Status GetTensorFlowType(std::shared_ptr dtype, ::tensorflow::DataType* out) {
+ switch (dtype->id()) {
+ case Type::BOOL:
+ *out = ::tensorflow::DT_BOOL;
+ break;
+ case Type::UINT8:
+ *out = ::tensorflow::DT_UINT8;
+ break;
+ case Type::INT8:
+ *out = ::tensorflow::DT_INT8;
+ break;
+ case Type::UINT16:
+ *out = ::tensorflow::DT_UINT16;
+ break;
+ case Type::INT16:
+ *out = ::tensorflow::DT_INT16;
+ break;
+ case Type::UINT32:
+ *out = ::tensorflow::DT_UINT32;
+ break;
+ case Type::INT32:
+ *out = ::tensorflow::DT_INT32;
+ break;
+ case Type::UINT64:
+ *out = ::tensorflow::DT_UINT64;
+ break;
+ case Type::INT64:
+ *out = ::tensorflow::DT_INT64;
+ break;
+ case Type::HALF_FLOAT:
+ *out = ::tensorflow::DT_HALF;
+ break;
+ case Type::FLOAT:
+ *out = ::tensorflow::DT_FLOAT;
+ break;
+ case Type::DOUBLE:
+ *out = ::tensorflow::DT_DOUBLE;
+ break;
+ default:
+ return Status::TypeError("Arrow data type is not supported");
+ }
+ return arrow::Status::OK();
+}
+
+} // namespace tensorflow
+
+} // namespace adapters
+
+} // namespace arrow
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/c/abi.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/c/abi.h
new file mode 100644
index 0000000000000000000000000000000000000000..ae632f2dbd2601135cb02bc203dd085afd0acaf7
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/c/abi.h
@@ -0,0 +1,460 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+/// \file abi.h Arrow C Data Interface
+///
+/// The Arrow C Data interface defines a very small, stable set
+/// of C definitions which can be easily copied into any project's
+/// source code and vendored to be used for columnar data interchange
+/// in the Arrow format. For non-C/C++ languages and runtimes,
+/// it should be almost as easy to translate the C definitions into
+/// the corresponding C FFI declarations.
+///
+/// Applications and libraries can therefore work with Arrow memory
+/// without necessarily using the Arrow libraries or reinventing
+/// the wheel. Developers can choose between tight integration
+/// with the Arrow software project or minimal integration with
+/// the Arrow format only.
+
+#pragma once
+
+#include
+
+// Spec and documentation: https://arrow.apache.org/docs/format/CDataInterface.html
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef ARROW_C_DATA_INTERFACE
+# define ARROW_C_DATA_INTERFACE
+
+# define ARROW_FLAG_DICTIONARY_ORDERED 1
+# define ARROW_FLAG_NULLABLE 2
+# define ARROW_FLAG_MAP_KEYS_SORTED 4
+
+struct ArrowSchema {
+ // Array type description
+ const char* format;
+ const char* name;
+ const char* metadata;
+ int64_t flags;
+ int64_t n_children;
+ struct ArrowSchema** children;
+ struct ArrowSchema* dictionary;
+
+ // Release callback
+ void (*release)(struct ArrowSchema*);
+ // Opaque producer-specific data
+ void* private_data;
+};
+
+struct ArrowArray {
+ // Array data description
+ int64_t length;
+ int64_t null_count;
+ int64_t offset;
+ int64_t n_buffers;
+ int64_t n_children;
+ const void** buffers;
+ struct ArrowArray** children;
+ struct ArrowArray* dictionary;
+
+ // Release callback
+ void (*release)(struct ArrowArray*);
+ // Opaque producer-specific data
+ void* private_data;
+};
+
+# define ARROW_STATISTICS_KEY_AVERAGE_BYTE_WIDTH_EXACT "ARROW:average_byte_width:exact"
+# define ARROW_STATISTICS_KEY_AVERAGE_BYTE_WIDTH_APPROXIMATE \
+ "ARROW:average_byte_width:approximate"
+# define ARROW_STATISTICS_KEY_DISTINCT_COUNT_EXACT "ARROW:distinct_count:exact"
+# define ARROW_STATISTICS_KEY_DISTINCT_COUNT_APPROXIMATE \
+ "ARROW:distinct_count:approximate"
+# define ARROW_STATISTICS_KEY_MAX_BYTE_WIDTH_EXACT "ARROW:max_byte_width:exact"
+# define ARROW_STATISTICS_KEY_MAX_BYTE_WIDTH_APPROXIMATE \
+ "ARROW:max_byte_width:approximate"
+# define ARROW_STATISTICS_KEY_MAX_VALUE_EXACT "ARROW:max_value:exact"
+# define ARROW_STATISTICS_KEY_MAX_VALUE_APPROXIMATE "ARROW:max_value:approximate"
+# define ARROW_STATISTICS_KEY_MIN_VALUE_EXACT "ARROW:min_value:exact"
+# define ARROW_STATISTICS_KEY_MIN_VALUE_APPROXIMATE "ARROW:min_value:approximate"
+# define ARROW_STATISTICS_KEY_NULL_COUNT_EXACT "ARROW:null_count:exact"
+# define ARROW_STATISTICS_KEY_NULL_COUNT_APPROXIMATE "ARROW:null_count:approximate"
+# define ARROW_STATISTICS_KEY_ROW_COUNT_EXACT "ARROW:row_count:exact"
+# define ARROW_STATISTICS_KEY_ROW_COUNT_APPROXIMATE "ARROW:row_count:approximate"
+
+#endif // ARROW_C_DATA_INTERFACE
+
+#ifndef ARROW_C_DEVICE_DATA_INTERFACE
+# define ARROW_C_DEVICE_DATA_INTERFACE
+
+// Spec and Documentation: https://arrow.apache.org/docs/format/CDeviceDataInterface.html
+
+// DeviceType for the allocated memory
+typedef int32_t ArrowDeviceType;
+
+// CPU device, same as using ArrowArray directly
+# define ARROW_DEVICE_CPU 1
+// CUDA GPU Device
+# define ARROW_DEVICE_CUDA 2
+// Pinned CUDA CPU memory by cudaMallocHost
+# define ARROW_DEVICE_CUDA_HOST 3
+// OpenCL Device
+# define ARROW_DEVICE_OPENCL 4
+// Vulkan buffer for next-gen graphics
+# define ARROW_DEVICE_VULKAN 7
+// Metal for Apple GPU
+# define ARROW_DEVICE_METAL 8
+// Verilog simulator buffer
+# define ARROW_DEVICE_VPI 9
+// ROCm GPUs for AMD GPUs
+# define ARROW_DEVICE_ROCM 10
+// Pinned ROCm CPU memory allocated by hipMallocHost
+# define ARROW_DEVICE_ROCM_HOST 11
+// Reserved for extension
+# define ARROW_DEVICE_EXT_DEV 12
+// CUDA managed/unified memory allocated by cudaMallocManaged
+# define ARROW_DEVICE_CUDA_MANAGED 13
+// unified shared memory allocated on a oneAPI non-partitioned device.
+# define ARROW_DEVICE_ONEAPI 14
+// GPU support for next-gen WebGPU standard
+# define ARROW_DEVICE_WEBGPU 15
+// Qualcomm Hexagon DSP
+# define ARROW_DEVICE_HEXAGON 16
+
+struct ArrowDeviceArray {
+ // the Allocated Array
+ //
+ // the buffers in the array (along with the buffers of any
+ // children) are what is allocated on the device.
+ struct ArrowArray array;
+ // The device id to identify a specific device
+ int64_t device_id;
+ // The type of device which can access this memory.
+ ArrowDeviceType device_type;
+ // An event-like object to synchronize on if needed.
+ void* sync_event;
+ // Reserved bytes for future expansion.
+ int64_t reserved[3];
+};
+
+#endif // ARROW_C_DEVICE_DATA_INTERFACE
+
+#ifndef ARROW_C_STREAM_INTERFACE
+# define ARROW_C_STREAM_INTERFACE
+
+struct ArrowArrayStream {
+ // Callback to get the stream type
+ // (will be the same for all arrays in the stream).
+ //
+ // Return value: 0 if successful, an `errno`-compatible error code otherwise.
+ //
+ // If successful, the ArrowSchema must be released independently from the stream.
+ int (*get_schema)(struct ArrowArrayStream*, struct ArrowSchema* out);
+
+ // Callback to get the next array
+ // (if no error and the array is released, the stream has ended)
+ //
+ // Return value: 0 if successful, an `errno`-compatible error code otherwise.
+ //
+ // If successful, the ArrowArray must be released independently from the stream.
+ int (*get_next)(struct ArrowArrayStream*, struct ArrowArray* out);
+
+ // Callback to get optional detailed error information.
+ // This must only be called if the last stream operation failed
+ // with a non-0 return code.
+ //
+ // Return value: pointer to a null-terminated character array describing
+ // the last error, or NULL if no description is available.
+ //
+ // The returned pointer is only valid until the next operation on this stream
+ // (including release).
+ const char* (*get_last_error)(struct ArrowArrayStream*);
+
+ // Release callback: release the stream's own resources.
+ // Note that arrays returned by `get_next` must be individually released.
+ void (*release)(struct ArrowArrayStream*);
+
+ // Opaque producer-specific data
+ void* private_data;
+};
+
+#endif // ARROW_C_STREAM_INTERFACE
+
+#ifndef ARROW_C_DEVICE_STREAM_INTERFACE
+# define ARROW_C_DEVICE_STREAM_INTERFACE
+
+// Equivalent to ArrowArrayStream, but for ArrowDeviceArrays.
+//
+// This stream is intended to provide a stream of data on a single
+// device, if a producer wants data to be produced on multiple devices
+// then multiple streams should be provided. One per device.
+struct ArrowDeviceArrayStream {
+ // The device that this stream produces data on.
+ ArrowDeviceType device_type;
+
+ // Callback to get the stream schema
+ // (will be the same for all arrays in the stream).
+ //
+ // Return value 0 if successful, an `errno`-compatible error code otherwise.
+ //
+ // If successful, the ArrowSchema must be released independently from the stream.
+ // The schema should be accessible via CPU memory.
+ int (*get_schema)(struct ArrowDeviceArrayStream* self, struct ArrowSchema* out);
+
+ // Callback to get the next array
+ // (if no error and the array is released, the stream has ended)
+ //
+ // Return value: 0 if successful, an `errno`-compatible error code otherwise.
+ //
+ // If successful, the ArrowDeviceArray must be released independently from the stream.
+ int (*get_next)(struct ArrowDeviceArrayStream* self, struct ArrowDeviceArray* out);
+
+ // Callback to get optional detailed error information.
+ // This must only be called if the last stream operation failed
+ // with a non-0 return code.
+ //
+ // Return value: pointer to a null-terminated character array describing
+ // the last error, or NULL if no description is available.
+ //
+ // The returned pointer is only valid until the next operation on this stream
+ // (including release).
+ const char* (*get_last_error)(struct ArrowDeviceArrayStream* self);
+
+ // Release callback: release the stream's own resources.
+ // Note that arrays returned by `get_next` must be individually released.
+ void (*release)(struct ArrowDeviceArrayStream* self);
+
+ // Opaque producer-specific data
+ void* private_data;
+};
+
+#endif // ARROW_C_DEVICE_STREAM_INTERFACE
+
+#ifndef ARROW_C_ASYNC_STREAM_INTERFACE
+# define ARROW_C_ASYNC_STREAM_INTERFACE
+
+// EXPERIMENTAL: ArrowAsyncTask represents available data from a producer that was passed
+// to an invocation of `on_next_task` on the ArrowAsyncDeviceStreamHandler.
+//
+// The reason for this Task approach instead of the Async interface returning
+// the Array directly is to allow for more complex thread handling and reducing
+// context switching and data transfers between CPU cores (e.g. from one L1/L2
+// cache to another) if desired.
+//
+// For example, the `on_next_task` callback can be called when data is ready, while
+// the producer puts potential "decoding" logic in the `ArrowAsyncTask` object. This
+// allows for the producer to manage the I/O on one thread which calls `on_next_task`
+// and the consumer can determine when the decoding (producer logic in the `extract_data`
+// callback of the task) occurs and on which thread, to avoid a CPU core transfer
+// (data staying in the L2 cache).
+struct ArrowAsyncTask {
+ // This callback should populate the ArrowDeviceArray associated with this task.
+ // The order of ArrowAsyncTasks provided by the producer enables a consumer to
+ // ensure the order of data to process.
+ //
+ // This function is expected to be synchronous, but should not perform any blocking
+ // I/O. Ideally it should be as cheap as possible so as to not tie up the consumer
+ // thread unnecessarily.
+ //
+ // Returns: 0 if successful, errno-compatible error otherwise.
+ //
+ // If a non-0 value is returned then it should be followed by a call to `on_error`
+ // on the appropriate ArrowAsyncDeviceStreamHandler. This is because it's highly
+ // likely that whatever is calling this function may be entirely disconnected from
+ // the current control flow. Indicating an error here with a non-zero return allows
+ // the current flow to be aware of the error occurring, while still allowing any
+ // logging or error handling to still be centralized in the `on_error` callback of
+ // the original Async handler.
+ //
+ // Rather than a release callback, any required cleanup should be performed as part
+ // of the invocation of `extract_data`. Ownership of the Array is passed to the consumer
+ // calling this, and so it must be released separately.
+ //
+ // It is only valid to call this method exactly once.
+ int (*extract_data)(struct ArrowAsyncTask* self, struct ArrowDeviceArray* out);
+
+ // opaque task-specific data
+ void* private_data;
+};
+
+// EXPERIMENTAL: ArrowAsyncProducer represents a 1-to-1 relationship between an async
+// producer and consumer. This object allows the consumer to perform backpressure and flow
+// control on the asynchronous stream processing. This object must be owned by the
+// producer who creates it, and thus is responsible for cleaning it up.
+struct ArrowAsyncProducer {
+ // The device type that this stream produces data on.
+ ArrowDeviceType device_type;
+
+ // A consumer must call this function to start receiving on_next_task calls.
+ //
+ // It *must* be valid to call this synchronously from within `on_next_task` or
+ // `on_schema`, but this function *must not* immediately call `on_next_task` so as
+ // to avoid recursion and reentrant callbacks.
+ //
+ // After cancel has been called, additional calls to this function must be NOPs,
+ // but allowed. While not cancelled, calling this function must register the
+ // given number of additional arrays/batches to be produced with the producer.
+ // The producer should only call `on_next_task` at most the registered number
+ // of arrays before propagating backpressure.
+ //
+ // Any error encountered by calling request must be propagated by calling the `on_error`
+ // callback of the ArrowAsyncDeviceStreamHandler.
+ //
+ // While not cancelled, any subsequent calls to `on_next_task`, `on_error` or
+ // `release` should be scheduled by the producer to be called later.
+ //
+ // It is invalid for a consumer to call this with a value of n <= 0, producers should
+ // error if given such a value.
+ void (*request)(struct ArrowAsyncProducer* self, int64_t n);
+
+ // This cancel callback signals a producer that it must eventually stop making calls
+ // to on_next_task. It must be idempotent and thread-safe. After calling cancel once,
+ // subsequent calls must be NOPs. This must not call any consumer-side handlers other
+ // than `on_error`.
+ //
+ // It is not required that calling cancel affect the producer immediately, only that it
+ // must eventually stop calling on_next_task and subsequently call release on the
+ // async handler. As such, a consumer must be prepared to receive one or more calls to
+ // `on_next_task` even after calling cancel if there are still requested arrays pending.
+ //
+ // Successful cancellation should *not* result in the producer calling `on_error`, it
+ // should finish out any remaining tasks and eventually call `release`.
+ //
+ // Any error encountered during handling a call to cancel must be reported via the
+ // on_error callback on the async stream handler.
+ void (*cancel)(struct ArrowAsyncProducer* self);
+
+ // Any additional metadata tied to a specific stream of data. This must either be NULL
+ // or a valid pointer to metadata which is encoded in the same way schema metadata
+ // would be. Non-null metadata must be valid for the lifetime of this object. As an
+ // example a producer could use this to provide the total number of rows and/or batches
+ // in the stream if known.
+ const char* additional_metadata;
+
+ // producer-specific opaque data.
+ void* private_data;
+};
+
+// EXPERIMENTAL: Similar to ArrowDeviceArrayStream, except designed for an asynchronous
+// style of interaction. While ArrowDeviceArrayStream provides producer
+// defined callbacks, this is intended to be created by the consumer instead.
+// The consumer passes this handler to the producer, which in turn uses the
+// callbacks to inform the consumer of events in the stream.
+struct ArrowAsyncDeviceStreamHandler {
+ // Handler for receiving a schema. The passed in stream_schema must be
+ // released or moved by the handler (producer is giving ownership of the schema to
+ // the handler, but not ownership of the top level object itself).
+ //
+ // With the exception of an error occurring (on_error), this must be the first
+ // callback function which is called by a producer and must only be called exactly
+ // once. As such, the producer should provide a valid ArrowAsyncProducer instance
+ // so the consumer can control the flow. See the documentation on ArrowAsyncProducer
+ // for how it works. The ArrowAsyncProducer is owned by the producer who calls this
+ // function and thus the producer is responsible for cleaning it up when calling
+ // the release callback of this handler.
+ //
+ // If there is any additional metadata tied to this stream, it will be provided as
+ // a non-null value for the `additional_metadata` field of the ArrowAsyncProducer
+ // which will be valid at least until the release callback is called.
+ //
+ // Return value: 0 if successful, `errno`-compatible error otherwise
+ //
+ // A producer that receives a non-zero return here should stop producing and eventually
+ // call release instead.
+ int (*on_schema)(struct ArrowAsyncDeviceStreamHandler* self,
+ struct ArrowSchema* stream_schema);
+
+ // Handler for receiving data. This is called when data is available providing an
+ // ArrowAsyncTask struct to signify it. The producer indicates the end of the stream
+ // by passing NULL as the value for the task rather than a valid pointer to a task.
+ // The task object is only valid for the lifetime of this function call, if a consumer
+ // wants to utilize it after this function returns, it must copy or move the contents
+ // of it to a new ArrowAsyncTask object.
+ //
+ // The `request` callback of a provided ArrowAsyncProducer must be called in order
+ // to start receiving calls to this handler.
+ //
+ // The metadata argument can be null or can be used by a producer
+ // to pass arbitrary extra information to the consumer (such as total number
+ // of rows, context info, or otherwise). The data should be passed using the same
+ // encoding as the metadata within the ArrowSchema struct itself (defined in
+ // the spec at
+ // https://arrow.apache.org/docs/format/CDataInterface.html#c.ArrowSchema.metadata)
+ //
+ // If metadata is non-null then it only needs to exist for the lifetime of this call,
+ // a consumer who wants it to live after that must copy it to ensure lifetime.
+ //
+ // A producer *must not* call this concurrently from multiple different threads.
+ //
+ // A consumer must be prepared to receive one or more calls to this callback even
+ // after calling cancel on the corresponding ArrowAsyncProducer, as cancel does not
+ // guarantee it happens immediately.
+ //
+ // Return value: 0 if successful, `errno`-compatible error otherwise.
+ //
+ // If the consumer returns a non-zero return from this method, that indicates to the
+ // producer that it should stop propagating data as an error occurred. After receiving
+ // such a return, the only interaction with this object is for the producer to call
+ // the `release` callback.
+ int (*on_next_task)(struct ArrowAsyncDeviceStreamHandler* self,
+ struct ArrowAsyncTask* task, const char* metadata);
+
+ // Handler for encountering an error. The producer should call release after
+ // this returns to clean up any resources. The `code` passed in can be any error
+ // code that a producer wants, but should be errno-compatible for consistency.
+ //
+ // If the message or metadata are non-null, they will only last as long as this
+ // function call. The consumer would need to perform a copy of the data if it is
+ // necessary for them to live past the lifetime of this call.
+ //
+ // Error metadata should be encoded as with metadata in ArrowSchema, defined in
+ // the spec at
+ // https://arrow.apache.org/docs/format/CDataInterface.html#c.ArrowSchema.metadata
+ //
+ // It is valid for this to be called by a producer with or without a preceding call
+ // to ArrowAsyncProducer.request.
+ //
+ // This callback must not call any methods of an ArrowAsyncProducer object.
+ void (*on_error)(struct ArrowAsyncDeviceStreamHandler* self, int code,
+ const char* message, const char* metadata);
+
+ // Release callback to release any resources for the handler. Should always be
+ // called by a producer when it is done utilizing a handler. No callbacks should
+ // be called after this is called.
+ //
+ // It is valid for the release callback to be called by a producer with or without
+ // a preceding call to ArrowAsyncProducer.request.
+ //
+ // The release callback must not call any methods of an ArrowAsyncProducer object.
+ void (*release)(struct ArrowAsyncDeviceStreamHandler* self);
+
+ // MUST be populated by the producer BEFORE calling any callbacks other than release.
+ // This provides the connection between a handler and its producer, and must exist until
+ // the release callback is called.
+ struct ArrowAsyncProducer* producer;
+
+ // Opaque handler-specific data
+ void* private_data;
+};
+
+#endif // ARROW_C_ASYNC_STREAM_INTERFACE
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/c/bridge.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/c/bridge.h
new file mode 100644
index 0000000000000000000000000000000000000000..78860e0650e741a95e7f8bc0c5ab35bc1c01cf79
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/c/bridge.h
@@ -0,0 +1,489 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include
+#include
+#include
+
+#include "arrow/c/abi.h"
+#include "arrow/device.h"
+#include "arrow/result.h"
+#include "arrow/status.h"
+#include "arrow/type_fwd.h"
+#include "arrow/util/async_generator_fwd.h"
+#include "arrow/util/macros.h"
+#include "arrow/util/visibility.h"
+
+namespace arrow {
+
+/// \defgroup c-data-interface Functions for working with the C data interface.
+///
+/// @{
+
+/// \brief Export C++ DataType using the C data interface format.
+///
+/// The root type is considered to have empty name and metadata.
+/// If you want the root type to have a name and/or metadata, pass
+/// a Field instead.
+///
+/// \param[in] type DataType object to export
+/// \param[out] out C struct where to export the datatype
+ARROW_EXPORT
+Status ExportType(const DataType& type, struct ArrowSchema* out);
+
+/// \brief Export C++ Field using the C data interface format.
+///
+/// \param[in] field Field object to export
+/// \param[out] out C struct where to export the field
+ARROW_EXPORT
+Status ExportField(const Field& field, struct ArrowSchema* out);
+
+/// \brief Export C++ Schema using the C data interface format.
+///
+/// \param[in] schema Schema object to export
+/// \param[out] out C struct where to export the field
+ARROW_EXPORT
+Status ExportSchema(const Schema& schema, struct ArrowSchema* out);
+
+/// \brief Export C++ Array using the C data interface format.
+///
+/// The resulting ArrowArray struct keeps the array data and buffers alive
+/// until its release callback is called by the consumer.
+///
+/// \param[in] array Array object to export
+/// \param[out] out C struct where to export the array
+/// \param[out] out_schema optional C struct where to export the array type
+ARROW_EXPORT
+Status ExportArray(const Array& array, struct ArrowArray* out,
+ struct ArrowSchema* out_schema = NULLPTR);
+
+/// \brief Export C++ RecordBatch using the C data interface format.
+///
+/// The record batch is exported as if it were a struct array.
+/// The resulting ArrowArray struct keeps the record batch data and buffers alive
+/// until its release callback is called by the consumer.
+///
+/// \param[in] batch Record batch to export
+/// \param[out] out C struct where to export the record batch
+/// \param[out] out_schema optional C struct where to export the record batch schema
+ARROW_EXPORT
+Status ExportRecordBatch(const RecordBatch& batch, struct ArrowArray* out,
+ struct ArrowSchema* out_schema = NULLPTR);
+
+/// \brief Import C++ DataType from the C data interface.
+///
+/// The given ArrowSchema struct is released (as per the C data interface
+/// specification), even if this function fails.
+///
+/// \param[in,out] schema C data interface struct representing the data type
+/// \return Imported type object
+ARROW_EXPORT
+Result> ImportType(struct ArrowSchema* schema);
+
+/// \brief Import C++ Field from the C data interface.
+///
+/// The given ArrowSchema struct is released (as per the C data interface
+/// specification), even if this function fails.
+///
+/// \param[in,out] schema C data interface struct representing the field
+/// \return Imported field object
+ARROW_EXPORT
+Result> ImportField(struct ArrowSchema* schema);
+
+/// \brief Import C++ Schema from the C data interface.
+///
+/// The given ArrowSchema struct is released (as per the C data interface
+/// specification), even if this function fails.
+///
+/// \param[in,out] schema C data interface struct representing the field
+/// \return Imported field object
+ARROW_EXPORT
+Result> ImportSchema(struct ArrowSchema* schema);
+
+/// \brief Import C++ array from the C data interface.
+///
+/// The ArrowArray struct has its contents moved (as per the C data interface
+/// specification) to a private object held alive by the resulting array.
+///
+/// \param[in,out] array C data interface struct holding the array data
+/// \param[in] type type of the imported array
+/// \return Imported array object
+ARROW_EXPORT
+Result> ImportArray(struct ArrowArray* array,
+ std::shared_ptr type);
+
+/// \brief Import C++ array and its type from the C data interface.
+///
+/// The ArrowArray struct has its contents moved (as per the C data interface
+/// specification) to a private object held alive by the resulting array.
+/// The ArrowSchema struct is released, even if this function fails.
+///
+/// \param[in,out] array C data interface struct holding the array data
+/// \param[in,out] type C data interface struct holding the array type
+/// \return Imported array object
+ARROW_EXPORT
+Result> ImportArray(struct ArrowArray* array,
+ struct ArrowSchema* type);
+
+/// \brief Import C++ record batch from the C data interface.
+///
+/// The ArrowArray struct has its contents moved (as per the C data interface
+/// specification) to a private object held alive by the resulting record batch.
+///
+/// \param[in,out] array C data interface struct holding the record batch data
+/// \param[in] schema schema of the imported record batch
+/// \return Imported record batch object
+ARROW_EXPORT
+Result> ImportRecordBatch(struct ArrowArray* array,
+ std::shared_ptr schema);
+
+/// \brief Import C++ record batch and its schema from the C data interface.
+///
+/// The type represented by the ArrowSchema struct must be a struct type array.
+/// The ArrowArray struct has its contents moved (as per the C data interface
+/// specification) to a private object held alive by the resulting record batch.
+/// The ArrowSchema struct is released, even if this function fails.
+///
+/// \param[in,out] array C data interface struct holding the record batch data
+/// \param[in,out] schema C data interface struct holding the record batch schema
+/// \return Imported record batch object
+ARROW_EXPORT
+Result> ImportRecordBatch(struct ArrowArray* array,
+ struct ArrowSchema* schema);
+
+/// @}
+
+/// \defgroup c-data-device-interface Functions for working with the C data device
+/// interface.
+///
+/// @{
+
+/// \brief EXPERIMENTAL: Export C++ Array as an ArrowDeviceArray.
+///
+/// The resulting ArrowDeviceArray struct keeps the array data and buffers alive
+/// until its release callback is called by the consumer. All buffers in
+/// the provided array MUST have the same device_type, otherwise an error
+/// will be returned.
+///
+/// If sync is non-null, get_event will be called on it in order to
+/// potentially provide an event for consumers to synchronize on.
+///
+/// \param[in] array Array object to export
+/// \param[in] sync shared_ptr to object derived from Device::SyncEvent or null
+/// \param[out] out C struct to export the array to
+/// \param[out] out_schema optional C struct to export the array type to
+ARROW_EXPORT
+Status ExportDeviceArray(const Array& array, std::shared_ptr sync,
+ struct ArrowDeviceArray* out,
+ struct ArrowSchema* out_schema = NULLPTR);
+
+/// \brief EXPERIMENTAL: Export C++ RecordBatch as an ArrowDeviceArray.
+///
+/// The record batch is exported as if it were a struct array.
+/// The resulting ArrowDeviceArray struct keeps the record batch data and buffers alive
+/// until its release callback is called by the consumer.
+///
+/// All buffers of all columns in the record batch must have the same device_type
+/// otherwise an error will be returned. If columns are on different devices,
+/// they should be exported using different ArrowDeviceArray instances.
+///
+/// If sync is non-null, get_event will be called on it in order to
+/// potentially provide an event for consumers to synchronize on.
+///
+/// \param[in] batch Record batch to export
+/// \param[in] sync shared_ptr to object derived from Device::SyncEvent or null
+/// \param[out] out C struct where to export the record batch
+/// \param[out] out_schema optional C struct where to export the record batch schema
+ARROW_EXPORT
+Status ExportDeviceRecordBatch(const RecordBatch& batch,
+ std::shared_ptr sync,
+ struct ArrowDeviceArray* out,
+ struct ArrowSchema* out_schema = NULLPTR);
+
+using DeviceMemoryMapper =
+ std::function>(ArrowDeviceType, int64_t)>;
+
+ARROW_EXPORT
+Result> DefaultDeviceMemoryMapper(
+ ArrowDeviceType device_type, int64_t device_id);
+
+/// \brief EXPERIMENTAL: Import C++ device array from the C data interface.
+///
+/// The ArrowArray struct has its contents moved (as per the C data interface
+/// specification) to a private object held alive by the resulting array. The
+/// buffers of the Array are located on the device indicated by the device_type.
+///
+/// \param[in,out] array C data interface struct holding the array data
+/// \param[in] type type of the imported array
+/// \param[in] mapper A function to map device + id to memory manager. If not
+/// specified, defaults to map "cpu" to the built-in default memory manager.
+/// \return Imported array object
+ARROW_EXPORT
+Result> ImportDeviceArray(
+ struct ArrowDeviceArray* array, std::shared_ptr type,
+ const DeviceMemoryMapper& mapper = DefaultDeviceMemoryMapper);
+
+/// \brief EXPERIMENTAL: Import C++ device array and its type from the C data interface.
+///
+/// The ArrowArray struct has its contents moved (as per the C data interface
+/// specification) to a private object held alive by the resulting array.
+/// The ArrowSchema struct is released, even if this function fails. The
+/// buffers of the Array are located on the device indicated by the device_type.
+///
+/// \param[in,out] array C data interface struct holding the array data
+/// \param[in,out] type C data interface struct holding the array type
+/// \param[in] mapper A function to map device + id to memory manager. If not
+/// specified, defaults to map "cpu" to the built-in default memory manager.
+/// \return Imported array object
+ARROW_EXPORT
+Result> ImportDeviceArray(
+ struct ArrowDeviceArray* array, struct ArrowSchema* type,
+ const DeviceMemoryMapper& mapper = DefaultDeviceMemoryMapper);
+
+/// \brief EXPERIMENTAL: Import C++ record batch with buffers on a device from the C data
+/// interface.
+///
+/// The ArrowArray struct has its contents moved (as per the C data interface
+/// specification) to a private object held alive by the resulting record batch.
+/// The buffers of all columns of the record batch are located on the device
+/// indicated by the device type.
+///
+/// \param[in,out] array C data interface struct holding the record batch data
+/// \param[in] schema schema of the imported record batch
+/// \param[in] mapper A function to map device + id to memory manager. If not
+/// specified, defaults to map "cpu" to the built-in default memory manager.
+/// \return Imported record batch object
+ARROW_EXPORT
+Result> ImportDeviceRecordBatch(
+ struct ArrowDeviceArray* array, std::shared_ptr schema,
+ const DeviceMemoryMapper& mapper = DefaultDeviceMemoryMapper);
+
+/// \brief EXPERIMENTAL: Import C++ record batch with buffers on a device and its schema
+/// from the C data interface.
+///
+/// The type represented by the ArrowSchema struct must be a struct type array.
+/// The ArrowArray struct has its contents moved (as per the C data interface
+/// specification) to a private object held alive by the resulting record batch.
+/// The ArrowSchema struct is released, even if this function fails. The buffers
+/// of all columns of the record batch are located on the device indicated by the
+/// device type.
+///
+/// \param[in,out] array C data interface struct holding the record batch data
+/// \param[in,out] schema C data interface struct holding the record batch schema
+/// \param[in] mapper A function to map device + id to memory manager. If not
+/// specified, defaults to map "cpu" to the built-in default memory manager.
+/// \return Imported record batch object
+ARROW_EXPORT
+Result> ImportDeviceRecordBatch(
+ struct ArrowDeviceArray* array, struct ArrowSchema* schema,
+ const DeviceMemoryMapper& mapper = DefaultDeviceMemoryMapper);
+
+/// @}
+
+/// \defgroup c-stream-interface Functions for working with the C data interface.
+///
+/// @{
+
+/// \brief Export C++ RecordBatchReader using the C stream interface.
+///
+/// The resulting ArrowArrayStream struct keeps the record batch reader alive
+/// until its release callback is called by the consumer.
+///
+/// \param[in] reader RecordBatchReader object to export
+/// \param[out] out C struct where to export the stream
+ARROW_EXPORT
+Status ExportRecordBatchReader(std::shared_ptr reader,
+ struct ArrowArrayStream* out);
+
+/// \brief Export C++ ChunkedArray using the C data interface format.
+///
+/// The resulting ArrowArrayStream struct keeps the chunked array data and buffers alive
+/// until its release callback is called by the consumer.
+///
+/// \param[in] chunked_array ChunkedArray object to export
+/// \param[out] out C struct where to export the stream
+ARROW_EXPORT
+Status ExportChunkedArray(std::shared_ptr chunked_array,
+ struct ArrowArrayStream* out);
+
+/// \brief Export C++ RecordBatchReader using the C device stream interface
+///
+/// The resulting ArrowDeviceArrayStream struct keeps the record batch reader
+/// alive until its release callback is called by the consumer. The device
+/// type is determined by calling device_type() on the RecordBatchReader.
+///
+/// \param[in] reader RecordBatchReader object to export
+/// \param[out] out C struct to export the stream to
+ARROW_EXPORT
+Status ExportDeviceRecordBatchReader(std::shared_ptr reader,
+ struct ArrowDeviceArrayStream* out);
+
+/// \brief Export C++ ChunkedArray using the C device data interface format.
+///
+/// The resulting ArrowDeviceArrayStream keeps the chunked array data and buffers
+/// alive until its release callback is called by the consumer.
+///
+/// \param[in] chunked_array ChunkedArray object to export
+/// \param[in] device_type the device type the data is located on
+/// \param[out] out C struct to export the stream to
+ARROW_EXPORT
+Status ExportDeviceChunkedArray(std::shared_ptr chunked_array,
+ DeviceAllocationType device_type,
+ struct ArrowDeviceArrayStream* out);
+
+/// \brief Import C++ RecordBatchReader from the C stream interface.
+///
+/// The ArrowArrayStream struct has its contents moved to a private object
+/// held alive by the resulting record batch reader.
+///
+/// \param[in,out] stream C stream interface struct
+/// \return Imported RecordBatchReader object
+ARROW_EXPORT
+Result> ImportRecordBatchReader(
+ struct ArrowArrayStream* stream);
+
+/// \brief Import C++ ChunkedArray from the C stream interface
+///
+/// The ArrowArrayStream struct has its contents moved to a private object,
+/// is consumed in its entirity, and released before returning all chunks
+/// as a ChunkedArray.
+///
+/// \param[in,out] stream C stream interface struct
+/// \return Imported ChunkedArray object
+ARROW_EXPORT
+Result> ImportChunkedArray(struct ArrowArrayStream* stream);
+
+/// \brief Import C++ RecordBatchReader from the C device stream interface
+///
+/// The ArrowDeviceArrayStream struct has its contents moved to a private object
+/// held alive by the resulting record batch reader.
+///
+/// \note If there was a required sync event, sync events are accessible by individual
+/// buffers of columns. We are not yet bubbling the sync events from the buffers up to
+/// the `GetSyncEvent` method of an imported RecordBatch. This will be added in a future
+/// update.
+///
+/// \param[in,out] stream C device stream interface struct
+/// \param[in] mapper mapping from device type and ID to memory manager
+/// \return Imported RecordBatchReader object
+ARROW_EXPORT
+Result> ImportDeviceRecordBatchReader(
+ struct ArrowDeviceArrayStream* stream,
+ const DeviceMemoryMapper& mapper = DefaultDeviceMemoryMapper);
+
+/// \brief Import C++ ChunkedArray from the C device stream interface
+///
+/// The ArrowDeviceArrayStream struct has its contents moved to a private object,
+/// is consumed in its entirety, and released before returning all chunks as a
+/// ChunkedArray.
+///
+/// \note Any chunks that require synchronization for their device memory will have
+/// the SyncEvent objects available by checking the individual buffers of each chunk.
+/// These SyncEvents should be checked before accessing the data in those buffers.
+///
+/// \param[in,out] stream C device stream interface struct
+/// \param[in] mapper mapping from device type and ID to memory manager
+/// \return Imported ChunkedArray object
+ARROW_EXPORT
+Result> ImportDeviceChunkedArray(
+ struct ArrowDeviceArrayStream* stream,
+ const DeviceMemoryMapper& mapper = DefaultDeviceMemoryMapper);
+
+/// @}
+
+/// \defgroup c-async-stream-interface Functions for working with the async C data
+/// interface.
+///
+/// @{
+
+/// \brief EXPERIMENTAL: AsyncErrorDetail is a StatusDetail that contains an error code
+/// and message from an asynchronous operation.
+class AsyncErrorDetail : public StatusDetail {
+ public:
+ AsyncErrorDetail(int code, std::string message, std::string metadata)
+ : code_(code), message_(std::move(message)), metadata_(std::move(metadata)) {}
+ const char* type_id() const override { return "AsyncErrorDetail"; }
+ // ToString just returns the error message that was returned with the error
+ std::string ToString() const override { return message_; }
+ // code is an errno-compatible error code
+ int code() const { return code_; }
+ // returns any metadata that was returned with the error, likely in a
+ // key-value format similar to ArrowSchema metadata
+ const std::string& ErrorMetadataString() const { return metadata_; }
+ std::shared_ptr ErrorMetadata() const;
+
+ private:
+ int code_{0};
+ std::string message_;
+ std::string metadata_;
+};
+
+struct AsyncRecordBatchGenerator {
+ std::shared_ptr schema;
+ DeviceAllocationType device_type;
+ AsyncGenerator generator;
+};
+
+namespace internal {
+class Executor;
+}
+
+/// \brief EXPERIMENTAL: Create an AsyncRecordBatchReader and populate a corresponding
+/// handler to pass to a producer
+///
+/// The ArrowAsyncDeviceStreamHandler struct is intended to have its callbacks populated
+/// and then be passed to a producer to call the appropriate callbacks when data is ready.
+/// This inverts the traditional flow of control, and so we construct a corresponding
+/// AsyncRecordBatchGenerator to provide an interface for the consumer to retrieve data as
+/// it is pushed to the handler.
+///
+/// \param[in,out] handler C struct to be populated
+/// \param[in] executor the executor to use for waiting and populating record batches
+/// \param[in] queue_size initial number of record batches to request for queueing
+/// \param[in] mapper mapping from device type and ID to memory manager
+/// \return Future that resolves to either an error or AsyncRecordBatchGenerator once a
+/// schema is available or an error is received.
+ARROW_EXPORT
+Future CreateAsyncDeviceStreamHandler(
+ struct ArrowAsyncDeviceStreamHandler* handler, internal::Executor* executor,
+ uint64_t queue_size = 5, DeviceMemoryMapper mapper = DefaultDeviceMemoryMapper);
+
+/// \brief EXPERIMENTAL: Export an AsyncGenerator of record batches using a provided
+/// handler
+///
+/// This function calls the callbacks on the consumer-provided async handler as record
+/// batches become available from the AsyncGenerator which is provided. It will first call
+/// on_schema using the provided schema, and then serially visit each record batch from
+/// the generator, calling the on_next_task callback. If an error occurs, on_error will be
+/// called appropriately.
+///
+/// \param[in] schema the schema of the stream being exported
+/// \param[in] generator a generator that asynchronously produces record batches
+/// \param[in] device_type the device type that the record batches will be located on
+/// \param[in] handler the handler whose callbacks to utilize as data is available
+/// \return Future that will resolve once the generator is exhausted or an error occurs
+ARROW_EXPORT
+Future<> ExportAsyncRecordBatchReader(
+ std::shared_ptr schema,
+ AsyncGenerator> generator,
+ DeviceAllocationType device_type, struct ArrowAsyncDeviceStreamHandler* handler);
+
+/// @}
+
+} // namespace arrow
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/c/dlpack.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/c/dlpack.h
new file mode 100644
index 0000000000000000000000000000000000000000..65da38423c2ad62fce26fc115024ef843fb802b5
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/c/dlpack.h
@@ -0,0 +1,57 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include "arrow/array/array_base.h"
+#include "arrow/c/dlpack_abi.h"
+
+namespace arrow::dlpack {
+
+/// \brief Export Arrow array as DLPack tensor.
+///
+/// DLMangedTensor is produced as defined by the DLPack protocol,
+/// see https://dmlc.github.io/dlpack/latest/.
+///
+/// Data types for which the protocol is supported are
+/// integer and floating-point data types.
+///
+/// DLPack protocol only supports arrays with one contiguous
+/// memory region which means Arrow Arrays with validity buffers
+/// are not supported.
+///
+/// \param[in] arr Arrow array
+/// \return DLManagedTensor struct
+ARROW_EXPORT
+Result ExportArray(const std::shared_ptr& arr);
+
+ARROW_EXPORT
+Result ExportTensor(const std::shared_ptr& t);
+
+/// \brief Get DLDevice with enumerator specifying the
+/// type of the device data is stored on and index of the
+/// device which is 0 by default for CPU.
+///
+/// \param[in] arr Arrow array
+/// \return DLDevice struct
+ARROW_EXPORT
+Result ExportDevice(const std::shared_ptr& arr);
+
+ARROW_EXPORT
+Result ExportDevice(const std::shared_ptr& t);
+
+} // namespace arrow::dlpack
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/c/dlpack_abi.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/c/dlpack_abi.h
new file mode 100644
index 0000000000000000000000000000000000000000..fbe2a56a344b373f3d3e950e434ba5392036a080
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/c/dlpack_abi.h
@@ -0,0 +1,321 @@
+// Taken from:
+// https://github.com/dmlc/dlpack/blob/ca4d00ad3e2e0f410eeab3264d21b8a39397f362/include/dlpack/dlpack.h
+/*!
+ * Copyright (c) 2017 by Contributors
+ * \file dlpack.h
+ * \brief The common header of DLPack.
+ */
+#ifndef DLPACK_DLPACK_H_
+#define DLPACK_DLPACK_H_
+
+/**
+ * \brief Compatibility with C++
+ */
+#ifdef __cplusplus
+# define DLPACK_EXTERN_C extern "C"
+#else
+# define DLPACK_EXTERN_C
+#endif
+
+/*! \brief The current major version of dlpack */
+#define DLPACK_MAJOR_VERSION 1
+
+/*! \brief The current minor version of dlpack */
+#define DLPACK_MINOR_VERSION 0
+
+/*! \brief DLPACK_DLL prefix for windows */
+#ifdef _WIN32
+# ifdef DLPACK_EXPORTS
+# define DLPACK_DLL __declspec(dllexport)
+# else
+# define DLPACK_DLL __declspec(dllimport)
+# endif
+#else
+# define DLPACK_DLL
+#endif
+
+#include
+#include
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*!
+ * \brief The DLPack version.
+ *
+ * A change in major version indicates that we have changed the
+ * data layout of the ABI - DLManagedTensorVersioned.
+ *
+ * A change in minor version indicates that we have added new
+ * code, such as a new device type, but the ABI is kept the same.
+ *
+ * If an obtained DLPack tensor has a major version that disagrees
+ * with the version number specified in this header file
+ * (i.e. major != DLPACK_MAJOR_VERSION), the consumer must call the deleter
+ * (and it is safe to do so). It is not safe to access any other fields
+ * as the memory layout will have changed.
+ *
+ * In the case of a minor version mismatch, the tensor can be safely used as
+ * long as the consumer knows how to interpret all fields. Minor version
+ * updates indicate the addition of enumeration values.
+ */
+typedef struct {
+ /*! \brief DLPack major version. */
+ uint32_t major;
+ /*! \brief DLPack minor version. */
+ uint32_t minor;
+} DLPackVersion;
+
+/*!
+ * \brief The device type in DLDevice.
+ */
+#ifdef __cplusplus
+typedef enum : int32_t {
+#else
+typedef enum {
+#endif
+ /*! \brief CPU device */
+ kDLCPU = 1,
+ /*! \brief CUDA GPU device */
+ kDLCUDA = 2,
+ /*!
+ * \brief Pinned CUDA CPU memory by cudaMallocHost
+ */
+ kDLCUDAHost = 3,
+ /*! \brief OpenCL devices. */
+ kDLOpenCL = 4,
+ /*! \brief Vulkan buffer for next generation graphics. */
+ kDLVulkan = 7,
+ /*! \brief Metal for Apple GPU. */
+ kDLMetal = 8,
+ /*! \brief Verilog simulator buffer */
+ kDLVPI = 9,
+ /*! \brief ROCm GPUs for AMD GPUs */
+ kDLROCM = 10,
+ /*!
+ * \brief Pinned ROCm CPU memory allocated by hipMallocHost
+ */
+ kDLROCMHost = 11,
+ /*!
+ * \brief Reserved extension device type,
+ * used for quickly test extension device
+ * The semantics can differ depending on the implementation.
+ */
+ kDLExtDev = 12,
+ /*!
+ * \brief CUDA managed/unified memory allocated by cudaMallocManaged
+ */
+ kDLCUDAManaged = 13,
+ /*!
+ * \brief Unified shared memory allocated on a oneAPI non-partititioned
+ * device. Call to oneAPI runtime is required to determine the device
+ * type, the USM allocation type and the sycl context it is bound to.
+ *
+ */
+ kDLOneAPI = 14,
+ /*! \brief GPU support for next generation WebGPU standard. */
+ kDLWebGPU = 15,
+ /*! \brief Qualcomm Hexagon DSP */
+ kDLHexagon = 16,
+} DLDeviceType;
+
+/*!
+ * \brief A Device for Tensor and operator.
+ */
+typedef struct {
+ /*! \brief The device type used in the device. */
+ DLDeviceType device_type;
+ /*!
+ * \brief The device index.
+ * For vanilla CPU memory, pinned memory, or managed memory, this is set to 0.
+ */
+ int32_t device_id;
+} DLDevice;
+
+/*!
+ * \brief The type code options DLDataType.
+ */
+typedef enum {
+ /*! \brief signed integer */
+ kDLInt = 0U,
+ /*! \brief unsigned integer */
+ kDLUInt = 1U,
+ /*! \brief IEEE floating point */
+ kDLFloat = 2U,
+ /*!
+ * \brief Opaque handle type, reserved for testing purposes.
+ * Frameworks need to agree on the handle data type for the exchange to be well-defined.
+ */
+ kDLOpaqueHandle = 3U,
+ /*! \brief bfloat16 */
+ kDLBfloat = 4U,
+ /*!
+ * \brief complex number
+ * (C/C++/Python layout: compact struct per complex number)
+ */
+ kDLComplex = 5U,
+ /*! \brief boolean */
+ kDLBool = 6U,
+} DLDataTypeCode;
+
+/*!
+ * \brief The data type the tensor can hold. The data type is assumed to follow the
+ * native endian-ness. An explicit error message should be raised when attempting to
+ * export an array with non-native endianness
+ *
+ * Examples
+ * - float: type_code = 2, bits = 32, lanes = 1
+ * - float4(vectorized 4 float): type_code = 2, bits = 32, lanes = 4
+ * - int8: type_code = 0, bits = 8, lanes = 1
+ * - std::complex: type_code = 5, bits = 64, lanes = 1
+ * - bool: type_code = 6, bits = 8, lanes = 1 (as per common array library convention,
+ * the underlying storage size of bool is 8 bits)
+ */
+typedef struct {
+ /*!
+ * \brief Type code of base types.
+ * We keep it uint8_t instead of DLDataTypeCode for minimal memory
+ * footprint, but the value should be one of DLDataTypeCode enum values.
+ * */
+ uint8_t code;
+ /*!
+ * \brief Number of bits, common choices are 8, 16, 32.
+ */
+ uint8_t bits;
+ /*! \brief Number of lanes in the type, used for vector types. */
+ uint16_t lanes;
+} DLDataType;
+
+/*!
+ * \brief Plain C Tensor object, does not manage memory.
+ */
+typedef struct {
+ /*!
+ * \brief The data pointer points to the allocated data. This will be CUDA
+ * device pointer or cl_mem handle in OpenCL. It may be opaque on some device
+ * types. This pointer is always aligned to 256 bytes as in CUDA. The
+ * `byte_offset` field should be used to point to the beginning of the data.
+ *
+ * Note that as of Nov 2021, multiply libraries (CuPy, PyTorch, TensorFlow,
+ * TVM, perhaps others) do not adhere to this 256 byte aligment requirement
+ * on CPU/CUDA/ROCm, and always use `byte_offset=0`. This must be fixed
+ * (after which this note will be updated); at the moment it is recommended
+ * to not rely on the data pointer being correctly aligned.
+ *
+ * For given DLTensor, the size of memory required to store the contents of
+ * data is calculated as follows:
+ *
+ * \code{.c}
+ * static inline size_t GetDataSize(const DLTensor* t) {
+ * size_t size = 1;
+ * for (tvm_index_t i = 0; i < t->ndim; ++i) {
+ * size *= t->shape[i];
+ * }
+ * size *= (t->dtype.bits * t->dtype.lanes + 7) / 8;
+ * return size;
+ * }
+ * \endcode
+ */
+ void* data;
+ /*! \brief The device of the tensor */
+ DLDevice device;
+ /*! \brief Number of dimensions */
+ int32_t ndim;
+ /*! \brief The data type of the pointer*/
+ DLDataType dtype;
+ /*! \brief The shape of the tensor */
+ int64_t* shape;
+ /*!
+ * \brief strides of the tensor (in number of elements, not bytes)
+ * can be NULL, indicating tensor is compact and row-majored.
+ */
+ int64_t* strides;
+ /*! \brief The offset in bytes to the beginning pointer to data */
+ uint64_t byte_offset;
+} DLTensor;
+
+/*!
+ * \brief C Tensor object, manage memory of DLTensor. This data structure is
+ * intended to facilitate the borrowing of DLTensor by another framework. It is
+ * not meant to transfer the tensor. When the borrowing framework doesn't need
+ * the tensor, it should call the deleter to notify the host that the resource
+ * is no longer needed.
+ *
+ * \note This data structure is used as Legacy DLManagedTensor
+ * in DLPack exchange and is deprecated after DLPack v0.8
+ * Use DLManagedTensorVersioned instead.
+ * This data structure may get renamed or deleted in future versions.
+ *
+ * \sa DLManagedTensorVersioned
+ */
+typedef struct DLManagedTensor {
+ /*! \brief DLTensor which is being memory managed */
+ DLTensor dl_tensor;
+ /*! \brief the context of the original host framework of DLManagedTensor in
+ * which DLManagedTensor is used in the framework. It can also be NULL.
+ */
+ void* manager_ctx;
+ /*!
+ * \brief Destructor - this should be called
+ * to destruct the manager_ctx which backs the DLManagedTensor. It can be
+ * NULL if there is no way for the caller to provide a reasonable destructor.
+ * The destructors deletes the argument self as well.
+ */
+ void (*deleter)(struct DLManagedTensor* self);
+} DLManagedTensor;
+
+// bit masks used in in the DLManagedTensorVersioned
+
+/*! \brief bit mask to indicate that the tensor is read only. */
+#define DLPACK_FLAG_BITMASK_READ_ONLY (1UL << 0UL)
+
+/*!
+ * \brief A versioned and managed C Tensor object, manage memory of DLTensor.
+ *
+ * This data structure is intended to facilitate the borrowing of DLTensor by
+ * another framework. It is not meant to transfer the tensor. When the borrowing
+ * framework doesn't need the tensor, it should call the deleter to notify the
+ * host that the resource is no longer needed.
+ *
+ * \note This is the current standard DLPack exchange data structure.
+ */
+struct DLManagedTensorVersioned {
+ /*!
+ * \brief The API and ABI version of the current managed Tensor
+ */
+ DLPackVersion version;
+ /*!
+ * \brief the context of the original host framework.
+ *
+ * Stores DLManagedTensorVersioned is used in the
+ * framework. It can also be NULL.
+ */
+ void* manager_ctx;
+ /*!
+ * \brief Destructor.
+ *
+ * This should be called to destruct manager_ctx which holds the
+ * DLManagedTensorVersioned. It can be NULL if there is no way for the caller to provide
+ * a reasonable destructor. The destructors deletes the argument self as well.
+ */
+ void (*deleter)(struct DLManagedTensorVersioned* self);
+ /*!
+ * \brief Additional bitmask flags information about the tensor.
+ *
+ * By default the flags should be set to 0.
+ *
+ * \note Future ABI changes should keep everything until this field
+ * stable, to ensure that deleter can be correctly called.
+ *
+ * \sa DLPACK_FLAG_BITMASK_READ_ONLY
+ */
+ uint64_t flags;
+ /*! \brief DLTensor which is being memory managed */
+ DLTensor dl_tensor;
+};
+
+#ifdef __cplusplus
+} // DLPACK_EXTERN_C
+#endif
+#endif // DLPACK_DLPACK_H_
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/c/helpers.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/c/helpers.h
new file mode 100644
index 0000000000000000000000000000000000000000..6e4df17f43ebfe238484056fedbd4e6d575460f0
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/c/helpers.h
@@ -0,0 +1,178 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include
+#include
+#include
+#include
+
+#include "arrow/c/abi.h"
+
+#define ARROW_C_ASSERT(condition, msg) \
+ do { \
+ if (!(condition)) { \
+ fprintf(stderr, "%s:%d:: %s", __FILE__, __LINE__, (msg)); \
+ abort(); \
+ } \
+ } while (0)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/// Query whether the C schema is released
+inline int ArrowSchemaIsReleased(const struct ArrowSchema* schema) {
+ return schema->release == NULL;
+}
+
+/// Mark the C schema released (for use in release callbacks)
+inline void ArrowSchemaMarkReleased(struct ArrowSchema* schema) {
+ schema->release = NULL;
+}
+
+/// Move the C schema from `src` to `dest`
+///
+/// Note `dest` must *not* point to a valid schema already, otherwise there
+/// will be a memory leak.
+inline void ArrowSchemaMove(struct ArrowSchema* src, struct ArrowSchema* dest) {
+ assert(dest != src);
+ assert(!ArrowSchemaIsReleased(src));
+ memcpy(dest, src, sizeof(struct ArrowSchema));
+ ArrowSchemaMarkReleased(src);
+}
+
+/// Release the C schema, if necessary, by calling its release callback
+inline void ArrowSchemaRelease(struct ArrowSchema* schema) {
+ if (!ArrowSchemaIsReleased(schema)) {
+ schema->release(schema);
+ ARROW_C_ASSERT(ArrowSchemaIsReleased(schema),
+ "ArrowSchemaRelease did not cleanup release callback");
+ }
+}
+
+/// Query whether the C array is released
+inline int ArrowArrayIsReleased(const struct ArrowArray* array) {
+ return array->release == NULL;
+}
+
+inline int ArrowDeviceArrayIsReleased(const struct ArrowDeviceArray* array) {
+ return ArrowArrayIsReleased(&array->array);
+}
+
+/// Mark the C array released (for use in release callbacks)
+inline void ArrowArrayMarkReleased(struct ArrowArray* array) { array->release = NULL; }
+
+inline void ArrowDeviceArrayMarkReleased(struct ArrowDeviceArray* array) {
+ ArrowArrayMarkReleased(&array->array);
+}
+
+/// Move the C array from `src` to `dest`
+///
+/// Note `dest` must *not* point to a valid array already, otherwise there
+/// will be a memory leak.
+inline void ArrowArrayMove(struct ArrowArray* src, struct ArrowArray* dest) {
+ assert(dest != src);
+ assert(!ArrowArrayIsReleased(src));
+ memcpy(dest, src, sizeof(struct ArrowArray));
+ ArrowArrayMarkReleased(src);
+}
+
+inline void ArrowDeviceArrayMove(struct ArrowDeviceArray* src,
+ struct ArrowDeviceArray* dest) {
+ assert(dest != src);
+ assert(!ArrowDeviceArrayIsReleased(src));
+ memcpy(dest, src, sizeof(struct ArrowDeviceArray));
+ ArrowDeviceArrayMarkReleased(src);
+}
+
+/// Release the C array, if necessary, by calling its release callback
+inline void ArrowArrayRelease(struct ArrowArray* array) {
+ if (!ArrowArrayIsReleased(array)) {
+ array->release(array);
+ ARROW_C_ASSERT(ArrowArrayIsReleased(array),
+ "ArrowArrayRelease did not cleanup release callback");
+ }
+}
+
+inline void ArrowDeviceArrayRelease(struct ArrowDeviceArray* array) {
+ if (!ArrowDeviceArrayIsReleased(array)) {
+ array->array.release(&array->array);
+ ARROW_C_ASSERT(ArrowDeviceArrayIsReleased(array),
+ "ArrowDeviceArrayRelease did not cleanup release callback");
+ }
+}
+
+/// Query whether the C array stream is released
+inline int ArrowArrayStreamIsReleased(const struct ArrowArrayStream* stream) {
+ return stream->release == NULL;
+}
+
+inline int ArrowDeviceArrayStreamIsReleased(const struct ArrowDeviceArrayStream* stream) {
+ return stream->release == NULL;
+}
+
+/// Mark the C array stream released (for use in release callbacks)
+inline void ArrowArrayStreamMarkReleased(struct ArrowArrayStream* stream) {
+ stream->release = NULL;
+}
+
+inline void ArrowDeviceArrayStreamMarkReleased(struct ArrowDeviceArrayStream* stream) {
+ stream->release = NULL;
+}
+
+/// Move the C array stream from `src` to `dest`
+///
+/// Note `dest` must *not* point to a valid stream already, otherwise there
+/// will be a memory leak.
+inline void ArrowArrayStreamMove(struct ArrowArrayStream* src,
+ struct ArrowArrayStream* dest) {
+ assert(dest != src);
+ assert(!ArrowArrayStreamIsReleased(src));
+ memcpy(dest, src, sizeof(struct ArrowArrayStream));
+ ArrowArrayStreamMarkReleased(src);
+}
+
+inline void ArrowDeviceArrayStreamMove(struct ArrowDeviceArrayStream* src,
+ struct ArrowDeviceArrayStream* dest) {
+ assert(dest != src);
+ assert(!ArrowDeviceArrayStreamIsReleased(src));
+ memcpy(dest, src, sizeof(struct ArrowDeviceArrayStream));
+ ArrowDeviceArrayStreamMarkReleased(src);
+}
+
+/// Release the C array stream, if necessary, by calling its release callback
+inline void ArrowArrayStreamRelease(struct ArrowArrayStream* stream) {
+ if (!ArrowArrayStreamIsReleased(stream)) {
+ stream->release(stream);
+ ARROW_C_ASSERT(ArrowArrayStreamIsReleased(stream),
+ "ArrowArrayStreamRelease did not cleanup release callback");
+ }
+}
+
+inline void ArrowDeviceArrayStreamRelease(struct ArrowDeviceArrayStream* stream) {
+ if (!ArrowDeviceArrayStreamIsReleased(stream)) {
+ stream->release(stream);
+ ARROW_C_ASSERT(ArrowDeviceArrayStreamIsReleased(stream),
+ "ArrowDeviceArrayStreamRelease did not cleanup release callback");
+ }
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/row/grouper.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/row/grouper.h
new file mode 100644
index 0000000000000000000000000000000000000000..9424559385b7391d4dc7d46ddbbb542803c9001e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/compute/row/grouper.h
@@ -0,0 +1,198 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include
+#include
+
+#include "arrow/compute/kernel.h"
+#include "arrow/compute/visibility.h"
+#include "arrow/datum.h"
+#include "arrow/result.h"
+#include "arrow/util/visibility.h"
+
+namespace arrow {
+namespace compute {
+
+/// \brief A segment
+/// A segment group is a chunk of continuous rows that have the same segment key. (For
+/// example, in ordered time series processing, segment key can be "date", and a segment
+/// group can be all the rows that belong to the same date.) A segment group can span
+/// across multiple exec batches. A segment is a chunk of continuous rows that has the
+/// same segment key within a given batch. When a segment group span cross batches, it
+/// will have multiple segments. A segment never spans cross batches. The segment data
+/// structure only makes sense when used along with a exec batch.
+struct ARROW_COMPUTE_EXPORT Segment {
+ /// \brief the offset into the batch where the segment starts
+ int64_t offset;
+ /// \brief the length of the segment
+ int64_t length;
+ /// \brief whether the segment may be extended by a next one
+ bool is_open;
+ /// \brief whether the segment extends a preceeding one
+ bool extends;
+};
+
+inline bool operator==(const Segment& segment1, const Segment& segment2) {
+ return segment1.offset == segment2.offset && segment1.length == segment2.length &&
+ segment1.is_open == segment2.is_open && segment1.extends == segment2.extends;
+}
+inline bool operator!=(const Segment& segment1, const Segment& segment2) {
+ return !(segment1 == segment2);
+}
+
+/// \brief a helper class to divide a batch into segments of equal values
+///
+/// For example, given a batch with two columns specifed as segment keys:
+///
+/// A A [other columns]...
+/// A A ...
+/// A B ...
+/// A B ...
+/// A A ...
+///
+/// Then the batch could be divided into 3 segments. The first would be rows 0 & 1,
+/// the second would be rows 2 & 3, and the third would be row 4.
+///
+/// Further, a segmenter keeps track of the last value seen. This allows it to calculate
+/// segments which span batches. In our above example the last batch we emit would set
+/// the "open" flag, which indicates whether the segment may extend into the next batch.
+///
+/// If the next call to the segmenter starts with `A A` then that segment would set the
+/// "extends" flag, which indicates whether the segment continues the last open batch.
+class ARROW_COMPUTE_EXPORT RowSegmenter {
+ public:
+ virtual ~RowSegmenter() = default;
+
+ /// \brief Construct a Segmenter which segments on the specified key types
+ ///
+ /// \param[in] key_types the specified key types
+ /// \param[in] nullable_keys whether values of the specified keys may be null
+ /// \param[in] ctx the execution context to use
+ static Result> Make(
+ const std::vector& key_types, bool nullable_keys, ExecContext* ctx);
+
+ /// \brief Return the key types of this segmenter
+ virtual const std::vector& key_types() const = 0;
+
+ /// \brief Reset this segmenter
+ ///
+ /// A segmenter normally extends (see `Segment`) a segment from one batch to the next.
+ /// If segment-extension is undesirable, for example when each batch is processed
+ /// independently, then `Reset` should be invoked before processing the next batch.
+ virtual Status Reset() = 0;
+
+ /// \brief Get all segments for the given batch
+ virtual Result> GetSegments(const ExecSpan& batch) = 0;
+};
+
+/// Consumes batches of keys and yields batches of the group ids.
+class ARROW_COMPUTE_EXPORT Grouper {
+ public:
+ virtual ~Grouper() = default;
+
+ /// Construct a Grouper which receives the specified key types
+ static Result> Make(const std::vector& key_types,
+ ExecContext* ctx = default_exec_context());
+
+ /// Reset all intermediate state, make the grouper logically as just `Make`ed.
+ /// The underlying buffers, if any, may or may not be released though.
+ virtual Status Reset() = 0;
+
+ /// Consume a batch of keys, producing the corresponding group ids as an integer array,
+ /// over a slice defined by an offset and length, which defaults to the batch length.
+ /// Currently only uint32 indices will be produced, eventually the bit width will only
+ /// be as wide as necessary.
+ virtual Result Consume(const ExecSpan& batch, int64_t offset = 0,
+ int64_t length = -1) = 0;
+
+ /// Like Consume, but groups not already encountered emit null instead of
+ /// generating a new group id.
+ virtual Result Lookup(const ExecSpan& batch, int64_t offset = 0,
+ int64_t length = -1) = 0;
+
+ /// Like Consume, but only populates the Grouper without returning the group ids.
+ virtual Status Populate(const ExecSpan& batch, int64_t offset = 0,
+ int64_t length = -1) = 0;
+
+ /// Get current unique keys. May be called multiple times.
+ virtual Result GetUniques() = 0;
+
+ /// Get the current number of groups.
+ virtual uint32_t num_groups() const = 0;
+
+ /// \brief Assemble lists of indices of identical elements.
+ ///
+ /// \param[in] ids An unsigned, all-valid integral array which will be
+ /// used as grouping criteria.
+ /// \param[in] num_groups An upper bound for the elements of ids
+ /// \param[in] ctx Execution context to use during the operation
+ /// \return A num_groups-long ListArray where the slot at i contains a
+ /// list of indices where i appears in ids.
+ ///
+ /// MakeGroupings([
+ /// 2,
+ /// 2,
+ /// 5,
+ /// 5,
+ /// 2,
+ /// 3
+ /// ], 8) == [
+ /// [],
+ /// [],
+ /// [0, 1, 4],
+ /// [5],
+ /// [],
+ /// [2, 3],
+ /// [],
+ /// []
+ /// ]
+ static Result> MakeGroupings(
+ const UInt32Array& ids, uint32_t num_groups,
+ ExecContext* ctx = default_exec_context());
+
+ /// \brief Produce a ListArray whose slots are selections of `array` which correspond to
+ /// the provided groupings.
+ ///
+ /// For example,
+ /// ApplyGroupings([
+ /// [],
+ /// [],
+ /// [0, 1, 4],
+ /// [5],
+ /// [],
+ /// [2, 3],
+ /// [],
+ /// []
+ /// ], [2, 2, 5, 5, 2, 3]) == [
+ /// [],
+ /// [],
+ /// [2, 2, 2],
+ /// [3],
+ /// [],
+ /// [5, 5],
+ /// [],
+ /// []
+ /// ]
+ static Result> ApplyGroupings(
+ const ListArray& groupings, const Array& array,
+ ExecContext* ctx = default_exec_context());
+};
+
+} // namespace compute
+} // namespace arrow
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/api.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/api.h
new file mode 100644
index 0000000000000000000000000000000000000000..4af1835cd709d43e0abe3b39b46531cae9a047fc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/api.h
@@ -0,0 +1,22 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include "arrow/csv/options.h"
+#include "arrow/csv/reader.h"
+#include "arrow/csv/writer.h"
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/chunker.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/chunker.h
new file mode 100644
index 0000000000000000000000000000000000000000..662b16ec40a9485547ce01b32ea0325a23122711
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/chunker.h
@@ -0,0 +1,36 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include
+#include
+
+#include "arrow/csv/options.h"
+#include "arrow/status.h"
+#include "arrow/util/delimiting.h"
+#include "arrow/util/macros.h"
+#include "arrow/util/visibility.h"
+
+namespace arrow {
+namespace csv {
+
+ARROW_EXPORT
+std::unique_ptr MakeChunker(const ParseOptions& options);
+
+} // namespace csv
+} // namespace arrow
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/column_builder.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/column_builder.h
new file mode 100644
index 0000000000000000000000000000000000000000..9fc4643d9d4c3d4cccff7f9d179e62b5f720ac6f
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/column_builder.h
@@ -0,0 +1,78 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include
+#include
+#include
+
+#include "arrow/result.h"
+#include "arrow/type_fwd.h"
+#include "arrow/util/type_fwd.h"
+#include "arrow/util/visibility.h"
+
+namespace arrow {
+namespace csv {
+
+class BlockParser;
+struct ConvertOptions;
+
+class ARROW_EXPORT ColumnBuilder {
+ public:
+ virtual ~ColumnBuilder() = default;
+
+ /// Spawn a task that will try to convert and append the given CSV block.
+ /// All calls to Append() should happen on the same thread, otherwise
+ /// call Insert() instead.
+ virtual void Append(const std::shared_ptr& parser) = 0;
+
+ /// Spawn a task that will try to convert and insert the given CSV block
+ virtual void Insert(int64_t block_index,
+ const std::shared_ptr& parser) = 0;
+
+ /// Return the final chunked array. The TaskGroup _must_ have finished!
+ virtual Result> Finish() = 0;
+
+ std::shared_ptr task_group() { return task_group_; }
+
+ /// Construct a strictly-typed ColumnBuilder.
+ static Result> Make(
+ MemoryPool* pool, const std::shared_ptr& type, int32_t col_index,
+ std::shared_ptr options,
+ std::shared_ptr task_group);
+
+ /// Construct a type-inferring ColumnBuilder.
+ static Result> Make(
+ MemoryPool* pool, int32_t col_index, std::shared_ptr options,
+ std::shared_ptr task_group);
+
+ /// Construct a ColumnBuilder for a column of nulls
+ /// (i.e. not present in the CSV file).
+ static Result> MakeNull(
+ MemoryPool* pool, const std::shared_ptr& type,
+ std::shared_ptr task_group);
+
+ protected:
+ explicit ColumnBuilder(std::shared_ptr task_group)
+ : task_group_(std::move(task_group)) {}
+
+ std::shared_ptr task_group_;
+};
+
+} // namespace csv
+} // namespace arrow
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/column_decoder.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/column_decoder.h
new file mode 100644
index 0000000000000000000000000000000000000000..5fbbd5df58b1c588b88e16b68da50b9399211abc
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/column_decoder.h
@@ -0,0 +1,64 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include
+#include
+#include
+
+#include "arrow/result.h"
+#include "arrow/type_fwd.h"
+#include "arrow/util/type_fwd.h"
+#include "arrow/util/visibility.h"
+
+namespace arrow {
+namespace csv {
+
+class BlockParser;
+struct ConvertOptions;
+
+class ARROW_EXPORT ColumnDecoder {
+ public:
+ virtual ~ColumnDecoder() = default;
+
+ /// Spawn a task that will try to convert and insert the given CSV block
+ virtual Future> Decode(
+ const std::shared_ptr& parser) = 0;
+
+ /// Construct a strictly-typed ColumnDecoder.
+ static Result> Make(MemoryPool* pool,
+ std::shared_ptr type,
+ int32_t col_index,
+ const ConvertOptions& options);
+
+ /// Construct a type-inferring ColumnDecoder.
+ /// Inference will run only on the first block, the type will be frozen afterwards.
+ static Result> Make(MemoryPool* pool, int32_t col_index,
+ const ConvertOptions& options);
+
+ /// Construct a ColumnDecoder for a column of nulls
+ /// (i.e. not present in the CSV file).
+ static Result> MakeNull(MemoryPool* pool,
+ std::shared_ptr type);
+
+ protected:
+ ColumnDecoder() = default;
+};
+
+} // namespace csv
+} // namespace arrow
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/converter.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/converter.h
new file mode 100644
index 0000000000000000000000000000000000000000..639f692f26a1ba3a134caac68a432ac22f068917
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/converter.h
@@ -0,0 +1,82 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include
+#include
+
+#include "arrow/csv/options.h"
+#include "arrow/result.h"
+#include "arrow/type_fwd.h"
+#include "arrow/util/macros.h"
+#include "arrow/util/visibility.h"
+
+namespace arrow {
+namespace csv {
+
+class BlockParser;
+
+class ARROW_EXPORT Converter {
+ public:
+ Converter(const std::shared_ptr& type, const ConvertOptions& options,
+ MemoryPool* pool);
+ virtual ~Converter() = default;
+
+ virtual Result> Convert(const BlockParser& parser,
+ int32_t col_index) = 0;
+
+ std::shared_ptr type() const { return type_; }
+
+ // Create a Converter for the given data type
+ static Result> Make(
+ const std::shared_ptr& type, const ConvertOptions& options,
+ MemoryPool* pool = default_memory_pool());
+
+ protected:
+ ARROW_DISALLOW_COPY_AND_ASSIGN(Converter);
+
+ virtual Status Initialize() = 0;
+
+ // CAUTION: ConvertOptions can grow large (if it customizes hundreds or
+ // thousands of columns), so avoid copying it in each Converter.
+ const ConvertOptions& options_;
+ MemoryPool* pool_;
+ std::shared_ptr type_;
+};
+
+class ARROW_EXPORT DictionaryConverter : public Converter {
+ public:
+ DictionaryConverter(const std::shared_ptr& value_type,
+ const ConvertOptions& options, MemoryPool* pool);
+
+ // If the dictionary length goes above this value, conversion will fail
+ // with Status::IndexError.
+ virtual void SetMaxCardinality(int32_t max_length) = 0;
+
+ // Create a Converter for the given dictionary value type.
+ // The dictionary index type will always be Int32.
+ static Result> Make(
+ const std::shared_ptr& value_type, const ConvertOptions& options,
+ MemoryPool* pool = default_memory_pool());
+
+ protected:
+ std::shared_ptr value_type_;
+};
+
+} // namespace csv
+} // namespace arrow
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/invalid_row.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/invalid_row.h
new file mode 100644
index 0000000000000000000000000000000000000000..4360ceaaea6ac07dd218c93ce13c3ab14c16fc63
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/invalid_row.h
@@ -0,0 +1,55 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include
+#include
+
+namespace arrow {
+namespace csv {
+
+/// \brief Description of an invalid row
+struct InvalidRow {
+ /// \brief Number of columns expected in the row
+ int32_t expected_columns;
+ /// \brief Actual number of columns found in the row
+ int32_t actual_columns;
+ /// \brief The physical row number if known or -1
+ ///
+ /// This number is one-based and also accounts for non-data rows (such as
+ /// CSV header rows).
+ int64_t number;
+ /// \brief View of the entire row. Memory will be freed after callback returns
+ const std::string_view text;
+};
+
+/// \brief Result returned by an InvalidRowHandler
+enum class InvalidRowResult {
+ // Generate an error describing this row
+ Error,
+ // Skip over this row
+ Skip
+};
+
+/// \brief callback for handling a row with an invalid number of columns while parsing
+/// \return result indicating if an error should be returned from the parser or the row is
+/// skipped
+using InvalidRowHandler = std::function;
+
+} // namespace csv
+} // namespace arrow
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/options.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/options.h
new file mode 100644
index 0000000000000000000000000000000000000000..10e55bf838c33f00ab520bce7f4e145a7db8819a
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/options.h
@@ -0,0 +1,226 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include
+#include
+#include
+#include
+#include
+
+#include "arrow/csv/invalid_row.h"
+#include "arrow/csv/type_fwd.h"
+#include "arrow/io/interfaces.h"
+#include "arrow/status.h"
+#include "arrow/util/visibility.h"
+
+namespace arrow {
+
+class DataType;
+class TimestampParser;
+
+namespace csv {
+
+// Silly workaround for https://github.com/michaeljones/breathe/issues/453
+constexpr char kDefaultEscapeChar = '\\';
+
+struct ARROW_EXPORT ParseOptions {
+ // Parsing options
+
+ /// Field delimiter
+ char delimiter = ',';
+ /// Whether quoting is used
+ bool quoting = true;
+ /// Quoting character (if `quoting` is true)
+ char quote_char = '"';
+ /// Whether a quote inside a value is double-quoted
+ bool double_quote = true;
+ /// Whether escaping is used
+ bool escaping = false;
+ /// Escaping character (if `escaping` is true)
+ char escape_char = kDefaultEscapeChar;
+ /// Whether values are allowed to contain CR (0x0d) and LF (0x0a) characters
+ bool newlines_in_values = false;
+ /// Whether empty lines are ignored. If false, an empty line represents
+ /// a single empty value (assuming a one-column CSV file).
+ bool ignore_empty_lines = true;
+ /// A handler function for rows which do not have the correct number of columns
+ InvalidRowHandler invalid_row_handler;
+
+ /// Create parsing options with default values
+ static ParseOptions Defaults();
+
+ /// \brief Test that all set options are valid
+ Status Validate() const;
+};
+
+struct ARROW_EXPORT ConvertOptions {
+ // Conversion options
+
+ /// Whether to check UTF8 validity of string columns
+ bool check_utf8 = true;
+ /// Optional per-column types (disabling type inference on those columns)
+ std::unordered_map> column_types;
+ /// Recognized spellings for null values
+ std::vector null_values;
+ /// Recognized spellings for boolean true values
+ std::vector true_values;
+ /// Recognized spellings for boolean false values
+ std::vector false_values;
+
+ /// Whether string / binary columns can have null values.
+ ///
+ /// If true, then strings in "null_values" are considered null for string columns.
+ /// If false, then all strings are valid string values.
+ bool strings_can_be_null = false;
+
+ /// Whether quoted values can be null.
+ ///
+ /// If true, then strings in "null_values" are also considered null when they
+ /// appear quoted in the CSV file. Otherwise, quoted values are never considered null.
+ bool quoted_strings_can_be_null = true;
+
+ /// Whether to try to automatically dict-encode string / binary data.
+ /// If true, then when type inference detects a string or binary column,
+ /// it is dict-encoded up to `auto_dict_max_cardinality` distinct values
+ /// (per chunk), after which it switches to regular encoding.
+ ///
+ /// This setting is ignored for non-inferred columns (those in `column_types`).
+ bool auto_dict_encode = false;
+ int32_t auto_dict_max_cardinality = 50;
+
+ /// Decimal point character for floating-point and decimal data
+ char decimal_point = '.';
+
+ // XXX Should we have a separate FilterOptions?
+
+ /// If non-empty, indicates the names of columns from the CSV file that should
+ /// be actually read and converted (in the vector's order).
+ /// Columns not in this vector will be ignored.
+ std::vector include_columns;
+ /// If false, columns in `include_columns` but not in the CSV file will error out.
+ /// If true, columns in `include_columns` but not in the CSV file will produce
+ /// a column of nulls (whose type is selected using `column_types`,
+ /// or null by default)
+ /// This option is ignored if `include_columns` is empty.
+ bool include_missing_columns = false;
+
+ /// User-defined timestamp parsers, using the virtual parser interface in
+ /// arrow/util/value_parsing.h. More than one parser can be specified, and
+ /// the CSV conversion logic will try parsing values starting from the
+ /// beginning of this vector. If no parsers are specified, we use the default
+ /// built-in ISO-8601 parser.
+ std::vector> timestamp_parsers;
+
+ /// Create conversion options with default values, including conventional
+ /// values for `null_values`, `true_values` and `false_values`
+ static ConvertOptions Defaults();
+
+ /// \brief Test that all set options are valid
+ Status Validate() const;
+};
+
+struct ARROW_EXPORT ReadOptions {
+ // Reader options
+
+ /// Whether to use the global CPU thread pool
+ bool use_threads = true;
+
+ /// \brief Block size we request from the IO layer.
+ ///
+ /// This will determine multi-threading granularity as well as
+ /// the size of individual record batches.
+ /// Minimum valid value for block size is 1
+ int32_t block_size = 1 << 20; // 1 MB
+
+ /// Number of header rows to skip (not including the row of column names, if any)
+ int32_t skip_rows = 0;
+
+ /// Number of rows to skip after the column names are read, if any
+ int32_t skip_rows_after_names = 0;
+
+ /// Column names for the target table.
+ /// If empty, fall back on autogenerate_column_names.
+ std::vector column_names;
+
+ /// Whether to autogenerate column names if `column_names` is empty.
+ /// If true, column names will be of the form "f0", "f1"...
+ /// If false, column names will be read from the first CSV row after `skip_rows`.
+ bool autogenerate_column_names = false;
+
+ /// Create read options with default values
+ static ReadOptions Defaults();
+
+ /// \brief Test that all set options are valid
+ Status Validate() const;
+};
+
+/// \brief Quoting style for CSV writing
+enum class ARROW_EXPORT QuotingStyle {
+ /// Only enclose values in quotes which need them, because their CSV rendering can
+ /// contain quotes itself (e.g. strings or binary values)
+ Needed,
+ /// Enclose all valid values in quotes. Nulls are not quoted. May cause readers to
+ /// interpret all values as strings if schema is inferred.
+ AllValid,
+ /// Do not enclose any values in quotes. Prevents values from containing quotes ("),
+ /// cell delimiters (,) or line endings (\\r, \\n), (following RFC4180). If values
+ /// contain these characters, an error is caused when attempting to write.
+ None
+};
+
+struct ARROW_EXPORT WriteOptions {
+ /// Whether to write an initial header line with column names
+ bool include_header = true;
+
+ /// \brief Maximum number of rows processed at a time
+ ///
+ /// The CSV writer converts and writes data in batches of N rows.
+ /// This number can impact performance.
+ int32_t batch_size = 1024;
+
+ /// Field delimiter
+ char delimiter = ',';
+
+ /// \brief The string to write for null values. Quotes are not allowed in this string.
+ std::string null_string;
+
+ /// \brief IO context for writing.
+ io::IOContext io_context;
+
+ /// \brief The end of line character to use for ending rows
+ std::string eol = "\n";
+
+ /// \brief Quoting style
+ QuotingStyle quoting_style = QuotingStyle::Needed;
+
+ /// \brief Quoting style of header
+ ///
+ /// Note that `QuotingStyle::Needed` and `QuotingStyle::AllValid` have the same
+ /// effect of quoting all column names.
+ QuotingStyle quoting_header = QuotingStyle::Needed;
+
+ /// Create write options with default values
+ static WriteOptions Defaults();
+
+ /// \brief Test that all set options are valid
+ Status Validate() const;
+};
+
+} // namespace csv
+} // namespace arrow
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/parser.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/parser.h
new file mode 100644
index 0000000000000000000000000000000000000000..c73e52ce831ed95b4abe83084b483c15660bae7e
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/parser.h
@@ -0,0 +1,228 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "arrow/buffer.h"
+#include "arrow/csv/options.h"
+#include "arrow/csv/type_fwd.h"
+#include "arrow/status.h"
+#include "arrow/util/macros.h"
+#include "arrow/util/visibility.h"
+
+namespace arrow {
+
+class MemoryPool;
+
+namespace csv {
+
+/// Skip at most num_rows from the given input. The input pointer is updated
+/// and the number of actually skipped rows is returns (may be less than
+/// requested if the input is too short).
+ARROW_EXPORT
+int32_t SkipRows(const uint8_t* data, uint32_t size, int32_t num_rows,
+ const uint8_t** out_data);
+
+class BlockParserImpl;
+
+namespace detail {
+
+struct ParsedValueDesc {
+ uint32_t offset : 31;
+ bool quoted : 1;
+};
+
+class ARROW_EXPORT DataBatch {
+ public:
+ explicit DataBatch(int32_t num_cols) : num_cols_(num_cols) {}
+
+ /// \brief Return the number of parsed rows (not skipped)
+ int32_t num_rows() const { return num_rows_; }
+ /// \brief Return the number of parsed columns
+ int32_t num_cols() const { return num_cols_; }
+ /// \brief Return the total size in bytes of parsed data
+ uint32_t num_bytes() const { return parsed_size_; }
+ /// \brief Return the number of skipped rows
+ int32_t num_skipped_rows() const { return static_cast(skipped_rows_.size()); }
+
+ template
+ Status VisitColumn(int32_t col_index, int64_t first_row, Visitor&& visit) const {
+ using detail::ParsedValueDesc;
+
+ int32_t batch_row = 0;
+ for (size_t buf_index = 0; buf_index < values_buffers_.size(); ++buf_index) {
+ const auto& values_buffer = values_buffers_[buf_index];
+ const auto values = reinterpret_cast(values_buffer->data());
+ const auto max_pos =
+ static_cast(values_buffer->size() / sizeof(ParsedValueDesc)) - 1;
+ for (int32_t pos = col_index; pos < max_pos; pos += num_cols_, ++batch_row) {
+ auto start = values[pos].offset;
+ auto stop = values[pos + 1].offset;
+ auto quoted = values[pos + 1].quoted;
+ Status status = visit(parsed_ + start, stop - start, quoted);
+ if (ARROW_PREDICT_FALSE(!status.ok())) {
+ return DecorateWithRowNumber(std::move(status), first_row, batch_row);
+ }
+ }
+ }
+ return Status::OK();
+ }
+
+ template
+ Status VisitLastRow(Visitor&& visit) const {
+ using detail::ParsedValueDesc;
+
+ const auto& values_buffer = values_buffers_.back();
+ const auto values = reinterpret_cast(values_buffer->data());
+ const auto start_pos =
+ static_cast(values_buffer->size() / sizeof(ParsedValueDesc)) -
+ num_cols_ - 1;
+ for (int32_t col_index = 0; col_index < num_cols_; ++col_index) {
+ auto start = values[start_pos + col_index].offset;
+ auto stop = values[start_pos + col_index + 1].offset;
+ auto quoted = values[start_pos + col_index + 1].quoted;
+ ARROW_RETURN_NOT_OK(visit(parsed_ + start, stop - start, quoted));
+ }
+ return Status::OK();
+ }
+
+ protected:
+ Status DecorateWithRowNumber(Status&& status, int64_t first_row,
+ int32_t batch_row) const {
+ if (first_row >= 0) {
+ // `skipped_rows_` is in ascending order by construction, so use bisection
+ // to find out how many rows were skipped before `batch_row`.
+ const auto skips_before =
+ std::upper_bound(skipped_rows_.begin(), skipped_rows_.end(), batch_row) -
+ skipped_rows_.begin();
+ status = status.WithMessage("Row #", batch_row + skips_before + first_row, ": ",
+ status.message());
+ }
+ // Use return_if so that when extra context is enabled it will be added
+ ARROW_RETURN_IF_(true, std::move(status), ARROW_STRINGIFY(status));
+ return std::move(status);
+ }
+
+ // The number of rows in this batch (not including any skipped ones)
+ int32_t num_rows_ = 0;
+ // The number of columns
+ int32_t num_cols_ = 0;
+
+ // XXX should we ensure the parsed buffer is padded with 8 or 16 excess zero bytes?
+ // It may help with null parsing...
+ std::vector> values_buffers_;
+ std::shared_ptr parsed_buffer_;
+ const uint8_t* parsed_ = NULLPTR;
+ int32_t parsed_size_ = 0;
+
+ // Record the current num_rows_ each time a row is skipped
+ std::vector skipped_rows_;
+
+ friend class ::arrow::csv::BlockParserImpl;
+};
+
+} // namespace detail
+
+constexpr int32_t kMaxParserNumRows = 100000;
+
+/// \class BlockParser
+/// \brief A reusable block-based parser for CSV data
+///
+/// The parser takes a block of CSV data and delimits rows and fields,
+/// unquoting and unescaping them on the fly. Parsed data is own by the
+/// parser, so the original buffer can be discarded after Parse() returns.
+///
+/// If the block is truncated (i.e. not all data can be parsed), it is up
+/// to the caller to arrange the next block to start with the trailing data.
+/// Also, if the previous block ends with CR (0x0d) and a new block starts
+/// with LF (0x0a), the parser will consider the leading newline as an empty
+/// line; the caller should therefore strip it.
+class ARROW_EXPORT BlockParser {
+ public:
+ explicit BlockParser(ParseOptions options, int32_t num_cols = -1,
+ int64_t first_row = -1, int32_t max_num_rows = kMaxParserNumRows);
+ explicit BlockParser(MemoryPool* pool, ParseOptions options, int32_t num_cols = -1,
+ int64_t first_row = -1, int32_t max_num_rows = kMaxParserNumRows);
+ ~BlockParser();
+
+ /// \brief Parse a block of data
+ ///
+ /// Parse a block of CSV data, ingesting up to max_num_rows rows.
+ /// The number of bytes actually parsed is returned in out_size.
+ Status Parse(std::string_view data, uint32_t* out_size);
+
+ /// \brief Parse sequential blocks of data
+ ///
+ /// Only the last block is allowed to be truncated.
+ Status Parse(const std::vector& data, uint32_t* out_size);
+
+ /// \brief Parse the final block of data
+ ///
+ /// Like Parse(), but called with the final block in a file.
+ /// The last row may lack a trailing line separator.
+ Status ParseFinal(std::string_view data, uint32_t* out_size);
+
+ /// \brief Parse the final sequential blocks of data
+ ///
+ /// Only the last block is allowed to be truncated.
+ Status ParseFinal(const std::vector& data, uint32_t* out_size);
+
+ /// \brief Return the number of parsed rows
+ int32_t num_rows() const { return parsed_batch().num_rows(); }
+ /// \brief Return the number of parsed columns
+ int32_t num_cols() const { return parsed_batch().num_cols(); }
+ /// \brief Return the total size in bytes of parsed data
+ uint32_t num_bytes() const { return parsed_batch().num_bytes(); }
+
+ /// \brief Return the total number of rows including rows which were skipped
+ int32_t total_num_rows() const {
+ return parsed_batch().num_rows() + parsed_batch().num_skipped_rows();
+ }
+
+ /// \brief Return the row number of the first row in the block or -1 if unsupported
+ int64_t first_row_num() const;
+
+ /// \brief Visit parsed values in a column
+ ///
+ /// The signature of the visitor is
+ /// Status(const uint8_t* data, uint32_t size, bool quoted)
+ template
+ Status VisitColumn(int32_t col_index, Visitor&& visit) const {
+ return parsed_batch().VisitColumn(col_index, first_row_num(),
+ std::forward(visit));
+ }
+
+ template
+ Status VisitLastRow(Visitor&& visit) const {
+ return parsed_batch().VisitLastRow(std::forward(visit));
+ }
+
+ protected:
+ std::unique_ptr impl_;
+
+ const detail::DataBatch& parsed_batch() const;
+};
+
+} // namespace csv
+} // namespace arrow
diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/reader.h b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/reader.h
new file mode 100644
index 0000000000000000000000000000000000000000..bae301dc14815a6fdf9388a08c4f9068155f20a6
--- /dev/null
+++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/pyarrow/include/arrow/csv/reader.h
@@ -0,0 +1,112 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include
+
+#include "arrow/csv/options.h" // IWYU pragma: keep
+#include "arrow/io/interfaces.h"
+#include "arrow/record_batch.h"
+#include "arrow/result.h"
+#include "arrow/type.h"
+#include "arrow/type_fwd.h"
+#include "arrow/util/future.h"
+#include "arrow/util/thread_pool.h"
+#include "arrow/util/visibility.h"
+
+namespace arrow {
+namespace io {
+class InputStream;
+} // namespace io
+
+namespace csv {
+
+/// A class that reads an entire CSV file into a Arrow Table
+class ARROW_EXPORT TableReader {
+ public:
+ virtual ~TableReader() = default;
+
+ /// Read the entire CSV file and convert it to a Arrow Table
+ virtual Result> Read() = 0;
+ /// Read the entire CSV file and convert it to a Arrow Table
+ virtual Future> ReadAsync() = 0;
+
+ /// Create a TableReader instance
+ static Result> Make(io::IOContext io_context,
+ std::shared_ptr input,
+ const ReadOptions&,
+ const ParseOptions&,
+ const ConvertOptions&);
+};
+
+/// \brief A class that reads a CSV file incrementally
+///
+/// Caveats:
+/// - For now, this is always single-threaded (regardless of `ReadOptions::use_threads`.
+/// - Type inference is done on the first block and types are frozen afterwards;
+/// to make sure the right data types are inferred, either set
+/// `ReadOptions::block_size` to a large enough value, or use
+/// `ConvertOptions::column_types` to set the desired data types explicitly.
+class ARROW_EXPORT StreamingReader : public RecordBatchReader {
+ public:
+ virtual ~StreamingReader() = default;
+
+ virtual Future> ReadNextAsync() = 0;
+
+ /// \brief Return the number of bytes which have been read and processed
+ ///
+ /// The returned number includes CSV bytes which the StreamingReader has
+ /// finished processing, but not bytes for which some processing (e.g.
+ /// CSV parsing or conversion to Arrow layout) is still ongoing.
+ ///
+ /// Furthermore, the following rules apply:
+ /// - bytes skipped by `ReadOptions.skip_rows` are counted as being read before
+ /// any records are returned.
+ /// - bytes read while parsing the header are counted as being read before any
+ /// records are returned.
+ /// - bytes skipped by `ReadOptions.skip_rows_after_names` are counted after the
+ /// first batch is returned.
+ virtual int64_t bytes_read() const = 0;
+
+ /// Create a StreamingReader instance
+ ///
+ /// This involves some I/O as the first batch must be loaded during the creation process
+ /// so it is returned as a future
+ ///
+ /// Currently, the StreamingReader is not async-reentrant and does not do any fan-out
+ /// parsing (see ARROW-11889)
+ static Future> MakeAsync(
+ io::IOContext io_context, std::shared_ptr