diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/.keep b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/.keep new file mode 100644 index 0000000000000000000000000000000000000000..5e2c99fdbefc565576f8c5f37b0b0a66d60f2015 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/.keep @@ -0,0 +1,4 @@ +File generated from our OpenAPI spec by Stainless. + +This directory can be used to store custom files to expand the SDK. +It is ignored by Stainless code generation and its content (other than this keep file) won't be touched. \ No newline at end of file diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/__init__.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..076480d7bb6fc1e1733ca621e4dfe1f83a474c98 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/__init__.py @@ -0,0 +1 @@ +from ._files import files_from_dir as files_from_dir, async_files_from_dir as async_files_from_dir diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/__pycache__/__init__.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef3180fd9d7c5ca72c45c14b68f67e3330eabd9a Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/__pycache__/__init__.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/__pycache__/_files.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/__pycache__/_files.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9cf211259899b74e2490cdfeac287d9cf506b18 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/__pycache__/_files.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/__pycache__/_stainless_helpers.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/__pycache__/_stainless_helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a875ee104b38fc4a2593cf7f8f4a4a3acc7cbcb4 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/__pycache__/_stainless_helpers.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/__pycache__/foundry.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/__pycache__/foundry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f60293927b9406f658a9658f2bc19e4d0786a50d Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/__pycache__/foundry.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_extras/__init__.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_extras/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4e3037ee335b1ce466b68bf918ae367a9ee6a9f3 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_extras/__init__.py @@ -0,0 +1 @@ +from ._google_auth import google_auth as google_auth diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_extras/__pycache__/__init__.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_extras/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c53d22d834b4368afd489625c0639d532f776e0a Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_extras/__pycache__/__init__.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_extras/__pycache__/_common.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_extras/__pycache__/_common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f08caba41f3bec270c09a36fd5a2d43bc41650a0 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_extras/__pycache__/_common.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_extras/__pycache__/_google_auth.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_extras/__pycache__/_google_auth.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffb94b2988393caa9982ffc19156a1f925908f51 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_extras/__pycache__/_google_auth.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_extras/_common.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_extras/_common.py new file mode 100644 index 0000000000000000000000000000000000000000..5d2b7f6a863c9e3090234d8e1bd1b7b6570afa07 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_extras/_common.py @@ -0,0 +1,13 @@ +from ..._exceptions import AnthropicError + +INSTRUCTIONS = """ + +Anthropic error: missing required dependency `{library}`. + + $ pip install anthropic[{extra}] +""" + + +class MissingDependencyError(AnthropicError): + def __init__(self, *, library: str, extra: str) -> None: + super().__init__(INSTRUCTIONS.format(library=library, extra=extra)) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_extras/_google_auth.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_extras/_google_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..16cc7909f5bcca5d2a8a618c2be18e519e474347 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_extras/_google_auth.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any +from typing_extensions import ClassVar, override + +from ._common import MissingDependencyError +from ..._utils import LazyProxy + +if TYPE_CHECKING: + import google.auth # type: ignore + + google_auth = google.auth + + +class GoogleAuthProxy(LazyProxy[Any]): + should_cache: ClassVar[bool] = True + + @override + def __load__(self) -> Any: + try: + import google.auth # type: ignore + except ImportError as err: + raise MissingDependencyError(extra="vertex", library="google-auth") from err + + return google.auth + + +if not TYPE_CHECKING: + google_auth = GoogleAuthProxy() diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_files.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_files.py new file mode 100644 index 0000000000000000000000000000000000000000..ad7b7e57a4ccf723ce1465b5c6d877de88d1b1de --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_files.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +import os +from pathlib import Path + +import anyio + +from .._types import FileTypes + + +def files_from_dir(directory: str | os.PathLike[str]) -> list[FileTypes]: + path = Path(directory) + + files: list[FileTypes] = [] + _collect_files(path, path.parent, files) + return files + + +def _collect_files(directory: Path, relative_to: Path, files: list[FileTypes]) -> None: + for path in directory.iterdir(): + if path.is_dir(): + _collect_files(path, relative_to, files) + continue + + files.append((path.relative_to(relative_to).as_posix(), path.read_bytes())) + + +async def async_files_from_dir(directory: str | os.PathLike[str]) -> list[FileTypes]: + path = anyio.Path(directory) + + files: list[FileTypes] = [] + await _async_collect_files(path, path.parent, files) + return files + + +async def _async_collect_files(directory: anyio.Path, relative_to: anyio.Path, files: list[FileTypes]) -> None: + async for path in directory.iterdir(): + if await path.is_dir(): + await _async_collect_files(path, relative_to, files) + continue + + files.append((path.relative_to(relative_to).as_posix(), await path.read_bytes())) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_parse/__pycache__/_response.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_parse/__pycache__/_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0143585aee515302357675ace061de1da3eff02 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_parse/__pycache__/_response.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_parse/__pycache__/_transform.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_parse/__pycache__/_transform.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60d9fad89a7890e6c508f23e135a8afb1b0cb37f Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_parse/__pycache__/_transform.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_parse/_response.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_parse/_response.py new file mode 100644 index 0000000000000000000000000000000000000000..ee8326e5f7a7072ed2ffdfed79fea347a1f3eb36 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_parse/_response.py @@ -0,0 +1,72 @@ +from __future__ import annotations + +from typing_extensions import TypeVar + +from ..._types import NotGiven +from ..._models import TypeAdapter, construct_type_unchecked +from ..._utils._utils import is_given +from ...types.message import Message +from ...types.parsed_message import ParsedMessage, ParsedTextBlock, ParsedContentBlock +from ...types.beta.beta_message import BetaMessage +from ...types.beta.parsed_beta_message import ParsedBetaMessage, ParsedBetaTextBlock, ParsedBetaContentBlock + +ResponseFormatT = TypeVar("ResponseFormatT", default=None) + + +def parse_text(text: str, output_format: ResponseFormatT | NotGiven) -> ResponseFormatT | None: + if is_given(output_format): + adapted_type: TypeAdapter[ResponseFormatT] = TypeAdapter(output_format) + return adapted_type.validate_json(text) + return None + + +def parse_beta_response( + *, + output_format: ResponseFormatT | NotGiven, + response: BetaMessage, +) -> ParsedBetaMessage[ResponseFormatT]: + content_list: list[ParsedBetaContentBlock[ResponseFormatT]] = [] + for content in response.content: + if content.type == "text": + content_list.append( + construct_type_unchecked( + type_=ParsedBetaTextBlock[ResponseFormatT], + value={**content.to_dict(), "parsed_output": parse_text(content.text, output_format)}, + ) + ) + else: + content_list.append(content) # type: ignore + + return construct_type_unchecked( + type_=ParsedBetaMessage[ResponseFormatT], + value={ + **response.to_dict(), + "content": content_list, + }, + ) + + +def parse_response( + *, + output_format: ResponseFormatT | NotGiven, + response: Message, +) -> ParsedMessage[ResponseFormatT]: + content_list: list[ParsedContentBlock[ResponseFormatT]] = [] + for content in response.content: + if content.type == "text": + content_list.append( + construct_type_unchecked( + type_=ParsedTextBlock[ResponseFormatT], + value={**content.to_dict(), "parsed_output": parse_text(content.text, output_format)}, + ) + ) + else: + content_list.append(content) # type: ignore + + return construct_type_unchecked( + type_=ParsedMessage[ResponseFormatT], + value={ + **response.to_dict(), + "content": content_list, + }, + ) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_parse/_transform.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_parse/_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..755ad280db406fa4f4adc21d0c0aa83e1a3fe007 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_parse/_transform.py @@ -0,0 +1,171 @@ +from __future__ import annotations + +import inspect +from typing import Any, Literal, Optional, cast +from typing_extensions import assert_never + +import pydantic + +from ..._utils import is_list + +SupportedTypes = Literal[ + "object", + "array", + "string", + "integer", + "number", + "boolean", + "null", +] + +SupportedStringFormats = { + "date-time", + "time", + "date", + "duration", + "email", + "hostname", + "uri", + "ipv4", + "ipv6", + "uuid", +} + + +def get_transformed_string( + schema: dict[str, Any], +) -> dict[str, Any]: + """Transforms a JSON schema of type string to ensure it conforms to the API's expectations. + + Specifically, it ensures that if the schema is of type "string" and does not already + specify a "format", it sets the format to "text". + + Args: + schema: The original JSON schema. + + Returns: + The transformed JSON schema. + """ + if schema.get("type") == "string" and "format" not in schema: + schema["format"] = "text" + return schema + + +def transform_schema( + json_schema: type[pydantic.BaseModel] | dict[str, Any], +) -> dict[str, Any]: + """ + Transforms a JSON schema to ensure it conforms to the API's expectations. + + Args: + json_schema (Dict[str, Any]): The original JSON schema. + + Returns: + The transformed JSON schema. + + Examples: + >>> transform_schema( + ... { + ... "type": "integer", + ... "minimum": 1, + ... "maximum": 10, + ... "description": "A number", + ... } + ... ) + {'type': 'integer', 'description': 'A number\n\n{minimum: 1, maximum: 10}'} + """ + if inspect.isclass(json_schema) and issubclass(json_schema, pydantic.BaseModel): # pyright: ignore[reportUnnecessaryIsInstance] + json_schema = json_schema.model_json_schema() + + strict_schema: dict[str, Any] = {} + json_schema = {**json_schema} + + ref = json_schema.pop("$ref", None) + if ref is not None: + strict_schema["$ref"] = ref + return strict_schema + + defs = json_schema.pop("$defs", None) + if defs is not None: + strict_defs: dict[str, Any] = {} + strict_schema["$defs"] = strict_defs + + for name, schema in defs.items(): + strict_defs[name] = transform_schema(schema) + + type_: Optional[SupportedTypes] = json_schema.pop("type", None) + any_of = json_schema.pop("anyOf", None) + one_of = json_schema.pop("oneOf", None) + all_of = json_schema.pop("allOf", None) + + if is_list(any_of): + strict_schema["anyOf"] = [transform_schema(cast("dict[str, Any]", variant)) for variant in any_of] + elif is_list(one_of): + strict_schema["anyOf"] = [transform_schema(cast("dict[str, Any]", variant)) for variant in one_of] + elif is_list(all_of): + strict_schema["allOf"] = [transform_schema(cast("dict[str, Any]", variant)) for variant in all_of] + else: + if type_ is None: + raise ValueError("Schema must have a 'type', 'anyOf', 'oneOf', or 'allOf' field.") + + strict_schema["type"] = type_ + + enum = json_schema.pop("enum", None) + if is_list(enum): + strict_schema["enum"] = enum + + description = json_schema.pop("description", None) + if description is not None: + strict_schema["description"] = description + + title = json_schema.pop("title", None) + if title is not None: + strict_schema["title"] = title + + if type_ == "object": + strict_schema["properties"] = { + key: transform_schema(prop_schema) for key, prop_schema in json_schema.pop("properties", {}).items() + } + json_schema.pop("additionalProperties", None) + strict_schema["additionalProperties"] = False + + required = json_schema.pop("required", None) + if required is not None: + strict_schema["required"] = required + + elif type_ == "string": + format = json_schema.pop("format", None) + if format and format in SupportedStringFormats: + strict_schema["format"] = format + elif format: + # add it back so its treated as an extra property and appended to the description + json_schema["format"] = format + elif type_ == "array": + items = json_schema.pop("items", None) + if items is not None: + strict_schema["items"] = transform_schema(items) + + min_items = json_schema.pop("minItems", None) + if min_items is not None and min_items == 0 or min_items == 1: + strict_schema["minItems"] = min_items + elif min_items is not None: + # add it back so its treated as an extra property and appended to the description + json_schema["minItems"] = min_items + + elif type_ == "boolean" or type_ == "integer" or type_ == "number" or type_ == "null" or type_ is None: + pass + else: + assert_never(type_) + + # if there are any propes leftover then they aren't supported, so we add them to the description + # so that the model *might* follow them. + if json_schema: + description = strict_schema.get("description") + strict_schema["description"] = ( + (description + "\n\n" if description is not None else "") + + "{" + + ", ".join(f"{key}: {value}" for key, value in json_schema.items()) + + "}" + ) + + return strict_schema diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_stainless_helpers.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_stainless_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..6b894142ead11748adf0e1c63d959d1774b655db --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/_stainless_helpers.py @@ -0,0 +1,75 @@ +"""Tracking for SDK helper usage via the x-stainless-helper header.""" + +from __future__ import annotations + +from typing import Any, Dict, cast + +_HELPER_ATTR = "_stainless_helper" + + +def tag_helper(obj: Any, name: str) -> None: + """Mark an object as created by a named SDK helper.""" + try: + object.__setattr__(obj, _HELPER_ATTR, name) + except (AttributeError, TypeError): + pass + + +def get_helper_tag(obj: object) -> str | None: + """Get the helper name from an object, if any.""" + return getattr(obj, _HELPER_ATTR, None) # type: ignore[return-value] + + +def collect_helpers( + tools: Any = None, + messages: Any = None, +) -> list[str]: + """Collect deduplicated helper names from tools and messages.""" + helpers: set[str] = set() + + if tools: + for tool in tools: + tag = get_helper_tag(tool) + if tag is not None: + helpers.add(tag) + + if messages: + for message in messages: + tag = get_helper_tag(message) + if tag is not None: + helpers.add(tag) + + # Check content blocks within messages + if isinstance(message, dict): + blocks: Any = cast(Dict[str, Any], message).get("content") + else: + blocks = getattr(message, "content", None) + if isinstance(blocks, list): + for block in cast(list[object], blocks): + tag = get_helper_tag(block) + if tag is not None: + helpers.add(tag) + + return list(helpers) + + +def stainless_helper_header( + tools: Any = None, + messages: Any = None, +) -> dict[str, str]: + """Build x-stainless-helper header dict from tools and messages. + + Returns an empty dict if no helpers are found. + """ + helpers = collect_helpers(tools, messages) + if not helpers: + return {} + return {"x-stainless-helper": ", ".join(helpers)} + + +def stainless_helper_header_from_file(file: object) -> dict[str, str]: + """Build x-stainless-helper header dict from a file object.""" + tag = get_helper_tag(file) + if tag is None: + return {} + return {"x-stainless-helper": tag} diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/__init__.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4fc4e6a60a86445f87ddad6ec0885ff5ce09830d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/__init__.py @@ -0,0 +1 @@ +from ._client import AnthropicAWS as AnthropicAWS, AsyncAnthropicAWS as AsyncAnthropicAWS diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/__pycache__/__init__.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f242a3ce4f5387be95114f6aa243d06c59400c0 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/__pycache__/__init__.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/__pycache__/_auth.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/__pycache__/_auth.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ce5163ed8f7fc07c4e8b06ff67923ea5f7dfb77 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/__pycache__/_auth.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/__pycache__/_client.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/__pycache__/_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae122b1c9fccc7e6722f092f45c8332a629eff72 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/__pycache__/_client.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/__pycache__/_credentials.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/__pycache__/_credentials.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32acb2b6d348ac866e43b29509a14313c302c783 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/__pycache__/_credentials.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/_auth.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..9da6e35705d9167d3f4c62fd7ca5147fb1e53075 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/_auth.py @@ -0,0 +1,72 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import httpx + +from ..._utils import lru_cache + +if TYPE_CHECKING: + import boto3 + + +@lru_cache(maxsize=512) +def _get_session( + *, + aws_access_key: str | None, + aws_secret_key: str | None, + aws_session_token: str | None, + region: str | None, + profile: str | None, +) -> boto3.Session: + import boto3 + + return boto3.Session( + profile_name=profile, + region_name=region, + aws_access_key_id=aws_access_key, + aws_secret_access_key=aws_secret_key, + aws_session_token=aws_session_token, + ) + + +def get_auth_headers( + *, + method: str, + url: str, + headers: httpx.Headers, + aws_access_key: str | None, + aws_secret_key: str | None, + aws_session_token: str | None, + region: str | None, + profile: str | None, + data: str | None, + service_name: str, +) -> dict[str, str]: + from botocore.auth import SigV4Auth + from botocore.awsrequest import AWSRequest + + session = _get_session( + profile=profile, + region=region, + aws_access_key=aws_access_key, + aws_secret_key=aws_secret_key, + aws_session_token=aws_session_token, + ) + + # The connection header may be stripped by a proxy somewhere, so the receiver + # of this message may not see this header, so we remove it from the set of headers + # that are signed. + new_headers = {k: v for k, v in dict(headers).items() if k.lower() != "connection"} + + request = AWSRequest(method=method.upper(), url=url, headers=new_headers, data=data) + credentials = session.get_credentials() + if not credentials: + raise RuntimeError("Could not resolve AWS credentials from session") + + signer = SigV4Auth(credentials, service_name, session.region_name) + signer.add_auth(request) + + prepped = request.prepare() + + return {key: value for key, value in dict(prepped.headers).items() if value is not None} diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/_client.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/_client.py new file mode 100644 index 0000000000000000000000000000000000000000..fafad3aa7b4c412812b8e17d70c728a30c8b8ed3 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/_client.py @@ -0,0 +1,409 @@ +from __future__ import annotations + +from typing import Any, Mapping +from typing_extensions import Self, override + +import httpx + +from ..._types import NOT_GIVEN, Omit, Headers, Timeout, NotGiven +from ..._client import Anthropic, AsyncAnthropic +from ._credentials import ( + resolve_region, + resolve_api_key, + resolve_base_url, + resolve_auth_mode, + resolve_workspace_id, + validate_credentials, +) +from ..._exceptions import AnthropicError +from ..._base_client import DEFAULT_MAX_RETRIES + + +class AnthropicAWS(Anthropic): + aws_access_key: str | None + aws_secret_key: str | None + aws_region: str | None + aws_profile: str | None + aws_session_token: str | None + workspace_id: str | None + _use_sigv4: bool + _skip_auth: bool + + def __init__( + self, + *, + api_key: str | None = None, + aws_access_key: str | None = None, + aws_secret_key: str | None = None, + aws_region: str | None = None, + aws_profile: str | None = None, + aws_session_token: str | None = None, + workspace_id: str | None = None, + skip_auth: bool = False, + base_url: str | httpx.URL | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + http_client: httpx.Client | None = None, + _strict_response_validation: bool = False, + # Passed through to parent but not used for AWS auth + auth_token: str | None = None, + webhook_key: str | None = None, + ) -> None: + self._skip_auth = skip_auth + + validate_credentials(aws_access_key=aws_access_key, aws_secret_key=aws_secret_key) + + if skip_auth: + self._use_sigv4 = False + resolved_api_key = None + else: + self._use_sigv4 = resolve_auth_mode( + api_key=api_key, + aws_access_key=aws_access_key, + aws_secret_key=aws_secret_key, + aws_profile=aws_profile, + ) + resolved_api_key = resolve_api_key(api_key=api_key, use_sigv4=self._use_sigv4) + + resolved_region = resolve_region(aws_region) + + if self._use_sigv4 and resolved_region is None: + raise AnthropicError( + "No AWS region was provided. Set the `aws_region` argument or the `AWS_REGION`/`AWS_DEFAULT_REGION` environment variable." + ) + + self.aws_access_key = aws_access_key + self.aws_secret_key = aws_secret_key + self.aws_region = resolved_region + self.aws_profile = aws_profile + self.aws_session_token = aws_session_token + + if skip_auth: + self.workspace_id = workspace_id + else: + resolved_workspace_id = resolve_workspace_id(workspace_id) + if resolved_workspace_id is None: + raise AnthropicError( + "No workspace ID found. Set the `workspace_id` argument or the `ANTHROPIC_AWS_WORKSPACE_ID` environment variable." + ) + self.workspace_id = resolved_workspace_id + + if not skip_auth: + resolved_base_url = resolve_base_url( + str(base_url) if base_url is not None else None, + region=resolved_region, + ) + if resolved_base_url is None: + raise AnthropicError( + "No AWS region was provided and no base_url was given. " + "Set the `aws_region` argument, the `AWS_REGION`/`AWS_DEFAULT_REGION` environment variable, " + "or provide a `base_url` directly." + ) + base_url = resolved_base_url + + super().__init__( + api_key=resolved_api_key, + auth_token=auth_token, + webhook_key=webhook_key, + base_url=base_url, # type: ignore[arg-type] + timeout=timeout, + max_retries=max_retries, + default_headers=default_headers, + default_query=default_query, + http_client=http_client, + _strict_response_validation=_strict_response_validation, + ) + + @property + @override + def default_headers(self) -> dict[str, str | Omit]: + headers = {**super().default_headers} + if self.workspace_id is not None: + headers["anthropic-workspace-id"] = self.workspace_id + return headers + + @property + @override + def _api_key_auth(self) -> dict[str, str]: + if self._use_sigv4 or self._skip_auth: + return {} + return super()._api_key_auth + + @override + def _validate_headers(self, headers: Headers, custom_headers: Headers) -> None: + if self._use_sigv4 or self._skip_auth: + return + super()._validate_headers(headers, custom_headers) + + @override + def _prepare_request(self, request: httpx.Request) -> None: + if not self._use_sigv4: + return + + from ._auth import get_auth_headers + + data = request.read().decode() + + headers = get_auth_headers( + method=request.method, + url=str(request.url), + headers=request.headers, + aws_access_key=self.aws_access_key, + aws_secret_key=self.aws_secret_key, + aws_session_token=self.aws_session_token, + region=self.aws_region, + profile=self.aws_profile, + data=data, + service_name="aws-external-anthropic", + ) + request.headers.update(headers) + + @override + def copy( # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] — subclass intentionally drops `credentials` + self, + *, + api_key: str | None = None, + aws_access_key: str | None = None, + aws_secret_key: str | None = None, + aws_region: str | None = None, + aws_profile: str | None = None, + aws_session_token: str | None = None, + workspace_id: str | None = None, + skip_auth: bool | None = None, + auth_token: str | None = None, + webhook_key: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + http_client: httpx.Client | None = None, + max_retries: int | NotGiven = NOT_GIVEN, + default_headers: Mapping[str, str] | None = None, + set_default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + set_default_query: Mapping[str, object] | None = None, + _extra_kwargs: Mapping[str, Any] = {}, + ) -> Self: + # If region is changing and no explicit base_url, let __init__ derive it + resolved_base_url = base_url or (None if aws_region else self.base_url) + + return super().copy( + api_key=api_key or self.api_key, + auth_token=auth_token, + webhook_key=webhook_key, + base_url=resolved_base_url, + timeout=timeout, + http_client=http_client, + max_retries=max_retries, + default_headers=default_headers, + set_default_headers=set_default_headers, + default_query=default_query, + set_default_query=set_default_query, + _extra_kwargs={ + "aws_access_key": aws_access_key or self.aws_access_key, + "aws_secret_key": aws_secret_key or self.aws_secret_key, + "aws_region": aws_region or self.aws_region, + "aws_profile": aws_profile or self.aws_profile, + "aws_session_token": aws_session_token or self.aws_session_token, + "workspace_id": workspace_id or self.workspace_id, + "skip_auth": skip_auth if skip_auth is not None else self._skip_auth, + **_extra_kwargs, + }, + ) + + with_options = copy # type: ignore[assignment] + + +class AsyncAnthropicAWS(AsyncAnthropic): + aws_access_key: str | None + aws_secret_key: str | None + aws_region: str | None + aws_profile: str | None + aws_session_token: str | None + workspace_id: str | None + _use_sigv4: bool + _skip_auth: bool + + def __init__( + self, + *, + api_key: str | None = None, + aws_access_key: str | None = None, + aws_secret_key: str | None = None, + aws_region: str | None = None, + aws_profile: str | None = None, + aws_session_token: str | None = None, + workspace_id: str | None = None, + skip_auth: bool = False, + base_url: str | httpx.URL | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + http_client: httpx.AsyncClient | None = None, + _strict_response_validation: bool = False, + # Accepted for compatibility with AsyncAnthropic.copy() but not used + auth_token: str | None = None, + webhook_key: str | None = None, + ) -> None: + self._skip_auth = skip_auth + + validate_credentials(aws_access_key=aws_access_key, aws_secret_key=aws_secret_key) + + if skip_auth: + self._use_sigv4 = False + resolved_api_key = None + else: + self._use_sigv4 = resolve_auth_mode( + api_key=api_key, + aws_access_key=aws_access_key, + aws_secret_key=aws_secret_key, + aws_profile=aws_profile, + ) + resolved_api_key = resolve_api_key(api_key=api_key, use_sigv4=self._use_sigv4) + + resolved_region = resolve_region(aws_region) + + if self._use_sigv4 and resolved_region is None: + raise AnthropicError( + "No AWS region was provided. Set the `aws_region` argument or the `AWS_REGION`/`AWS_DEFAULT_REGION` environment variable." + ) + + self.aws_access_key = aws_access_key + self.aws_secret_key = aws_secret_key + self.aws_region = resolved_region + self.aws_profile = aws_profile + self.aws_session_token = aws_session_token + + if skip_auth: + self.workspace_id = workspace_id + else: + resolved_workspace_id = resolve_workspace_id(workspace_id) + if resolved_workspace_id is None: + raise AnthropicError( + "No workspace ID found. Set the `workspace_id` argument or the `ANTHROPIC_AWS_WORKSPACE_ID` environment variable." + ) + self.workspace_id = resolved_workspace_id + + if not skip_auth: + resolved_base_url = resolve_base_url( + str(base_url) if base_url is not None else None, + region=resolved_region, + ) + if resolved_base_url is None: + raise AnthropicError( + "No AWS region was provided and no base_url was given. " + "Set the `aws_region` argument, the `AWS_REGION`/`AWS_DEFAULT_REGION` environment variable, " + "or provide a `base_url` directly." + ) + base_url = resolved_base_url + + super().__init__( + api_key=resolved_api_key, + auth_token=auth_token, + webhook_key=webhook_key, + base_url=base_url, # type: ignore[arg-type] + timeout=timeout, + max_retries=max_retries, + default_headers=default_headers, + default_query=default_query, + http_client=http_client, + _strict_response_validation=_strict_response_validation, + ) + + @property + @override + def default_headers(self) -> dict[str, str | Omit]: + headers = {**super().default_headers} + if self.workspace_id is not None: + headers["anthropic-workspace-id"] = self.workspace_id + return headers + + @property + @override + def _api_key_auth(self) -> dict[str, str]: + if self._use_sigv4 or self._skip_auth: + return {} + return super()._api_key_auth + + @override + def _validate_headers(self, headers: Headers, custom_headers: Headers) -> None: + if self._use_sigv4 or self._skip_auth: + return + super()._validate_headers(headers, custom_headers) + + @override + async def _prepare_request(self, request: httpx.Request) -> None: + if not self._use_sigv4: + return + + from ._auth import get_auth_headers + + data = request.read().decode() + + headers = get_auth_headers( + method=request.method, + url=str(request.url), + headers=request.headers, + aws_access_key=self.aws_access_key, + aws_secret_key=self.aws_secret_key, + aws_session_token=self.aws_session_token, + region=self.aws_region, + profile=self.aws_profile, + data=data, + service_name="aws-external-anthropic", + ) + request.headers.update(headers) + + @override + def copy( # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] — subclass intentionally drops `credentials` + self, + *, + api_key: str | None = None, + aws_access_key: str | None = None, + aws_secret_key: str | None = None, + aws_region: str | None = None, + aws_profile: str | None = None, + aws_session_token: str | None = None, + workspace_id: str | None = None, + skip_auth: bool | None = None, + auth_token: str | None = None, + webhook_key: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + http_client: httpx.AsyncClient | None = None, + max_retries: int | NotGiven = NOT_GIVEN, + default_headers: Mapping[str, str] | None = None, + set_default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + set_default_query: Mapping[str, object] | None = None, + _extra_kwargs: Mapping[str, Any] = {}, + ) -> Self: + # If region is changing and no explicit base_url, let __init__ derive it + resolved_base_url = base_url or (None if aws_region else self.base_url) + + return super().copy( + api_key=api_key or self.api_key, + auth_token=auth_token, + webhook_key=webhook_key, + base_url=resolved_base_url, + timeout=timeout, + http_client=http_client, + max_retries=max_retries, + default_headers=default_headers, + set_default_headers=set_default_headers, + default_query=default_query, + set_default_query=set_default_query, + _extra_kwargs={ + "aws_access_key": aws_access_key or self.aws_access_key, + "aws_secret_key": aws_secret_key or self.aws_secret_key, + "aws_region": aws_region or self.aws_region, + "aws_profile": aws_profile or self.aws_profile, + "aws_session_token": aws_session_token or self.aws_session_token, + "workspace_id": workspace_id or self.workspace_id, + "skip_auth": skip_auth if skip_auth is not None else self._skip_auth, + **_extra_kwargs, + }, + ) + + with_options = copy # type: ignore[assignment] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/_credentials.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/_credentials.py new file mode 100644 index 0000000000000000000000000000000000000000..d6f591dda73a6f5d08aa3b1c98658a6d3f63f1b1 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/aws/_credentials.py @@ -0,0 +1,129 @@ +from __future__ import annotations + +import os +from typing import Sequence + + +def validate_credentials( + *, + aws_access_key: str | None, + aws_secret_key: str | None, +) -> None: + """Raise if only one of aws_access_key/aws_secret_key is provided.""" + if (aws_access_key is not None) != (aws_secret_key is not None): + provided = "aws_access_key" if aws_access_key is not None else "aws_secret_key" + missing = "aws_secret_key" if aws_access_key is not None else "aws_access_key" + raise ValueError( + f"`{provided}` was provided without `{missing}`. " + f"Both must be provided together, or neither (to use the default credential chain)." + ) + + +def _read_env(*env_vars: str) -> str | None: + """Return the first non-None value from the given env vars, or None.""" + for var in env_vars: + value = os.environ.get(var) + if value is not None: + return value + return None + + +def resolve_auth_mode( + *, + api_key: str | None, + aws_access_key: str | None, + aws_secret_key: str | None, + aws_profile: str | None, + api_key_env_vars: Sequence[str] = ("ANTHROPIC_AWS_API_KEY",), +) -> bool: + """Determine whether to use SigV4 auth. Returns True for SigV4, False for API key. + + Auth precedence: + 1. api_key constructor arg → API key mode + 2. aws_access_key + aws_secret_key constructor args → SigV4 + 3. aws_profile constructor arg → SigV4 + 4. API key env var(s) → API key mode (checked in order; first match wins) + 5. Default AWS credential chain → SigV4 + """ + if api_key is not None: + return False + + if aws_access_key is not None or aws_secret_key is not None: + return True + + if aws_profile is not None: + return True + + # No explicit constructor args that signal SigV4 — check env vars + if _read_env(*api_key_env_vars) is not None: + return False + + # Fall back to default AWS credential chain + return True + + +def resolve_api_key( + *, + api_key: str | None, + use_sigv4: bool, + api_key_env_vars: Sequence[str] = ("ANTHROPIC_AWS_API_KEY",), +) -> str | None: + """Resolve the API key. Returns None if using SigV4.""" + if api_key is not None: + return api_key + + if not use_sigv4: + # Must be from env var + return _read_env(*api_key_env_vars) + + return None + + +def resolve_region(aws_region: str | None) -> str | None: + """Resolve the AWS region from constructor arg or env var. + + Does not silently default — returns None if no region is available. + """ + if aws_region is not None: + return aws_region + + return os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION") + + +def resolve_workspace_id( + workspace_id: str | None, + *, + workspace_id_env_vars: Sequence[str] = ("ANTHROPIC_AWS_WORKSPACE_ID",), +) -> str | None: + """Resolve the workspace ID from constructor arg or env var(s). + + Returns None if no workspace ID is available (caller should raise). + """ + if workspace_id is not None: + return workspace_id + + return _read_env(*workspace_id_env_vars) + + +def resolve_base_url( + base_url: str | None, + *, + region: str | None, + base_url_env_vars: Sequence[str] = ("ANTHROPIC_AWS_BASE_URL",), + url_template: str = "https://aws-external-anthropic.{region}.api.aws", +) -> str | None: + """Resolve the base URL from constructor arg, env var, or region. + + Returns None if no base URL is resolvable (caller should raise). + """ + if base_url is not None: + return base_url + + env_url = _read_env(*base_url_env_vars) + if env_url is not None: + return env_url + + if region is not None: + return url_template.format(region=region) + + return None diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__init__.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e4fac291eb95fc981808d08b13af6afdd3e0e4a6 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__init__.py @@ -0,0 +1,5 @@ +from ._client import AnthropicBedrock as AnthropicBedrock, AsyncAnthropicBedrock as AsyncAnthropicBedrock +from ._mantle import ( + AnthropicBedrockMantle as AnthropicBedrockMantle, + AsyncAnthropicBedrockMantle as AsyncAnthropicBedrockMantle, +) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/__init__.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abe2fe6c94bc46a14c56e7534263dbfc035e3e2f Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/__init__.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/_auth.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/_auth.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e2e46d3be17fe4cbc31cabc327555639bad150a Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/_auth.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/_beta.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/_beta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5814494fa3ef8ae13da769e65e2163939aa8d1b Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/_beta.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/_beta_messages.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/_beta_messages.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d5e9ebc9d021d65df9db91b808cf460f195cae7 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/_beta_messages.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/_client.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbd0d7ed0998638d461322d16373458b7a4fad57 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/_client.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/_mantle.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/_mantle.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad3214e9ddf5d9cbbdb9957f785ba36b229fb83d Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/_mantle.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/_stream.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/_stream.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf846a7566599bc2c35da33423d5442f9fcdbe3a Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/_stream.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/_stream_decoder.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/_stream_decoder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9691c09b1b4b60fe988934327b38f379700ee50c Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/__pycache__/_stream_decoder.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/_auth.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..0a8b2109d133898f8681660c9f789347e9d91de8 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/_auth.py @@ -0,0 +1,72 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import httpx + +from ..._utils import lru_cache + +if TYPE_CHECKING: + import boto3 + + +@lru_cache(maxsize=512) +def _get_session( + *, + aws_access_key: str | None, + aws_secret_key: str | None, + aws_session_token: str | None, + region: str | None, + profile: str | None, +) -> boto3.Session: + import boto3 + + return boto3.Session( + profile_name=profile, + region_name=region, + aws_access_key_id=aws_access_key, + aws_secret_access_key=aws_secret_key, + aws_session_token=aws_session_token, + ) + + +def get_auth_headers( + *, + method: str, + url: str, + headers: httpx.Headers, + aws_access_key: str | None, + aws_secret_key: str | None, + aws_session_token: str | None, + region: str | None, + profile: str | None, + data: str | None, +) -> dict[str, str]: + from botocore.auth import SigV4Auth + from botocore.awsrequest import AWSRequest + + session = _get_session( + profile=profile, + region=region, + aws_access_key=aws_access_key, + aws_secret_key=aws_secret_key, + aws_session_token=aws_session_token, + ) + + # The connection header may be stripped by a proxy somewhere, so the receiver + # of this message may not see this header, so we remove it from the set of headers + # that are signed. + headers = headers.copy() + del headers["connection"] + + request = AWSRequest(method=method.upper(), url=url, headers=headers, data=data) + credentials = session.get_credentials() + if not credentials: + raise RuntimeError("could not resolve credentials from session") + + signer = SigV4Auth(credentials, "bedrock", session.region_name) + signer.add_auth(request) + + prepped = request.prepare() + + return {key: value for key, value in dict(prepped.headers).items() if value is not None} diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/_beta.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/_beta.py new file mode 100644 index 0000000000000000000000000000000000000000..f2a91b428f73abf787e4943c004229953080f8eb --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/_beta.py @@ -0,0 +1,102 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ._beta_messages import ( + Messages, + AsyncMessages, + MessagesWithRawResponse, + AsyncMessagesWithRawResponse, + MessagesWithStreamingResponse, + AsyncMessagesWithStreamingResponse, +) + +__all__ = ["Beta", "AsyncBeta"] + + +class Beta(SyncAPIResource): + @cached_property + def messages(self) -> Messages: + return Messages(self._client) + + @cached_property + def with_raw_response(self) -> BetaWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers + """ + return BetaWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> BetaWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response + """ + return BetaWithStreamingResponse(self) + + +class AsyncBeta(AsyncAPIResource): + @cached_property + def messages(self) -> AsyncMessages: + return AsyncMessages(self._client) + + @cached_property + def with_raw_response(self) -> AsyncBetaWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers + """ + return AsyncBetaWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncBetaWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response + """ + return AsyncBetaWithStreamingResponse(self) + + +class BetaWithRawResponse: + def __init__(self, beta: Beta) -> None: + self._beta = beta + + @cached_property + def messages(self) -> MessagesWithRawResponse: + return MessagesWithRawResponse(self._beta.messages) + + +class AsyncBetaWithRawResponse: + def __init__(self, beta: AsyncBeta) -> None: + self._beta = beta + + @cached_property + def messages(self) -> AsyncMessagesWithRawResponse: + return AsyncMessagesWithRawResponse(self._beta.messages) + + +class BetaWithStreamingResponse: + def __init__(self, beta: Beta) -> None: + self._beta = beta + + @cached_property + def messages(self) -> MessagesWithStreamingResponse: + return MessagesWithStreamingResponse(self._beta.messages) + + +class AsyncBetaWithStreamingResponse: + def __init__(self, beta: AsyncBeta) -> None: + self._beta = beta + + @cached_property + def messages(self) -> AsyncMessagesWithStreamingResponse: + return AsyncMessagesWithStreamingResponse(self._beta.messages) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/_beta_messages.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/_beta_messages.py new file mode 100644 index 0000000000000000000000000000000000000000..332f6fbabc3ddc8fa111d8b2f313fb239ffdd93f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/_beta_messages.py @@ -0,0 +1,93 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from ... import _legacy_response +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ...resources.beta import Messages as FirstPartyMessagesAPI, AsyncMessages as FirstPartyAsyncMessagesAPI + +__all__ = ["Messages", "AsyncMessages"] + + +class Messages(SyncAPIResource): + create = FirstPartyMessagesAPI.create + + @cached_property + def with_raw_response(self) -> MessagesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers + """ + return MessagesWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> MessagesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response + """ + return MessagesWithStreamingResponse(self) + + +class AsyncMessages(AsyncAPIResource): + create = FirstPartyAsyncMessagesAPI.create + + @cached_property + def with_raw_response(self) -> AsyncMessagesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers + """ + return AsyncMessagesWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncMessagesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response + """ + return AsyncMessagesWithStreamingResponse(self) + + +class MessagesWithRawResponse: + def __init__(self, messages: Messages) -> None: + self._messages = messages + + self.create = _legacy_response.to_raw_response_wrapper( + messages.create, + ) + + +class AsyncMessagesWithRawResponse: + def __init__(self, messages: AsyncMessages) -> None: + self._messages = messages + + self.create = _legacy_response.async_to_raw_response_wrapper( + messages.create, + ) + + +class MessagesWithStreamingResponse: + def __init__(self, messages: Messages) -> None: + self._messages = messages + + self.create = to_streamed_response_wrapper( + messages.create, + ) + + +class AsyncMessagesWithStreamingResponse: + def __init__(self, messages: AsyncMessages) -> None: + self._messages = messages + + self.create = async_to_streamed_response_wrapper( + messages.create, + ) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/_client.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/_client.py new file mode 100644 index 0000000000000000000000000000000000000000..cda0690df7a0fae2722118c4e49a2d1ead8439fe --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/_client.py @@ -0,0 +1,458 @@ +from __future__ import annotations + +import os +import logging +import urllib.parse +from typing import Any, Union, Mapping, TypeVar +from typing_extensions import Self, override + +import httpx + +from ... import _exceptions +from ._beta import Beta, AsyncBeta +from ..._types import NOT_GIVEN, Timeout, NotGiven +from ..._utils import is_dict, is_given +from ..._compat import model_copy +from ..._version import __version__ +from ..._streaming import Stream, AsyncStream +from ..._exceptions import AnthropicError, APIStatusError +from ..._base_client import ( + DEFAULT_MAX_RETRIES, + BaseClient, + SyncAPIClient, + AsyncAPIClient, + FinalRequestOptions, +) +from ._stream_decoder import AWSEventStreamDecoder +from ...resources.messages import Messages, AsyncMessages +from ...resources.completions import Completions, AsyncCompletions + +log: logging.Logger = logging.getLogger(__name__) + +DEFAULT_VERSION = "bedrock-2023-05-31" + +_HttpxClientT = TypeVar("_HttpxClientT", bound=Union[httpx.Client, httpx.AsyncClient]) +_DefaultStreamT = TypeVar("_DefaultStreamT", bound=Union[Stream[Any], AsyncStream[Any]]) + + +def _prepare_options(input_options: FinalRequestOptions) -> FinalRequestOptions: + options = model_copy(input_options, deep=True) + + if is_dict(options.json_data): + options.json_data.setdefault("anthropic_version", DEFAULT_VERSION) + + if is_given(options.headers): + betas = options.headers.get("anthropic-beta") + if betas: + options.json_data.setdefault("anthropic_beta", betas.split(",")) + + if options.url in {"/v1/complete", "/v1/messages", "/v1/messages?beta=true"} and options.method == "post": + if not is_dict(options.json_data): + raise RuntimeError("Expected dictionary json_data for post /completions endpoint") + + model = options.json_data.pop("model", None) + model = urllib.parse.quote(str(model), safe=":") + stream = options.json_data.pop("stream", False) + if stream: + options.url = f"/model/{model}/invoke-with-response-stream" + else: + options.url = f"/model/{model}/invoke" + + if options.url.startswith("/v1/messages/batches"): + raise AnthropicError("The Batch API is not supported in Bedrock yet") + + if options.url == "/v1/messages/count_tokens": + raise AnthropicError("Token counting is not supported in Bedrock yet") + + return options + + +def _infer_region() -> str: + """ + Infer the AWS region from the environment variables or + from the boto3 session if available. + """ + aws_region = os.environ.get("AWS_REGION") + if aws_region is None: + try: + import boto3 + + session = boto3.Session() + if session.region_name: + aws_region = session.region_name + except ImportError: + pass + + if aws_region is None: + log.warning("No AWS region specified, defaulting to us-east-1") + aws_region = "us-east-1" # fall back to legacy behavior + + return aws_region + + +class BaseBedrockClient(BaseClient[_HttpxClientT, _DefaultStreamT]): + @override + def _make_status_error( + self, + err_msg: str, + *, + body: object, + response: httpx.Response, + ) -> APIStatusError: + if response.status_code == 400: + return _exceptions.BadRequestError(err_msg, response=response, body=body) + + if response.status_code == 401: + return _exceptions.AuthenticationError(err_msg, response=response, body=body) + + if response.status_code == 403: + return _exceptions.PermissionDeniedError(err_msg, response=response, body=body) + + if response.status_code == 404: + return _exceptions.NotFoundError(err_msg, response=response, body=body) + + if response.status_code == 409: + return _exceptions.ConflictError(err_msg, response=response, body=body) + + if response.status_code == 422: + return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body) + + if response.status_code == 429: + return _exceptions.RateLimitError(err_msg, response=response, body=body) + + if response.status_code == 503: + return _exceptions.ServiceUnavailableError(err_msg, response=response, body=body) + + if response.status_code >= 500: + return _exceptions.InternalServerError(err_msg, response=response, body=body) + return APIStatusError(err_msg, response=response, body=body) + + +class AnthropicBedrock(BaseBedrockClient[httpx.Client, Stream[Any]], SyncAPIClient): + messages: Messages + completions: Completions + beta: Beta + + def __init__( + self, + aws_secret_key: str | None = None, + aws_access_key: str | None = None, + aws_region: str | None = None, + aws_profile: str | None = None, + aws_session_token: str | None = None, + api_key: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + # Configure a custom httpx client. See the [httpx documentation](https://www.python-httpx.org/api/#client) for more details. + http_client: httpx.Client | None = None, + # Enable or disable schema validation for data returned by the API. + # When enabled an error APIResponseValidationError is raised + # if the API responds with invalid data for the expected schema. + # + # This parameter may be removed or changed in the future. + # If you rely on this feature, please open a GitHub issue + # outlining your use-case to help us decide if it should be + # part of our public interface in the future. + _strict_response_validation: bool = False, + ) -> None: + if api_key is None: + api_key = os.environ.get("AWS_BEARER_TOKEN_BEDROCK") + + has_aws_credentials = ( + aws_access_key is not None + or aws_secret_key is not None + or aws_session_token is not None + or aws_profile is not None + ) + if api_key is not None and has_aws_credentials: + raise ValueError( + "Cannot specify both `api_key` and AWS credentials (`aws_access_key`, `aws_secret_key`, `aws_session_token`, `aws_profile`)" + ) + + self.api_key: str | None = api_key + + self.aws_secret_key = aws_secret_key + + self.aws_access_key = aws_access_key + + self.aws_region = _infer_region() if aws_region is None else aws_region + self.aws_profile = aws_profile + + self.aws_session_token = aws_session_token + + if base_url is None: + base_url = os.environ.get("ANTHROPIC_BEDROCK_BASE_URL") + if base_url is None: + base_url = f"https://bedrock-runtime.{self.aws_region}.amazonaws.com" + + super().__init__( + version=__version__, + base_url=base_url, + timeout=timeout, + max_retries=max_retries, + custom_headers=default_headers, + custom_query=default_query, + http_client=http_client, + _strict_response_validation=_strict_response_validation, + ) + + self.beta = Beta(self) + self.messages = Messages(self) + self.completions = Completions(self) + + @override + def _make_sse_decoder(self) -> AWSEventStreamDecoder: + return AWSEventStreamDecoder() + + @override + def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions: + return _prepare_options(options) + + @override + def _prepare_request(self, request: httpx.Request) -> None: + if self.api_key is not None: + request.headers["Authorization"] = f"Bearer {self.api_key}" + return + + from ._auth import get_auth_headers + + data = request.read().decode() + + headers = get_auth_headers( + method=request.method, + url=str(request.url), + headers=request.headers, + aws_access_key=self.aws_access_key, + aws_secret_key=self.aws_secret_key, + aws_session_token=self.aws_session_token, + region=self.aws_region or "us-east-1", + profile=self.aws_profile, + data=data, + ) + request.headers.update(headers) + + def copy( + self, + *, + aws_secret_key: str | None = None, + aws_access_key: str | None = None, + aws_region: str | None = None, + aws_session_token: str | None = None, + api_key: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + http_client: httpx.Client | None = None, + max_retries: int | NotGiven = NOT_GIVEN, + default_headers: Mapping[str, str] | None = None, + set_default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + set_default_query: Mapping[str, object] | None = None, + _extra_kwargs: Mapping[str, Any] = {}, + ) -> Self: + """ + Create a new client instance re-using the same options given to the current client with optional overriding. + """ + if default_headers is not None and set_default_headers is not None: + raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive") + + if default_query is not None and set_default_query is not None: + raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive") + + headers = self._custom_headers + if default_headers is not None: + headers = {**headers, **default_headers} + elif set_default_headers is not None: + headers = set_default_headers + + params = self._custom_query + if default_query is not None: + params = {**params, **default_query} + elif set_default_query is not None: + params = set_default_query + + return self.__class__( + aws_secret_key=aws_secret_key or self.aws_secret_key, + aws_access_key=aws_access_key or self.aws_access_key, + aws_region=aws_region or self.aws_region, + aws_session_token=aws_session_token or self.aws_session_token, + api_key=api_key or self.api_key, + base_url=base_url or self.base_url, + timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, + http_client=http_client, + max_retries=max_retries if is_given(max_retries) else self.max_retries, + default_headers=headers, + default_query=params, + **_extra_kwargs, + ) + + # Alias for `copy` for nicer inline usage, e.g. + # client.with_options(timeout=10).foo.create(...) + with_options = copy + + +class AsyncAnthropicBedrock(BaseBedrockClient[httpx.AsyncClient, AsyncStream[Any]], AsyncAPIClient): + messages: AsyncMessages + completions: AsyncCompletions + beta: AsyncBeta + + def __init__( + self, + aws_secret_key: str | None = None, + aws_access_key: str | None = None, + aws_region: str | None = None, + aws_profile: str | None = None, + aws_session_token: str | None = None, + api_key: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + # Configure a custom httpx client. See the [httpx documentation](https://www.python-httpx.org/api/#client) for more details. + http_client: httpx.AsyncClient | None = None, + # Enable or disable schema validation for data returned by the API. + # When enabled an error APIResponseValidationError is raised + # if the API responds with invalid data for the expected schema. + # + # This parameter may be removed or changed in the future. + # If you rely on this feature, please open a GitHub issue + # outlining your use-case to help us decide if it should be + # part of our public interface in the future. + _strict_response_validation: bool = False, + ) -> None: + if api_key is None: + api_key = os.environ.get("AWS_BEARER_TOKEN_BEDROCK") + + has_aws_credentials = ( + aws_access_key is not None + or aws_secret_key is not None + or aws_session_token is not None + or aws_profile is not None + ) + if api_key is not None and has_aws_credentials: + raise ValueError( + "Cannot specify both `api_key` and AWS credentials (`aws_access_key`, `aws_secret_key`, `aws_session_token`, `aws_profile`)" + ) + + self.api_key: str | None = api_key + + self.aws_secret_key = aws_secret_key + + self.aws_access_key = aws_access_key + + self.aws_region = _infer_region() if aws_region is None else aws_region + self.aws_profile = aws_profile + + self.aws_session_token = aws_session_token + + if base_url is None: + base_url = os.environ.get("ANTHROPIC_BEDROCK_BASE_URL") + if base_url is None: + base_url = f"https://bedrock-runtime.{self.aws_region}.amazonaws.com" + + super().__init__( + version=__version__, + base_url=base_url, + timeout=timeout, + max_retries=max_retries, + custom_headers=default_headers, + custom_query=default_query, + http_client=http_client, + _strict_response_validation=_strict_response_validation, + ) + + self.messages = AsyncMessages(self) + self.completions = AsyncCompletions(self) + self.beta = AsyncBeta(self) + + @override + def _make_sse_decoder(self) -> AWSEventStreamDecoder: + return AWSEventStreamDecoder() + + @override + async def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions: + return _prepare_options(options) + + @override + async def _prepare_request(self, request: httpx.Request) -> None: + if self.api_key is not None: + request.headers["Authorization"] = f"Bearer {self.api_key}" + return + + from ._auth import get_auth_headers + + data = request.read().decode() + + headers = get_auth_headers( + method=request.method, + url=str(request.url), + headers=request.headers, + aws_access_key=self.aws_access_key, + aws_secret_key=self.aws_secret_key, + aws_session_token=self.aws_session_token, + region=self.aws_region or "us-east-1", + profile=self.aws_profile, + data=data, + ) + request.headers.update(headers) + + def copy( + self, + *, + aws_secret_key: str | None = None, + aws_access_key: str | None = None, + aws_region: str | None = None, + aws_session_token: str | None = None, + api_key: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + http_client: httpx.AsyncClient | None = None, + max_retries: int | NotGiven = NOT_GIVEN, + default_headers: Mapping[str, str] | None = None, + set_default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + set_default_query: Mapping[str, object] | None = None, + _extra_kwargs: Mapping[str, Any] = {}, + ) -> Self: + """ + Create a new client instance re-using the same options given to the current client with optional overriding. + """ + if default_headers is not None and set_default_headers is not None: + raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive") + + if default_query is not None and set_default_query is not None: + raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive") + + headers = self._custom_headers + if default_headers is not None: + headers = {**headers, **default_headers} + elif set_default_headers is not None: + headers = set_default_headers + + params = self._custom_query + if default_query is not None: + params = {**params, **default_query} + elif set_default_query is not None: + params = set_default_query + + return self.__class__( + aws_secret_key=aws_secret_key or self.aws_secret_key, + aws_access_key=aws_access_key or self.aws_access_key, + aws_region=aws_region or self.aws_region, + aws_session_token=aws_session_token or self.aws_session_token, + api_key=api_key or self.api_key, + base_url=base_url or self.base_url, + timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, + http_client=http_client, + max_retries=max_retries if is_given(max_retries) else self.max_retries, + default_headers=headers, + default_query=params, + **_extra_kwargs, + ) + + # Alias for `copy` for nicer inline usage, e.g. + # client.with_options(timeout=10).foo.create(...) + with_options = copy diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/_mantle.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/_mantle.py new file mode 100644 index 0000000000000000000000000000000000000000..5507462af58ca1ca06a40de5a4ab4e267b446d62 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/_mantle.py @@ -0,0 +1,512 @@ +from __future__ import annotations + +import os +from typing import Any, Union, Mapping, TypeVar +from typing_extensions import Self, override + +import httpx + +from ... import _exceptions +from ..._qs import Querystring +from ..._types import NOT_GIVEN, Omit, Timeout, NotGiven +from ..._utils import is_given +from ..._compat import cached_property +from ..._version import __version__ +from ..aws._auth import get_auth_headers +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._streaming import Stream, AsyncStream +from ..._exceptions import AnthropicError, APIStatusError +from ..._base_client import ( + DEFAULT_MAX_RETRIES, + BaseClient, + SyncAPIClient, + AsyncAPIClient, +) +from ..aws._credentials import ( + resolve_region, + resolve_api_key, + resolve_auth_mode, + validate_credentials, +) +from ...resources.messages import Messages, AsyncMessages +from ...resources.beta.messages import Messages as BetaMessages, AsyncMessages as AsyncBetaMessages + +DEFAULT_SERVICE_NAME = "bedrock-mantle" + +_MANTLE_API_KEY_ENV_VARS = ("AWS_BEARER_TOKEN_BEDROCK", "ANTHROPIC_AWS_API_KEY") + +_HttpxClientT = TypeVar("_HttpxClientT", bound=Union[httpx.Client, httpx.AsyncClient]) +_DefaultStreamT = TypeVar("_DefaultStreamT", bound=Union[Stream[Any], AsyncStream[Any]]) + + +# --- Beta resources (messages-only) --- + + +class MantleBeta(SyncAPIResource): + @cached_property + def messages(self) -> BetaMessages: + return BetaMessages(self._client) + + +class AsyncMantleBeta(AsyncAPIResource): + @cached_property + def messages(self) -> AsyncBetaMessages: + return AsyncBetaMessages(self._client) + + +# --- Base --- + + +class BaseMantleClient(BaseClient[_HttpxClientT, _DefaultStreamT]): + @override + def _make_status_error( + self, + err_msg: str, + *, + body: object, + response: httpx.Response, + ) -> APIStatusError: + if response.status_code == 400: + return _exceptions.BadRequestError(err_msg, response=response, body=body) + + if response.status_code == 401: + return _exceptions.AuthenticationError(err_msg, response=response, body=body) + + if response.status_code == 403: + return _exceptions.PermissionDeniedError(err_msg, response=response, body=body) + + if response.status_code == 404: + return _exceptions.NotFoundError(err_msg, response=response, body=body) + + if response.status_code == 409: + return _exceptions.ConflictError(err_msg, response=response, body=body) + + if response.status_code == 413: + return _exceptions.RequestTooLargeError(err_msg, response=response, body=body) + + if response.status_code == 422: + return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body) + + if response.status_code == 429: + return _exceptions.RateLimitError(err_msg, response=response, body=body) + + if response.status_code == 529: + return _exceptions.OverloadedError(err_msg, response=response, body=body) + + if response.status_code >= 500: + return _exceptions.InternalServerError(err_msg, response=response, body=body) + return APIStatusError(err_msg, response=response, body=body) + + +# --- Shared init logic --- + + +def _resolve_mantle_config( + *, + api_key: str | None, + aws_access_key: str | None, + aws_secret_key: str | None, + aws_region: str | None, + aws_profile: str | None, + skip_auth: bool, + base_url: str | httpx.URL | None, + default_headers: Mapping[str, str] | None, +) -> tuple[str | None, str | httpx.URL, bool, dict[str, str]]: + """Resolve and validate all Mantle client configuration. + + Returns (resolved_api_key, resolved_base_url, use_sigv4, merged_headers). + """ + if skip_auth: + use_sigv4 = False + resolved_api_key = None + else: + validate_credentials(aws_access_key=aws_access_key, aws_secret_key=aws_secret_key) + + use_sigv4 = resolve_auth_mode( + api_key=api_key, + aws_access_key=aws_access_key, + aws_secret_key=aws_secret_key, + aws_profile=aws_profile, + api_key_env_vars=_MANTLE_API_KEY_ENV_VARS, + ) + + resolved_api_key = resolve_api_key( + api_key=api_key, + use_sigv4=use_sigv4, + api_key_env_vars=_MANTLE_API_KEY_ENV_VARS, + ) + + resolved_region = resolve_region(aws_region) + + if base_url is None: + base_url = os.environ.get("ANTHROPIC_BEDROCK_MANTLE_BASE_URL") + if base_url is None: + if resolved_region is None: + raise AnthropicError( + "No AWS region or base URL found. Set `aws_region` in the constructor, " + "the `AWS_REGION` / `AWS_DEFAULT_REGION` environment variable, or provide " + "a `base_url` / `ANTHROPIC_BEDROCK_MANTLE_BASE_URL` environment variable." + ) + base_url = f"https://bedrock-mantle.{resolved_region}.api.aws/anthropic" + + merged_headers: dict[str, str] = {} + if default_headers: + merged_headers.update(default_headers) + + return resolved_api_key, base_url, use_sigv4, merged_headers + + +# --- Sync client --- + + +class AnthropicBedrockMantle(BaseMantleClient[httpx.Client, Stream[Any]], SyncAPIClient): + messages: Messages + beta: MantleBeta + + aws_region: str | None + aws_access_key: str | None + aws_secret_key: str | None + aws_session_token: str | None + aws_profile: str | None + skip_auth: bool + + _use_sigv4: bool + + def __init__( + self, + *, + aws_access_key: str | None = None, + aws_secret_key: str | None = None, + aws_session_token: str | None = None, + aws_region: str | None = None, + aws_profile: str | None = None, + api_key: str | None = None, + skip_auth: bool = False, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + http_client: httpx.Client | None = None, + _strict_response_validation: bool = False, + ) -> None: + resolved_api_key, resolved_base_url, use_sigv4, merged_headers = _resolve_mantle_config( + api_key=api_key, + aws_access_key=aws_access_key, + aws_secret_key=aws_secret_key, + aws_region=aws_region, + aws_profile=aws_profile, + skip_auth=skip_auth, + base_url=base_url, + default_headers=default_headers, + ) + + resolved_region = resolve_region(aws_region) + + super().__init__( + version=__version__, + base_url=resolved_base_url, + timeout=timeout, + max_retries=max_retries, + custom_headers=merged_headers, + custom_query=default_query, + http_client=http_client, + _strict_response_validation=_strict_response_validation, + ) + + self.api_key = resolved_api_key + self.aws_region = resolved_region + self.aws_access_key = aws_access_key + self.aws_secret_key = aws_secret_key + self.aws_session_token = aws_session_token + self.aws_profile = aws_profile + self.skip_auth = skip_auth + self._use_sigv4 = use_sigv4 + + self.messages = Messages(self) + self.beta = MantleBeta(self) + + @property + @override + def qs(self) -> Querystring: + return Querystring(array_format="comma") + + @property + @override + def auth_headers(self) -> dict[str, str]: + if self.skip_auth or self._use_sigv4: + return {} + api_key = self.api_key + if api_key is None: + return {} + return {"Authorization": f"Bearer {api_key}"} + + @property + @override + def default_headers(self) -> dict[str, str | Omit]: + return { + **super().default_headers, + "X-Stainless-Async": "false", + "anthropic-version": "2023-06-01", + **self._custom_headers, + } + + @override + def _validate_headers(self, headers: Any, custom_headers: Any) -> None: + pass + + @override + def _prepare_request(self, request: httpx.Request) -> None: + if self.skip_auth or not self._use_sigv4: + return + + data = request.read().decode() + + headers = get_auth_headers( + method=request.method, + url=str(request.url), + headers=request.headers, + aws_access_key=self.aws_access_key, + aws_secret_key=self.aws_secret_key, + aws_session_token=self.aws_session_token, + region=self.aws_region, + profile=self.aws_profile, + data=data, + service_name=DEFAULT_SERVICE_NAME, + ) + request.headers.update(headers) + + def copy( + self, + *, + api_key: str | None = None, + aws_access_key: str | None = None, + aws_secret_key: str | None = None, + aws_session_token: str | None = None, + aws_region: str | None = None, + aws_profile: str | None = None, + skip_auth: bool | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + http_client: httpx.Client | None = None, + max_retries: int | NotGiven = NOT_GIVEN, + default_headers: Mapping[str, str] | None = None, + set_default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + set_default_query: Mapping[str, object] | None = None, + _extra_kwargs: Mapping[str, Any] = {}, + ) -> Self: + if default_headers is not None and set_default_headers is not None: + raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive") + + if default_query is not None and set_default_query is not None: + raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive") + + headers = self._custom_headers + if default_headers is not None: + headers = {**headers, **default_headers} + elif set_default_headers is not None: + headers = set_default_headers + + params = self._custom_query + if default_query is not None: + params = {**params, **default_query} + elif set_default_query is not None: + params = set_default_query + + return self.__class__( + api_key=api_key or self.api_key, + aws_access_key=aws_access_key or self.aws_access_key, + aws_secret_key=aws_secret_key or self.aws_secret_key, + aws_session_token=aws_session_token or self.aws_session_token, + aws_region=aws_region or self.aws_region, + aws_profile=aws_profile or self.aws_profile, + skip_auth=skip_auth if skip_auth is not None else self.skip_auth, + base_url=base_url or self.base_url, + timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, + http_client=http_client, + max_retries=max_retries if is_given(max_retries) else self.max_retries, + default_headers=headers, + default_query=params, + **_extra_kwargs, + ) + + with_options = copy + + +# --- Async client --- + + +class AsyncAnthropicBedrockMantle(BaseMantleClient[httpx.AsyncClient, AsyncStream[Any]], AsyncAPIClient): + messages: AsyncMessages + beta: AsyncMantleBeta + + aws_region: str | None + aws_access_key: str | None + aws_secret_key: str | None + aws_session_token: str | None + aws_profile: str | None + skip_auth: bool + + _use_sigv4: bool + + def __init__( + self, + *, + aws_access_key: str | None = None, + aws_secret_key: str | None = None, + aws_session_token: str | None = None, + aws_region: str | None = None, + aws_profile: str | None = None, + api_key: str | None = None, + skip_auth: bool = False, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + http_client: httpx.AsyncClient | None = None, + _strict_response_validation: bool = False, + ) -> None: + resolved_api_key, resolved_base_url, use_sigv4, merged_headers = _resolve_mantle_config( + api_key=api_key, + aws_access_key=aws_access_key, + aws_secret_key=aws_secret_key, + aws_region=aws_region, + aws_profile=aws_profile, + skip_auth=skip_auth, + base_url=base_url, + default_headers=default_headers, + ) + + resolved_region = resolve_region(aws_region) + + super().__init__( + version=__version__, + base_url=resolved_base_url, + timeout=timeout, + max_retries=max_retries, + custom_headers=merged_headers, + custom_query=default_query, + http_client=http_client, + _strict_response_validation=_strict_response_validation, + ) + + self.api_key = resolved_api_key + self.aws_region = resolved_region + self.aws_access_key = aws_access_key + self.aws_secret_key = aws_secret_key + self.aws_session_token = aws_session_token + self.aws_profile = aws_profile + self.skip_auth = skip_auth + self._use_sigv4 = use_sigv4 + + self.messages = AsyncMessages(self) + self.beta = AsyncMantleBeta(self) + + @property + @override + def qs(self) -> Querystring: + return Querystring(array_format="comma") + + @property + @override + def auth_headers(self) -> dict[str, str]: + if self.skip_auth or self._use_sigv4: + return {} + api_key = self.api_key + if api_key is None: + return {} + return {"Authorization": f"Bearer {api_key}"} + + @property + @override + def default_headers(self) -> dict[str, str | Omit]: + return { + **super().default_headers, + "X-Stainless-Async": "async:asyncio", + "anthropic-version": "2023-06-01", + **self._custom_headers, + } + + @override + def _validate_headers(self, headers: Any, custom_headers: Any) -> None: + pass + + @override + async def _prepare_request(self, request: httpx.Request) -> None: + if self.skip_auth or not self._use_sigv4: + return + + data = request.read().decode() + + headers = get_auth_headers( + method=request.method, + url=str(request.url), + headers=request.headers, + aws_access_key=self.aws_access_key, + aws_secret_key=self.aws_secret_key, + aws_session_token=self.aws_session_token, + region=self.aws_region, + profile=self.aws_profile, + data=data, + service_name=DEFAULT_SERVICE_NAME, + ) + request.headers.update(headers) + + def copy( + self, + *, + api_key: str | None = None, + aws_access_key: str | None = None, + aws_secret_key: str | None = None, + aws_session_token: str | None = None, + aws_region: str | None = None, + aws_profile: str | None = None, + skip_auth: bool | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + http_client: httpx.AsyncClient | None = None, + max_retries: int | NotGiven = NOT_GIVEN, + default_headers: Mapping[str, str] | None = None, + set_default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + set_default_query: Mapping[str, object] | None = None, + _extra_kwargs: Mapping[str, Any] = {}, + ) -> Self: + if default_headers is not None and set_default_headers is not None: + raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive") + + if default_query is not None and set_default_query is not None: + raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive") + + headers = self._custom_headers + if default_headers is not None: + headers = {**headers, **default_headers} + elif set_default_headers is not None: + headers = set_default_headers + + params = self._custom_query + if default_query is not None: + params = {**params, **default_query} + elif set_default_query is not None: + params = set_default_query + + return self.__class__( + api_key=api_key or self.api_key, + aws_access_key=aws_access_key or self.aws_access_key, + aws_secret_key=aws_secret_key or self.aws_secret_key, + aws_session_token=aws_session_token or self.aws_session_token, + aws_region=aws_region or self.aws_region, + aws_profile=aws_profile or self.aws_profile, + skip_auth=skip_auth if skip_auth is not None else self.skip_auth, + base_url=base_url or self.base_url, + timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, + http_client=http_client, + max_retries=max_retries if is_given(max_retries) else self.max_retries, + default_headers=headers, + default_query=params, + **_extra_kwargs, + ) + + with_options = copy diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/_stream.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..6512c4681b1b21acdcddaeec9751915b382678b4 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/_stream.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +from typing import TypeVar + +import httpx + +from ..._client import Anthropic, AsyncAnthropic +from ..._streaming import Stream, AsyncStream +from ._stream_decoder import AWSEventStreamDecoder + +_T = TypeVar("_T") + + +class BedrockStream(Stream[_T]): + def __init__( + self, + *, + cast_to: type[_T], + response: httpx.Response, + client: Anthropic, + ) -> None: + super().__init__(cast_to=cast_to, response=response, client=client) + + self._decoder = AWSEventStreamDecoder() + + +class AsyncBedrockStream(AsyncStream[_T]): + def __init__( + self, + *, + cast_to: type[_T], + response: httpx.Response, + client: AsyncAnthropic, + ) -> None: + super().__init__(cast_to=cast_to, response=response, client=client) + + self._decoder = AWSEventStreamDecoder() diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/_stream_decoder.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/_stream_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..02e81a3ca86961f27c603b3d2ec59b3df2b9393b --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/bedrock/_stream_decoder.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Iterator, AsyncIterator + +from ..._utils import lru_cache +from ..._streaming import ServerSentEvent + +if TYPE_CHECKING: + from botocore.model import Shape + from botocore.eventstream import EventStreamMessage + + +@lru_cache(maxsize=None) +def get_response_stream_shape() -> Shape: + from botocore.model import ServiceModel + from botocore.loaders import Loader + + loader = Loader() + bedrock_service_dict = loader.load_service_model("bedrock-runtime", "service-2") + bedrock_service_model = ServiceModel(bedrock_service_dict) + return bedrock_service_model.shape_for("ResponseStream") + + +class AWSEventStreamDecoder: + def __init__(self) -> None: + from botocore.parsers import EventStreamJSONParser + + self.parser = EventStreamJSONParser() + + def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]: + """Given an iterator that yields lines, iterate over it & yield every event encountered""" + from botocore.eventstream import EventStreamBuffer + + event_stream_buffer = EventStreamBuffer() + for chunk in iterator: + event_stream_buffer.add_data(chunk) + for event in event_stream_buffer: + message = self._parse_message_from_event(event) + if message: + yield ServerSentEvent(data=message, event="completion") + + async def aiter_bytes(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[ServerSentEvent]: + """Given an async iterator that yields lines, iterate over it & yield every event encountered""" + from botocore.eventstream import EventStreamBuffer + + event_stream_buffer = EventStreamBuffer() + async for chunk in iterator: + event_stream_buffer.add_data(chunk) + for event in event_stream_buffer: + message = self._parse_message_from_event(event) + if message: + yield ServerSentEvent(data=message, event="completion") + + def _parse_message_from_event(self, event: EventStreamMessage) -> str | None: + response_dict = event.to_response_dict() + parsed_response = self.parser.parse(response_dict, get_response_stream_shape()) + if response_dict["status_code"] != 200: + raise ValueError(f"Bad response code, expected 200: {response_dict}") + + chunk = parsed_response.get("chunk") + if not chunk: + return None + + return chunk.get("bytes").decode() # type: ignore[no-any-return] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__init__.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e3c2507b42de5a4329e661526971607da70ced99 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__init__.py @@ -0,0 +1,39 @@ +from ._auth import AccessTokenAuth as AccessTokenAuth +from ._cache import TokenCache as TokenCache +from ._chain import default_credentials as default_credentials +from ._types import ( + AccessToken as AccessToken, + CredentialResult as CredentialResult, + AccessTokenProvider as AccessTokenProvider, + IdentityTokenProvider as IdentityTokenProvider, +) +from ._workload import ( + WorkloadIdentityError as WorkloadIdentityError, + WorkloadIdentityCredentials as WorkloadIdentityCredentials, + exchange_federation_assertion as exchange_federation_assertion, +) +from ._providers import ( + EnvToken as EnvToken, + StaticToken as StaticToken, + InMemoryConfig as InMemoryConfig, + CredentialsFile as CredentialsFile, + IdentityTokenFile as IdentityTokenFile, +) + +__all__ = [ + "AccessToken", + "AccessTokenProvider", + "CredentialResult", + "IdentityTokenProvider", + "StaticToken", + "EnvToken", + "CredentialsFile", + "InMemoryConfig", + "IdentityTokenFile", + "WorkloadIdentityCredentials", + "WorkloadIdentityError", + "exchange_federation_assertion", + "TokenCache", + "AccessTokenAuth", + "default_credentials", +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/__init__.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb1fd75d85742bda9b9289d0dcadf46ae1212491 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/__init__.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/_auth.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/_auth.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bc2a4dfb831da7ce5fe9d6ae5f9423757441cfa Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/_auth.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/_cache.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1df762d260d69ace21917bd2d6d491f515aca87f Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/_cache.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/_chain.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/_chain.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..688569c51de19c12ca5eff212dfb40c1801b1c56 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/_chain.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/_constants.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/_constants.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ac70221f33ea959ba2d916404f8a7e4d4927821 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/_constants.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/_providers.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/_providers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cdd1a494a344cfb098e501f6bedb94cc1f5c44c4 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/_providers.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/_types.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a2ea2fad93a29024e444ecf11e92907ae43263b Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/_types.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/_workload.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/_workload.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c55d99c631668da1b730f271a091a7ed51421b7 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/__pycache__/_workload.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/_auth.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..d2019666c1ee6668c44627a66206ae215229b722 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/_auth.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +import logging +import threading +from typing import Generator, AsyncGenerator +from typing_extensions import override + +import httpx + +from ._cache import TokenCache +from ..._utils import asyncify +from ._constants import OAUTH_API_BETA_HEADER + +__all__ = ["AccessTokenAuth"] + +log: logging.Logger = logging.getLogger(__name__) + +_warn_once_lock = threading.Lock() +_warn_once_seen: set[str] = set() + + +def _warn_once(key: str, message: str, *args: object) -> None: + """Emit a log warning at most once per ``key`` per process.""" + with _warn_once_lock: + if key in _warn_once_seen: + return + _warn_once_seen.add(key) + log.warning(message, *args) + + +def warn_explicit_static_shadows_credentials(param: str) -> None: + """Warn that an explicit ``api_key=`` / ``auth_token=`` argument shadows + an explicit ``credentials=`` provider passed to the same constructor or + ``copy()`` call. The static credential wins at the request-header level + (``AccessTokenAuth.sync_auth_flow`` short-circuits on the pre-set header), + which silently disables the credentials provider. + """ + _warn_once( + f"explicit-shadow:{param}", + "`%s=` was passed alongside `credentials=`; the static credential " + "takes precedence and the credentials provider is silently disabled. " + "Pass only one.", + param, + ) + + +def warn_env_static_shadows_auto_discovery(env_var: str) -> None: + """Warn that an ``ANTHROPIC_API_KEY`` / ``ANTHROPIC_AUTH_TOKEN`` from the + environment is shadowing the SDK's profile / federation auto-discovery. + + Per the credential-precedence spec, a static-credential env var silently + disables the auto-discovered federation and profile paths. Surface a + one-shot warning so migrating users can see why their ``ANTHROPIC_PROFILE`` + or WIF env vars are being ignored. + """ + _warn_once( + f"env-shadow:{env_var}", + "%s is set and takes precedence over the SDK's profile / federation " + "auto-discovery; unset %s to use the auto-discovered credential.", + env_var, + env_var, + ) + + +class AccessTokenAuth(httpx.Auth): + """Adapts a :class:`TokenCache` to httpx's :class:`~httpx.Auth` protocol. + + Used by :meth:`anthropic.Anthropic.custom_auth` to inject ``Authorization: Bearer`` + plus the OAuth beta header on every request, with proactive refresh handled by + :class:`TokenCache`. + + Static credentials shadow federation: if the outgoing request already carries + an ``X-Api-Key`` or ``Authorization`` header (set by the client's api_key / + auth_token path), this auth flow is a no-op. That matches the Go SDK's + ``authMiddleware`` and the documented precedence in the WIF user guide — + a static ``ANTHROPIC_API_KEY`` shadows any credentials provider. + """ + + requires_response_body = False + + def __init__(self, token_cache: TokenCache) -> None: + self._token_cache = token_cache + + @staticmethod + def _has_static_credential(request: httpx.Request) -> bool: + return bool(request.headers.get("X-Api-Key") or request.headers.get("Authorization")) + + def _apply(self, request: httpx.Request, token: str) -> None: + request.headers["Authorization"] = f"Bearer {token}" + existing_beta = request.headers.get("anthropic-beta", "") + # Tokenize the comma-separated header so dedupe matches whole flag + # names rather than substrings — `oauth-2025-04-20` would otherwise + # spuriously match a future `oauth-2025-04-20b`. + # + # The flag we inject here is the *API* beta (oauth-2025-04-20), which + # unlocks `Authorization: Bearer` auth on the API. The *federation* + # beta (oidc-federation-2026-04-01) is a separate routing switch used + # only on jwt-bearer POSTs to /v1/oauth/token — see _workload.py. + existing_flags = [flag.strip() for flag in existing_beta.split(",") if flag.strip()] + if OAUTH_API_BETA_HEADER not in existing_flags: + existing_flags.append(OAUTH_API_BETA_HEADER) + request.headers["anthropic-beta"] = ", ".join(existing_flags) + + @override + def sync_auth_flow(self, request: httpx.Request) -> Generator[httpx.Request, httpx.Response, None]: + if self._has_static_credential(request): + yield request + return + token = self._token_cache.get_token() + self._apply(request, token) + yield request + + @override + async def async_auth_flow(self, request: httpx.Request) -> AsyncGenerator[httpx.Request, httpx.Response]: + if self._has_static_credential(request): + yield request + return + # TokenCache.get_token is sync (and may make a blocking HTTP call); run it + # in a worker thread to avoid blocking the event loop. Uses the same + # ``asyncify`` helper as the rest of the SDK (see lib/vertex). + token = await asyncify(self._token_cache.get_token)() + self._apply(request, token) + yield request diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/_cache.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..f36e18fb119bcf133570682a47c90839bff00575 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/_cache.py @@ -0,0 +1,185 @@ +from __future__ import annotations + +import time +import logging +import threading +from typing import Callable, Optional + +import httpx + +from ._types import AccessToken, AccessTokenProvider +from ._workload import WorkloadIdentityError +from ._constants import ADVISORY_REFRESH_SECONDS, MANDATORY_REFRESH_SECONDS +from ..._exceptions import AnthropicError + +__all__ = ["TokenCache"] + +log: logging.Logger = logging.getLogger(__name__) + +# Skip advisory refreshes for this many seconds after a failure so a +# token-endpoint outage isn't hammered at request rate. Fixed (no jitter): +# trades fast recovery against fleet load during a sustained outage. +ADVISORY_REFRESH_BACKOFF_SECONDS = 5 + + +class TokenCache: + """Thread-safe cache wrapping an :class:`AccessTokenProvider` with two-tier + proactive refresh and single-flight semantics. + + Refresh policy on each :meth:`get_token` call: + + * No cached token → call provider (blocking), cache, return. + * Cached with ``expires_at=None`` → return cached forever (never refresh). + * More than ``advisory_refresh_seconds`` remaining → return cached. + * Between ``mandatory_refresh_seconds`` and ``advisory_refresh_seconds`` + remaining (advisory window) → try provider; on success swap cache; on + failure log a warning and return the stale cached token. If another + caller is already refreshing, the advisory caller just returns the + cached token — no second refresh, no waiting. + * Less than ``mandatory_refresh_seconds`` remaining or already expired + (mandatory window) → call provider; on failure RAISE. Concurrent + mandatory callers wait on a shared ``Event`` so exactly one provider + call is in flight. + + The lock is released before the provider call so a 30-second HTTP POST + doesn't serialize unrelated callers through a single thread. This matters + under async: ``asyncify(get_token)`` runs on the thread pool, and holding + the lock across the network call would pin an async worker for the whole + exchange. + """ + + def __init__( + self, + provider: AccessTokenProvider, + *, + advisory_refresh_seconds: int = ADVISORY_REFRESH_SECONDS, + mandatory_refresh_seconds: int = MANDATORY_REFRESH_SECONDS, + time_source: Callable[[], float] = time.time, + ) -> None: + self._provider = provider + self._advisory = advisory_refresh_seconds + self._mandatory = mandatory_refresh_seconds + self._time_source = time_source + self._lock = threading.Lock() + self._cached: Optional[AccessToken] = None + # Set when a refresh is in flight. Waiters in the mandatory window + # block on this event; the leader clears it after publishing the + # fresh token (or on failure). + self._refresh_event: Optional[threading.Event] = None + # One-shot: invalidate() sets it; next provider call passes + # force_refresh=True so on-disk providers don't re-serve a stale token. + self._next_force = False + # Time of last advisory-refresh failure (never reset on success — + # only distance-from-now matters). + self._last_advisory_failure_time: float = 0.0 + + def _invoke_provider(self, *, force: bool) -> AccessToken: + """Invoke ``self._provider``, tolerating legacy zero-arg callables.""" + try: + return self._provider(force_refresh=force) + except TypeError as err: + # Back-compat for legacy zero-arg providers. Argument-binding + # TypeErrors fire before the body runs, so this can't double-invoke; + # a TypeError from inside the provider won't mention the kwarg name. + if "force_refresh" not in str(err): + raise + return self._provider() # type: ignore[call-arg] + + def _call_provider(self) -> AccessToken: + """Call the provider, retrying once on a 401 from the token endpoint.""" + # Read but don't clear yet — clearing only on success keeps the flag + # alive across a transient failure so the retry still forces. + with self._lock: + force = self._next_force + try: + result = self._invoke_provider(force=force) + except WorkloadIdentityError as err: + if err.status_code != 401: + raise + log.debug("Token provider returned 401; retrying once") + result = self._invoke_provider(force=True) + with self._lock: + self._next_force = False + return result + + def get_token(self) -> str: + """Return a valid bearer token, refreshing if necessary.""" + while True: + advisory_fallback: Optional[AccessToken] = None + remaining_seconds = 0 + with self._lock: + cached = self._cached + if cached is not None: + if cached.expires_at is None: + return cached.token + remaining = cached.expires_at - self._time_source() + if remaining > self._advisory: + return cached.token + if remaining > self._mandatory: + # Advisory window. If a refresh is already running, + # keep serving the cached token — don't queue and + # don't start a second refresh. + if self._refresh_event is not None: + return cached.token + # Backoff: skip refresh and serve cached after a + # recent advisory failure. + if self._time_source() - self._last_advisory_failure_time < ADVISORY_REFRESH_BACKOFF_SECONDS: + return cached.token + advisory_fallback = cached + remaining_seconds = int(remaining) + + if self._refresh_event is not None: + # Mandatory-window caller with a refresh in flight: wait. + waiter_event: Optional[threading.Event] = self._refresh_event + else: + # We're the leader. + self._refresh_event = threading.Event() + waiter_event = None + + if waiter_event is not None: + waiter_event.wait() + # Loop back and re-read the cache — the refresh may have + # succeeded (return fresh token), failed (start a new + # refresh ourselves), or been invalidated in between. + continue + + # Leader: run the provider outside the lock. The except catches + # BaseException (not a narrow tuple) so the refresh event is + # always released — a user-supplied provider raising e.g. + # RuntimeError must not deadlock mandatory-window waiters. + try: + fresh = self._call_provider() + except BaseException as err: + with self._lock: + released = self._refresh_event + self._refresh_event = None + assert released is not None + released.set() + if advisory_fallback is not None and isinstance(err, (AnthropicError, httpx.HTTPError)): + log.warning( + "Advisory token refresh failed (%ds remaining); serving cached token: %s", + remaining_seconds, + err, + ) + with self._lock: + self._last_advisory_failure_time = self._time_source() + return advisory_fallback.token + raise + + with self._lock: + self._cached = fresh + released = self._refresh_event + self._refresh_event = None + assert released is not None + released.set() + return fresh.token + + def invalidate(self) -> None: + """Clear the cached token so the next :meth:`get_token` re-invokes the provider. + + Also sets a one-shot ``force_refresh`` flag so on-disk providers skip + their freshness short-circuit instead of re-serving the revoked token. + """ + with self._lock: + self._cached = None + self._next_force = True diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/_chain.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/_chain.py new file mode 100644 index 0000000000000000000000000000000000000000..948969360a8c3186d70a8504b4d64b254947736e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/_chain.py @@ -0,0 +1,155 @@ +from __future__ import annotations + +import os +from typing import Optional + +from ._types import CredentialResult, IdentityTokenProvider +from ._workload import WorkloadIdentityCredentials +from ._constants import ( + ENV_SCOPE, + ENV_API_KEY, + ENV_PROFILE, + ENV_AUTH_TOKEN, + ENV_CONFIG_DIR, + ENV_WORKSPACE_ID, + ENV_IDENTITY_TOKEN, + ENV_ORGANIZATION_ID, + ENV_FEDERATION_RULE_ID, + ENV_SERVICE_ACCOUNT_ID, + _has_active_profile_config, + _has_explicit_active_config, + resolve_identity_token_path, +) +from ._providers import StaticToken, CredentialsFile, IdentityTokenFile +from ..._exceptions import AnthropicError + +__all__ = ["default_credentials"] + + +def _build_federation_result(*, base_url: str) -> Optional[CredentialResult]: + """Build a :class:`CredentialResult` for the env-var federation path + (step 4 in the precedence spec). Returns ``None`` if the required trio + isn't fully set.""" + federation_rule_id = os.environ.get(ENV_FEDERATION_RULE_ID) + organization_id = os.environ.get(ENV_ORGANIZATION_ID) + has_literal_token = ENV_IDENTITY_TOKEN in os.environ + identity_token_path = resolve_identity_token_path() + + if not federation_rule_id or not organization_id: + return None + if not has_literal_token and identity_token_path is None: + return None + + identity_provider: IdentityTokenProvider + if identity_token_path is not None: + identity_provider = IdentityTokenFile(identity_token_path) + else: + # Read the env var on every call so a rotated value is picked up + # at the next token exchange (don't capture into a closure). + def _read_env_token() -> str: + value = os.environ.get(ENV_IDENTITY_TOKEN) + if value is None: + raise AnthropicError( + f"{ENV_IDENTITY_TOKEN} is not set; the workload-identity chain " + f"selected this provider at construction time but the env var " + f"is no longer present." + ) + return value + + identity_provider = _read_env_token + + provider = WorkloadIdentityCredentials( + identity_token_provider=identity_provider, + federation_rule_id=federation_rule_id, + organization_id=organization_id, + service_account_id=os.environ.get(ENV_SERVICE_ACCOUNT_ID), + # Coerce empty string to None so a defaulted-but-empty CI variable + # doesn't put ``"workspace_id": ""`` on the wire — matches the falsy + # skip in :func:`._providers._fill_missing_from_env`. + workspace_id=os.environ.get(ENV_WORKSPACE_ID) or None, + scope=os.environ.get(ENV_SCOPE), + ) + provider.bind_base_url(base_url) + return CredentialResult(provider=provider) + + +def default_credentials(*, base_url: str = "https://api.anthropic.com") -> Optional[CredentialResult]: + """Resolve a :class:`CredentialResult` from the environment per the + credential-resolution spec. First match wins. + + Implements steps 2-5 of the spec precedence chain (step 1 is handled at + the client constructor level, above this function): + + Step 2a: ``ANTHROPIC_API_KEY`` → return ``None`` so the client uses its + existing ``X-Api-Key`` header path. (API keys are not Bearer + tokens, so they can't flow through this chain.) + Step 2b: ``ANTHROPIC_AUTH_TOKEN`` → :class:`StaticToken` (Bearer). + Step 3: ``ANTHROPIC_PROFILE`` / ``ANTHROPIC_CONFIG_DIR`` set, or the + ``active_config`` pointer file exists → load that profile. + This is *explicit profile selection*; failures propagate. + Step 4: ``ANTHROPIC_FEDERATION_RULE_ID`` + ``ANTHROPIC_ORGANIZATION_ID`` + + ``ANTHROPIC_IDENTITY_TOKEN[_FILE]`` → direct jwt-bearer + exchange via :class:`WorkloadIdentityCredentials`. Critically, + step 4 sits **between** explicit profile (step 3) and + fallback profile (step 5): a machine with WIF env vars wired + up must use WIF even if a leftover ``default`` profile exists + on disk, but a user who explicitly ``ANTHROPIC_PROFILE=dev`` + still gets their profile. + Step 5: Fallback active profile from disk (``configs/default.json`` + or whatever ``active_config`` points at). Errors at this step + are swallowed and the chain falls through — a corrupt + unselected profile shouldn't break an otherwise-explicit + api_key= path. + + Returns ``None`` when nothing matches — the client will fall back to + its normal "no auth configured" error. + """ + # Step 2a — env api_key: return None so the base client handles X-Api-Key. + if os.environ.get(ENV_API_KEY): + return None + + # Step 2b — env auth_token: static bearer. + auth_token = os.environ.get(ENV_AUTH_TOKEN) + if auth_token: + return CredentialResult(provider=StaticToken(auth_token)) + + # Step 3 — explicit profile selection (ANTHROPIC_PROFILE / ANTHROPIC_CONFIG_DIR + # / active_config pointer). Failures propagate — a user who explicitly + # names a profile expects a broken config to surface, not to fall through. + env_explicit = bool(os.environ.get(ENV_PROFILE) or os.environ.get(ENV_CONFIG_DIR)) + pointer_explicit = _has_explicit_active_config() + if env_explicit or pointer_explicit: + creds_file = CredentialsFile() + creds_file.bind_base_url(base_url) + extra_headers = creds_file.extra_headers() + return CredentialResult( + provider=creds_file, + extra_headers=extra_headers, + base_url=creds_file.resolved_base_url, + ) + + # Step 4 — env-var workload identity federation. Sits above the + # fallback on-disk profile so a machine with WIF env vars uses WIF + # even if a leftover ``default`` profile exists on disk. + federation_result = _build_federation_result(base_url=base_url) + if federation_result is not None: + return federation_result + + # Step 5 — fallback active profile from disk. Errors are swallowed and + # the chain falls through because the user didn't explicitly select + # this profile; a corrupt auto-discovered config shouldn't break + # construction. + if _has_active_profile_config(): + creds_file = CredentialsFile() + creds_file.bind_base_url(base_url) + try: + extra_headers = creds_file.extra_headers() + except AnthropicError: + return None + return CredentialResult( + provider=creds_file, + extra_headers=extra_headers, + base_url=creds_file.resolved_base_url, + ) + + return None diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/_constants.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..0d302f78dfb3a2d1a99e8627c3da31df329fd4a1 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/_constants.py @@ -0,0 +1,249 @@ +from __future__ import annotations + +import os +import sys +import pathlib +from typing import Optional + +from ..._exceptions import AnthropicError + +GRANT_TYPE_JWT_BEARER = "urn:ietf:params:oauth:grant-type:jwt-bearer" +GRANT_TYPE_REFRESH_TOKEN = "refresh_token" +TOKEN_ENDPOINT = "/v1/oauth/token" + +# Seconds to wait on the /v1/oauth/token POST before giving up. Tokens are cheap +# to mint and the handler is fast; a long timeout mostly means a sick backend. +TOKEN_EXCHANGE_TIMEOUT = 30.0 + +# Beta header required on any authenticated API request that uses a Bearer +# token obtained via OAuth/federation (unlocks `Authorization: Bearer` auth +# at all), and on refresh_token grants against /v1/oauth/token. +OAUTH_API_BETA_HEADER = "oauth-2025-04-20" + +# Beta header routing switch for /v1/oauth/token jwt-bearer grants. Presence +# routes the POST to the api-go userauth handler (jwt-bearer only); absence +# routes it to the Python oauth_server (authorization_code / refresh_token). +# MUST only be sent on jwt-bearer exchanges — sending it on refresh_token would +# misroute the request to userauth and fail with "unsupported grant_type". +FEDERATION_BETA_HEADER = "oidc-federation-2026-04-01" + +# Proactive refresh thresholds (seconds before expiry). Tuned for ≤10min token TTL. +ADVISORY_REFRESH_SECONDS = 120 +MANDATORY_REFRESH_SECONDS = 30 + +DEFAULT_PROFILE = "default" +DEFAULT_BASE_URL = "https://api.anthropic.com" + +# Env vars — explicit auth (tier 0) +ENV_API_KEY = "ANTHROPIC_API_KEY" +ENV_AUTH_TOKEN = "ANTHROPIC_AUTH_TOKEN" + +# Env vars — config dir + profile selection (tier 1) +ENV_CONFIG_DIR = "ANTHROPIC_CONFIG_DIR" +ENV_PROFILE = "ANTHROPIC_PROFILE" + +# Env vars — direct workload identity, bypassing config files (tier 2) +ENV_IDENTITY_TOKEN = "ANTHROPIC_IDENTITY_TOKEN" +ENV_IDENTITY_TOKEN_FILE = "ANTHROPIC_IDENTITY_TOKEN_FILE" +ENV_FEDERATION_RULE_ID = "ANTHROPIC_FEDERATION_RULE_ID" +ENV_ORGANIZATION_ID = "ANTHROPIC_ORGANIZATION_ID" +ENV_SERVICE_ACCOUNT_ID = "ANTHROPIC_SERVICE_ACCOUNT_ID" +ENV_WORKSPACE_ID = "ANTHROPIC_WORKSPACE_ID" +ENV_SCOPE = "ANTHROPIC_SCOPE" +ENV_BASE_URL = "ANTHROPIC_BASE_URL" + + +def _user_agent() -> str: # pyright: ignore[reportUnusedFunction] — used by _workload/_providers + """``User-Agent`` value sent on token-endpoint POSTs. + + Computed lazily so this module doesn't need to import ``_version`` at + module load time (the credentials package is otherwise import-light). + """ + from ..._version import __version__ + + return f"anthropic-python/{__version__}" + + +def _config_dir() -> pathlib.Path: + """Resolve the config directory. + + ``ANTHROPIC_CONFIG_DIR`` env var → platform default. + + Platform defaults: + * Linux & macOS: ``~/.config/anthropic/`` — XDG-style on both platforms + for consistency across SDKs (macOS does **not** use + ``~/Library/Application Support/``). + * Windows: ``%APPDATA%\\Anthropic\\`` + """ + env = os.environ.get(ENV_CONFIG_DIR) + if env: + return pathlib.Path(env) + if sys.platform == "win32": + appdata = os.environ.get("APPDATA") + base = pathlib.Path(appdata) if appdata else pathlib.Path.home() / "AppData" / "Roaming" + return base / "Anthropic" + return pathlib.Path.home() / ".config" / "anthropic" + + +def _read_active_config_pointer() -> Optional[str]: + """Return the stripped contents of ``/active_config``, or ``None`` + if the pointer file is missing or empty.""" + try: + name = (_config_dir() / "active_config").read_text(encoding="utf-8").strip() + except OSError: + return None + return name or None + + +def _active_profile() -> str: # pyright: ignore[reportUnusedFunction] — used by _providers + """Resolve the active profile name. + + ``ANTHROPIC_PROFILE`` env var → ``/active_config`` pointer file + → ``"default"`` literal. The resolved name is validated against path- + traversal patterns before being returned. + """ + env = os.environ.get(ENV_PROFILE) + if env: + _validate_profile_name(env, source=ENV_PROFILE) + return env + name = _read_active_config_pointer() + if name is None: + return DEFAULT_PROFILE + _validate_profile_name(name, source="active_config pointer file") + return name + + +def _require_https(url: str, *, field: str) -> None: # pyright: ignore[reportUnusedFunction] — used by _workload/_providers + """Reject non-``https://`` token-endpoint URLs. + + Localhost is allowed for testing so ``base_url="http://localhost:8080"`` + works against a local ``oauth_server`` instance; everything else must be + TLS-encrypted because the body of these POSTs carries the assertion JWT + or a long-lived refresh token. + """ + lowered = url.lower().rstrip("/") + if lowered.startswith("https://"): + return + if lowered.startswith(("http://localhost", "http://127.0.0.1", "http://[::1]")): + return + raise AnthropicError( + f"{field} must use https (got {url!r}); the token-exchange endpoint " + f"carries secret material and cannot be used over cleartext HTTP." + ) + + +def _validate_profile_name(profile: str, *, source: str = "profile name") -> None: + """Reject profile names that could escape the config directory. + + Profile names come from user-controlled sources (``ANTHROPIC_PROFILE``, + the ``active_config`` pointer file, ``CredentialsFile(profile=...)``) and + are interpolated into filesystem paths. A value like ``"../../etc/shadow"`` + would otherwise let a read of ``configs/.json`` escape the config + root entirely. Pass ``source=`` so the error message names where the bad + value came from. + """ + if not profile: + raise AnthropicError(f"{source} must not be empty.") + if profile != profile.strip(): + raise AnthropicError(f"{source} {profile!r} has leading or trailing whitespace.") + if profile.startswith("."): + raise AnthropicError(f"{source} {profile!r} must not start with a dot.") + for sep in ("/", "\\", os.sep): + if sep and sep in profile: + raise AnthropicError( + f"{source} {profile!r} must not contain path separators — " + f"profiles are filenames under the config directory. Pick a name without {sep!r}." + ) + if "\x00" in profile: + raise AnthropicError(f"{source} {profile!r} must not contain null bytes.") + + +def _resolve_under(base: pathlib.Path, candidate: pathlib.Path) -> pathlib.Path: + """Assert ``candidate`` resolves to a descendant of ``base``, return it verbatim. + + The containment check uses ``resolve(strict=False)`` on both sides so + symlinks and ``..`` segments are normalized for the purposes of escape + detection. The returned path is the *original* (unresolved) candidate — + callers that care about symlink following must handle it themselves + (e.g. ``os.stat(follow_symlinks=False)``). + """ + base_resolved = base.resolve(strict=False) + candidate_resolved = candidate.resolve(strict=False) + try: + candidate_resolved.relative_to(base_resolved) + except ValueError as err: + raise AnthropicError( + f"Resolved path {candidate_resolved} escapes config directory {base_resolved}." + ) from err + return candidate + + +def _config_file_path(profile: str) -> pathlib.Path: # pyright: ignore[reportUnusedFunction] — used by _providers + """Path to ``/configs/.json`` (non-secret, 0644).""" + _validate_profile_name(profile) + base = _config_dir() + return _resolve_under(base, base / "configs" / f"{profile}.json") + + +def _credentials_file_path(profile: str) -> pathlib.Path: # pyright: ignore[reportUnusedFunction] — used by _providers + """Path to ``/credentials/.json`` (secret, 0600).""" + _validate_profile_name(profile) + base = _config_dir() + return _resolve_under(base, base / "credentials" / f"{profile}.json") + + +def _has_active_profile_config() -> bool: # pyright: ignore[reportUnusedFunction] — used by _chain + """Tighter auto-discover check for the tier-1 credential chain. + + Returns ``True`` only if the *active* profile's config file exists. The + previous version returned ``True`` for any ``.json`` under ``configs/``, + which meant a stray ``configs/work.json`` on disk was enough to steer + ``default_credentials()`` into reading ``configs/default.json`` and + failing because ``default.json`` wasn't there. + """ + try: + return _config_file_path(_active_profile()).is_file() + except (OSError, AnthropicError): + return False + + +def _has_explicit_active_config() -> bool: # pyright: ignore[reportUnusedFunction] — used by _chain + """True if the user wrote a non-empty ``active_config`` pointer file. + + This is an explicit opt-in signal equivalent to setting ``ANTHROPIC_PROFILE``: + the user has told us which profile to load. If the target config file is + missing or malformed, the chain should surface that error rather than + silently falling through — matching how ``ANTHROPIC_PROFILE=missing`` + behaves today. + """ + return _read_active_config_pointer() is not None + + +def resolve_identity_token_path(path: str | os.PathLike[str] | None = None) -> pathlib.Path | None: + """ctor arg → ``ANTHROPIC_IDENTITY_TOKEN_FILE`` → ``None``.""" + if path is not None: + return pathlib.Path(path) + env = os.environ.get(ENV_IDENTITY_TOKEN_FILE) + if env: + return pathlib.Path(env) + return None + + +def _has_auto_discoverable_credentials() -> bool: # pyright: ignore[reportUnusedFunction] — used by _client + """True if the environment / filesystem contains signals that would + normally drive the tier-1 (profile) or tier-2 (env federation) paths of + :func:`default_credentials`. + + Used by the shadow-warning detection in the client constructor: if a + static ``ANTHROPIC_API_KEY`` / ``ANTHROPIC_AUTH_TOKEN`` is set alongside + any of these signals, the auto-discovery would have yielded a credential + but got silently shadowed — and the user should know. + """ + if os.environ.get(ENV_PROFILE) or os.environ.get(ENV_CONFIG_DIR): + return True + if _has_explicit_active_config(): + return True + if os.environ.get(ENV_FEDERATION_RULE_ID) and os.environ.get(ENV_ORGANIZATION_ID): + if os.environ.get(ENV_IDENTITY_TOKEN_FILE) or os.environ.get(ENV_IDENTITY_TOKEN): + return True + return False diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/_providers.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/_providers.py new file mode 100644 index 0000000000000000000000000000000000000000..9c7b0b80bbfd46cd6d3324be86dcaf6665f98b75 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/_providers.py @@ -0,0 +1,825 @@ +from __future__ import annotations + +import os +import json +import stat +import time +import logging +import pathlib +import tempfile +from typing import TYPE_CHECKING, Any, Dict, Union, Optional, cast +from typing_extensions import override + +import httpx + +from ._types import AccessToken, IdentityTokenProvider +from ._constants import ( + ENV_SCOPE, + ENV_PROFILE, + ENV_BASE_URL, + ENV_AUTH_TOKEN, + ENV_CONFIG_DIR, + TOKEN_ENDPOINT, + DEFAULT_BASE_URL, + ENV_WORKSPACE_ID, + ENV_ORGANIZATION_ID, + OAUTH_API_BETA_HEADER, + ENV_FEDERATION_RULE_ID, + ENV_SERVICE_ACCOUNT_ID, + TOKEN_EXCHANGE_TIMEOUT, + ENV_IDENTITY_TOKEN_FILE, + GRANT_TYPE_REFRESH_TOKEN, + MANDATORY_REFRESH_SECONDS, + _user_agent, + _require_https, + _active_profile, + _config_file_path, + _credentials_file_path, + resolve_identity_token_path, +) +from ..._exceptions import AnthropicError + +log: logging.Logger = logging.getLogger(__name__) + +if TYPE_CHECKING: + from ._workload import WorkloadIdentityCredentials + +__all__ = ["StaticToken", "EnvToken", "CredentialsFile", "InMemoryConfig", "IdentityTokenFile"] + + +def _coerce_expires_at(value: Any, source: Optional[pathlib.Path]) -> Optional[int]: + """Parse a credentials-file ``expires_at`` field into Unix seconds.""" + if value is None: + return None + try: + return int(value) + except (TypeError, ValueError) as err: + where = f"credentials file at {source}" if source is not None else "credentials" + raise AnthropicError( + f"{where} has invalid 'expires_at' {value!r}; expected an integer " + f"Unix timestamp in seconds. The SDK does not parse ISO8601 — convert " + f"with int(datetime.timestamp()) before writing the file." + ) from err + + +# Discriminator written to credentials/.json. Only one value in v1; +# future credential shapes (e.g. private key material) get their own. +CREDENTIALS_FILE_TYPE = "oauth_token" + +# On-disk file-format versions. Absent on read = 1 (current shape). +CONFIG_FILE_VERSION = "1.0" +CREDENTIALS_FILE_VERSION = "1.0" + +# Discriminator values for the config file's ``authentication.type`` field. +AUTH_TYPE_OIDC_FEDERATION = "oidc_federation" +AUTH_TYPE_USER_OAUTH = "user_oauth" + + +def _fill_missing_from_env(config: Dict[str, Any], auth: Dict[str, Any]) -> None: + """Fill empty profile fields from corresponding ANTHROPIC_* env vars. + + The profile file is authoritative — this only fills fields the file left + unset. Empty-string env values are treated as unset. + """ + + def fill(target: Dict[str, Any], key: str, env_var: str) -> None: + # Absent-key and empty-string profile values are both treated as unset. + if not target.get(key): + v = os.environ.get(env_var) + if v: + target[key] = v + + fill(config, "base_url", ENV_BASE_URL) + fill(config, "organization_id", ENV_ORGANIZATION_ID) + fill(config, "workspace_id", ENV_WORKSPACE_ID) + + auth_type = auth.get("type") + if auth_type == AUTH_TYPE_OIDC_FEDERATION: + fill(auth, "federation_rule_id", ENV_FEDERATION_RULE_ID) + fill(auth, "service_account_id", ENV_SERVICE_ACCOUNT_ID) + fill(auth, "scope", ENV_SCOPE) + if not auth.get("identity_token"): + v = os.environ.get(ENV_IDENTITY_TOKEN_FILE) + if v: + auth["identity_token"] = {"source": "file", "path": v} + elif auth_type == AUTH_TYPE_USER_OAUTH: + fill(auth, "scope", ENV_SCOPE) + + +class StaticToken: + """An :class:`AccessTokenProvider` that always returns a fixed token with no expiry.""" + + def __init__(self, token: str) -> None: + self._token = token + + def __call__(self, *, force_refresh: bool = False) -> AccessToken: + del force_refresh # no provider-side cache to bypass + return AccessToken(token=self._token, expires_at=None) + + +class EnvToken: + """An :class:`AccessTokenProvider` that reads ``ANTHROPIC_AUTH_TOKEN`` at call time.""" + + def __init__(self, env_var: str = ENV_AUTH_TOKEN) -> None: + self._env_var = env_var + + def __call__(self, *, force_refresh: bool = False) -> AccessToken: + del force_refresh + value = os.environ.get(self._env_var) + if value is None: + raise AnthropicError( + f"Environment variable {self._env_var} is not set. " + f"Set it or pass an explicit `credentials=` provider to the client." + ) + return AccessToken(token=value, expires_at=None) + + +class CredentialsFile: + """An :class:`AccessTokenProvider` backed by a named profile. + + A profile is a pair of files under the config directory + (``~/.config/anthropic/`` by default; override with ``ANTHROPIC_CONFIG_DIR``): + + * ``configs/.json`` — non-secret. Holds the nested + ``"authentication"`` object (discriminated by its ``"type"`` field), plus + top-level ``organization_id``, ``workspace_id``, and ``base_url``. + The ``authentication`` object may contain a ``credentials_path`` field + overriding the credentials file location. + * ``credentials/.json`` — secret (0600). Holds ``access_token``, + ``expires_at``, and (for ``user_oauth`` with a ``client_id``) + ``refresh_token``. + + The split keeps secret material out of files that may need to be readable + by config-only consumers, and lets the SDK enforce 0600 on the credentials + file without locking out config readers. + + Dispatches on the ``authentication.type`` discriminator: + + ``"oidc_federation"`` + OIDC workload identity federation. Lazily constructs a + :class:`WorkloadIdentityCredentials` delegate from the nested auth + fields plus the top-level ``organization_id`` and calls it to perform + the jwt-bearer exchange. + + ``"user_oauth"`` + Output of an interactive PKCE login. If the auth block has a + ``client_id``, performs ``refresh_token`` grants on expiry and + writes the new tokens back to the credentials file (atomic replace, + refresh-token rotation supported). Without a ``client_id``, the + credentials file is treated as externally rotated — the SDK re-reads + it on every invocation and returns whatever ``access_token`` is + there, no refresh grant attempted. This is the pattern for a + sidecar/daemon that mints the access token out-of-band. + + Args: + profile: Profile name. ``None`` resolves via ``ANTHROPIC_PROFILE`` env + → ``/active_config`` pointer file → ``"default"``. + """ + + def __init__( + self, + profile: Optional[str] = None, + *, + http_client: Optional[httpx.Client] = None, + ) -> None: + self._profile = profile if profile is not None else _active_profile() + self._config_path = _config_file_path(self._profile) + self._bound_base_url: Optional[str] = None + self._http_client = http_client + self._owned_http_client: Optional[httpx.Client] = None + + # Populated on first __call__ — keeps construction cheap and exception-free + # so the chain can construct us optimistically after an existence check. + self._config: Optional[Dict[str, Any]] = None + self._credentials_path: Optional[pathlib.Path] = None + self._base_url: str = DEFAULT_BASE_URL + self._workload_delegate: Optional[WorkloadIdentityCredentials] = None + + @property + def profile(self) -> str: + return self._profile + + @property + def config_path(self) -> pathlib.Path: + return self._config_path + + @property + def resolved_base_url(self) -> Optional[str]: + """The ``base_url`` declared in the profile config file, if any. + + Returns ``None`` when the config has no top-level ``base_url`` key — + callers should fall back to their own default rather than the + provider's bound/default value, so a profile that *doesn't* pin a + host never overrides an explicit client setting. Loads the config + on first access. + """ + config = self._load_config() + raw = config.get("base_url") + return str(raw).rstrip("/") if raw else None + + def bind_base_url(self, base_url: str) -> None: + """Adopt the owning client's ``base_url`` as a fallback for the token + exchange. Slots between the config file's own ``base_url`` field and + the hard-coded default; a ``base_url`` in the config file still wins. + + The owning client binds exactly once at construction; sharing one + instance across clients with different ``base_url`` values is + unsupported and silently picks the last bind when the config file + doesn't pin a host. + """ + bound = base_url.rstrip("/") + # Validate eagerly so an invalid bind fails at bind time, not at the + # subsequent _load_config() — matches WorkloadIdentityCredentials. + _require_https(bound, field=f"{self._config_path}: base_url") + self._bound_base_url = bound + if self._config is not None: + self._base_url = self._resolve_base_url(self._config) + _require_https(self._base_url, field=f"{self._config_path}: base_url") + + def _resolve_base_url(self, config: Dict[str, Any]) -> str: + """base_url precedence: top-level config field → bound (the owning + client's base_url, via :meth:`bind_base_url`) → default. Validated + against the scheme/TLS rules so a malicious config with + ``base_url="http://evil/"`` can't exfiltrate the assertion or refresh + token.""" + if config.get("base_url"): + return str(config["base_url"]).rstrip("/") + if self._bound_base_url is not None: + return self._bound_base_url + return DEFAULT_BASE_URL + + def extra_headers(self) -> Dict[str, str]: + """Return headers derived from the config file (e.g. ``workspace_id``). + + Eagerly reads the config if not yet loaded. The returned dict is + suitable for merging into the client's default headers. + """ + config = self._load_config() + headers: Dict[str, str] = {} + # For federation profiles workspace_id is sent in the jwt-bearer + # exchange body, not as a request header (the minted token is already + # workspace-scoped, so the header would be ignored). + if self._auth_block().get("type") != AUTH_TYPE_OIDC_FEDERATION: + workspace_id = config.get("workspace_id") + if workspace_id: + headers["anthropic-workspace-id"] = str(workspace_id) + return headers + + # -- file IO ----------------------------------------------------------- + + def _load_config(self) -> Dict[str, Any]: + """Read and cache the config file, resolving ``base_url`` and ``credentials_path``.""" + if self._config is not None: + return self._config + + try: + raw = self._config_path.read_text(encoding="utf-8") + except FileNotFoundError as err: + raise AnthropicError( + f"Config file not found at {self._config_path} (profile {self._profile!r}). " + f"Set {ENV_PROFILE} to select a different profile, or set {ENV_CONFIG_DIR} " + f"to relocate the config directory." + ) from err + except (OSError, UnicodeDecodeError) as err: + raise AnthropicError(f"Config file at {self._config_path} could not be read: {err}") from err + try: + raw_config: Any = json.loads(raw) + except json.JSONDecodeError as err: + raise AnthropicError(f"Config file at {self._config_path} is not valid JSON: {err}") from err + + if not isinstance(raw_config, dict): + raise AnthropicError( + f"Config file at {self._config_path} must contain a JSON object, not {type(raw_config).__name__}." + ) + config = cast("Dict[str, Any]", raw_config) + + raw_auth = config.get("authentication") + if not isinstance(raw_auth, dict): + raise AnthropicError( + f"Config file at {self._config_path} is missing the 'authentication' object. " + f'Expected shape: {{"authentication": {{"type": ' + f'"{AUTH_TYPE_OIDC_FEDERATION}"|"{AUTH_TYPE_USER_OAUTH}", ...}}, ...}}' + ) + auth = cast("Dict[str, Any]", raw_auth) + + # Env-vars fill only what the file left empty; runs before derived + # state (base_url, identity_token path) is resolved. + _fill_missing_from_env(config, auth) + + self._base_url = self._resolve_base_url(config) + _require_https(self._base_url, field=f"{self._config_path}: base_url") + + override = auth.get("credentials_path") + if override: + self._credentials_path = pathlib.Path(str(override)).expanduser() + else: + self._credentials_path = _credentials_file_path(self._profile) + + self._config = config + return config + + def _read_credentials(self) -> Dict[str, Any]: + """Read the credentials file. Re-reads on every call — daemons rotate it. + + On Unix, verifies the file is not group/world-readable. World-readable + credentials files are refused outright; group-readable files log a + warning but are accepted. The check is skipped on Windows where POSIX + mode bits don't carry the same meaning. + """ + assert self._credentials_path is not None # set by _load_config + path = self._credentials_path + if os.name == "posix": + try: + file_stat = os.stat(path, follow_symlinks=False) + except FileNotFoundError as err: + raise AnthropicError(f"Credentials file not found at {path} (profile {self._profile!r}).") from err + except OSError as err: + raise AnthropicError(f"Credentials file at {path} could not be accessed: {err}") from err + if stat.S_ISLNK(file_stat.st_mode): + raise AnthropicError( + f"Credentials file at {path} is a symlink; refusing to follow " + f"(move the real file into place to keep secret material on the expected filesystem)." + ) + mode = stat.S_IMODE(file_stat.st_mode) + if mode & 0o004: + raise AnthropicError( + f"Credentials file at {path} is world-readable (mode {mode:#o}); " + f"run `chmod 600 {path}` before retrying." + ) + if mode & 0o070: + log.warning( + "Credentials file at %s is group-readable (mode %#o); consider `chmod 600 %s`.", + path, + mode, + path, + ) + try: + raw = path.read_text(encoding="utf-8") + except FileNotFoundError as err: + raise AnthropicError(f"Credentials file not found at {path} (profile {self._profile!r}).") from err + except (OSError, UnicodeDecodeError) as err: + raise AnthropicError(f"Credentials file at {path} could not be read: {err}") from err + try: + creds: Dict[str, Any] = json.loads(raw) + except json.JSONDecodeError as err: + raise AnthropicError(f"Credentials file at {path} is not valid JSON: {err}") from err + + # Validate discriminator if present; lenient if absent so hand-written + # or older files keep working. Catches config/credentials drift early. + actual = creds.get("type") + if actual is not None and actual != CREDENTIALS_FILE_TYPE: + assert self._config is not None # _load_config always precedes _read_credentials + auth_type = self._config["authentication"].get("type") + raise AnthropicError( + f"credentials file has type {actual!r}; expected {CREDENTIALS_FILE_TYPE!r} " + f"for authentication.type {auth_type!r}" + ) + return creds + + def _get_http_client(self) -> httpx.Client: + """Return an ``httpx.Client``, lazily creating (and tracking) one we own.""" + if self._http_client is not None: + return self._http_client + if self._owned_http_client is None: + self._owned_http_client = httpx.Client(timeout=TOKEN_EXCHANGE_TIMEOUT) + return self._owned_http_client + + def close(self) -> None: + """Close the owned ``httpx.Client`` if we created one.""" + if self._owned_http_client is not None: + self._owned_http_client.close() + self._owned_http_client = None + if self._workload_delegate is not None: + self._workload_delegate.close() + + def reload(self) -> None: + """Drop the cached config so the next call re-reads it from disk. + + ``CredentialsFile`` caches the parsed config across calls to keep the + hot path cheap; a daemon that rotates a profile in place (e.g. flips + ``"type": "user_oauth"`` to ``"type": "oidc_federation"``) will not be + picked up automatically. Callers that need to react to such changes + can call ``reload()`` to force a fresh read on the next ``__call__``. + """ + self._config = None + self._workload_delegate = None + + def _atomic_write_credentials(self, data: Dict[str, Any]) -> None: + """Atomic write to the credentials file (NOT the config file).""" + assert self._credentials_path is not None + parent = self._credentials_path.parent + parent.mkdir(parents=True, exist_ok=True, mode=0o700) + # mkstemp gives a unique temp name so concurrent writers (e.g. + # gunicorn workers cold-starting together) don't race on a fixed + # ``.tmp`` path; whichever os.replace lands last wins, which is fine + # for a best-effort cache. + fd, tmp = tempfile.mkstemp(dir=parent, prefix=f".{self._credentials_path.name}.", suffix=".tmp") + try: + try: + os.fchmod(fd, 0o600) + os.write(fd, json.dumps(data, indent=2).encode("utf-8")) + os.fsync(fd) + finally: + os.close(fd) + os.replace(tmp, self._credentials_path) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + # fsync the parent directory so the rename itself survives a crash on + # filesystems that defer directory-entry writes. Best-effort: Windows + # and some POSIX flavours don't support directory fds. + try: + dir_fd = os.open(parent, os.O_RDONLY) + try: + os.fsync(dir_fd) + finally: + os.close(dir_fd) + except OSError: + pass + + # -- dispatch ---------------------------------------------------------- + + def _auth_block(self) -> Dict[str, Any]: + """Return the cached ``authentication`` sub-object from the config file.""" + config = self._load_config() + return cast("Dict[str, Any]", config["authentication"]) + + def __call__(self, *, force_refresh: bool = False) -> AccessToken: + auth = self._auth_block() + auth_type = auth.get("type") + + if auth_type == AUTH_TYPE_OIDC_FEDERATION: + return self._call_oidc_federation(auth, force_refresh=force_refresh) + + if auth_type == AUTH_TYPE_USER_OAUTH: + return self._call_user_oauth(auth, force_refresh=force_refresh) + + raise AnthropicError( + f"Unknown authentication.type {auth_type!r} at {self._config_path}. " + f"Expected {AUTH_TYPE_OIDC_FEDERATION!r} or {AUTH_TYPE_USER_OAUTH!r}." + ) + + # -- "user_oauth" ----------------------------------------------------- + + def _call_user_oauth(self, auth: Dict[str, Any], *, force_refresh: bool = False) -> AccessToken: + """Interactive-login profile. With a ``client_id`` in the auth block, + we run the refresh_token grant on expiry; without one, we treat the + credentials file as externally rotated and just read it fresh. + """ + from ._workload import WorkloadIdentityError, _raise_token_endpoint_error + + creds = self._read_credentials() + access_token = creds.get("access_token") + if not access_token: + raise AnthropicError(f"Credentials file at {self._credentials_path} is missing 'access_token'.") + + client_id = auth.get("client_id") + if not client_id: + # No client_id → externally rotated. Return whatever the file has; + # a sidecar/daemon is responsible for keeping it fresh. + expires_at = _coerce_expires_at(creds.get("expires_at"), self._credentials_path) + return AccessToken(token=access_token, expires_at=expires_at) + + refresh_token = creds.get("refresh_token") + if not refresh_token: + raise WorkloadIdentityError( + f"credentials file for profile {self._profile!r} (authentication.type " + f"{AUTH_TYPE_USER_OAUTH!r} with client_id) must include 'refresh_token': " + f"{self._credentials_path}" + ) + + # Strict expiry only — TokenCache owns the advisory/mandatory refresh + # policy. A second threshold here could trigger a refresh grant while + # the outer cache is still serving fine. + # force_refresh (set by TokenCache.invalidate after a 401) bypasses + # the disk-freshness short-circuit so a revoked token isn't re-served. + expires_at = _coerce_expires_at(creds.get("expires_at"), self._credentials_path) + if not force_refresh and expires_at is not None and time.time() < expires_at: + return AccessToken(token=access_token, expires_at=expires_at) + + body: Dict[str, str] = { + "grant_type": GRANT_TYPE_REFRESH_TOKEN, + "refresh_token": refresh_token, + "client_id": client_id, + } + + try: + resp = self._get_http_client().post( + f"{self._base_url}{TOKEN_ENDPOINT}", + json=body, + headers={ + "Content-Type": "application/json", + # oauth-2025-04-20 unlocks the token endpoint family. Do + # NOT send oidc-federation-2026-04-01 — that's a routing + # switch that misroutes refresh_token grants to the Go + # userauth handler, which only accepts jwt-bearer. + "anthropic-beta": OAUTH_API_BETA_HEADER, + "User-Agent": _user_agent(), + }, + ) + except httpx.HTTPError as err: + raise WorkloadIdentityError(f"user_oauth refresh failed to reach token endpoint: {err}") from err + + if resp.status_code != 200: + _raise_token_endpoint_error(resp, message_prefix="user_oauth refresh failed") + + payload: Dict[str, Any] = resp.json() + new_access = payload.get("access_token") + if not new_access: + raise WorkloadIdentityError("user_oauth refresh response missing 'access_token'") + raw_expires_in = payload.get("expires_in", 3600) + try: + expires_in = int(raw_expires_in) + except (TypeError, ValueError) as err: + raise WorkloadIdentityError( + f"user_oauth refresh response has invalid 'expires_in' {raw_expires_in!r}; " + f"expected an integer number of seconds." + ) from err + new_expires_at = int(time.time()) + expires_in + new_refresh = payload.get("refresh_token") or refresh_token + + creds["version"] = CREDENTIALS_FILE_VERSION + creds["type"] = CREDENTIALS_FILE_TYPE + creds["access_token"] = new_access + creds["expires_at"] = new_expires_at + creds["refresh_token"] = new_refresh + self._atomic_write_credentials(creds) + + return AccessToken(token=new_access, expires_at=new_expires_at) + + # -- "oidc_federation" ------------------------------------------------ + + def _read_credentials_if_exists(self) -> Optional[Dict[str, Any]]: + """``_read_credentials`` variant that returns ``None`` on absence + instead of raising — used by the federation disk-cache path where a + missing credentials file just means "exchange now". + """ + assert self._credentials_path is not None + if not self._credentials_path.exists(): + return None + try: + return self._read_credentials() + except AnthropicError as err: + if isinstance(err.__cause__, FileNotFoundError): + return None + raise + + def _call_oidc_federation(self, auth: Dict[str, Any], *, force_refresh: bool = False) -> AccessToken: + if self._workload_delegate is None: + self._workload_delegate = self._build_workload_delegate(auth) + + # Disk cache: if a prior exchange wrote credentials/.json and + # the token there is unexpired, return it instead of re-exchanging. + # The in-memory TokenCache layer applies the proactive 120s/30s policy + # on top of this; the disk cache only matters across process restarts. + # ``_credentials_path`` is always set for ``CredentialsFile`` proper + # (``_load_config`` defaults it); subclasses (``InMemoryConfig``) + # leave it ``None`` to opt out of the disk cache entirely. + if self._credentials_path is None: + return self._workload_delegate() + + # force_refresh (set by TokenCache.invalidate after a 401) bypasses + # the disk-cache short-circuit so a revoked token isn't re-served. + cached = self._read_credentials_if_exists() + if not force_refresh and cached is not None: + access_token = cached.get("access_token") + expires_at = cached.get("expires_at") + try: + if ( + access_token + and expires_at is not None + and time.time() < float(expires_at) - MANDATORY_REFRESH_SECONDS + ): + return AccessToken(token=str(access_token), expires_at=int(expires_at)) + except (TypeError, ValueError): + # corrupted expires_at — fall through to re-exchange and overwrite + pass + + token = self._workload_delegate() + try: + self._atomic_write_credentials( + { + **(cached or {}), + "version": CREDENTIALS_FILE_VERSION, + "type": CREDENTIALS_FILE_TYPE, + "access_token": token.token, + "expires_at": token.expires_at, + } + ) + except OSError as err: + log.debug("federation token disk-cache write-back failed (best-effort): %s", err) + return token + + def _build_workload_delegate(self, auth: Dict[str, Any]) -> WorkloadIdentityCredentials: + # Import here to avoid a circular import (_workload imports nothing from + # _providers so the dependency is one-way at runtime). + from ._workload import WorkloadIdentityError, WorkloadIdentityCredentials + + federation_rule_id = auth.get("federation_rule_id") + assert self._config is not None # _load_config precedes dispatch + organization_id = self._config.get("organization_id") + if not federation_rule_id or not organization_id: + raise WorkloadIdentityError( + f"config file with authentication.type {AUTH_TYPE_OIDC_FEDERATION!r} must include " + f"'authentication.federation_rule_id' and top-level 'organization_id': " + f"{self._config_path}" + ) + + # identity_token is a discriminated object so future variants (url, + # executable, aws_sigv4) slot in without renaming. v1 implements + # source:"file" only. Absent → fall back to ANTHROPIC_IDENTITY_TOKEN_FILE. + identity_token_cfg = auth.get("identity_token") + if identity_token_cfg is not None: + source = identity_token_cfg.get("source") + if source != "file": + raise AnthropicError(f"identity_token source {source!r} is not supported; only 'file' is implemented") + identity_token_path = identity_token_cfg.get("path") + if not identity_token_path: + # Empty/missing path is a config bug, not an env-var fallback + # signal — the source explicitly says "file", which has no + # meaning without a path. Without this check we'd silently + # fall through to ANTHROPIC_IDENTITY_TOKEN_FILE and override + # user intent. + raise AnthropicError( + f"identity_token source 'file' requires a non-empty path; " + f"profile {self._profile!r} at {self._config_path} has identity_token={identity_token_cfg!r}." + ) + else: + identity_token_path = None + provider = IdentityTokenFile(identity_token_path) if identity_token_path else IdentityTokenFile() + + # The delegate borrows our owned httpx.Client: passing http_client= + # sets _owns_http_client=False on the delegate so its close() is a + # no-op. CredentialsFile.close() remains the single closer. + delegate = WorkloadIdentityCredentials( + identity_token_provider=provider, + federation_rule_id=federation_rule_id, + organization_id=organization_id, + service_account_id=auth.get("service_account_id"), + workspace_id=self._config.get("workspace_id"), + scope=auth.get("scope"), + http_client=self._get_http_client(), + ) + delegate.bind_base_url(self._base_url) + return delegate + + +class IdentityTokenFile: + """An :class:`IdentityTokenProvider` that reads a JWT from a file on every call. + + Kubernetes projected service-account tokens (and similar) are rotated in place, + so the file MUST be re-read on every invocation rather than cached. + """ + + def __init__(self, path: Union[str, "os.PathLike[str]", None] = None) -> None: + resolved = resolve_identity_token_path(path) + if resolved is None: + raise AnthropicError( + f"No identity token file path given. Pass `path=` or set the {ENV_IDENTITY_TOKEN_FILE} " + f"environment variable." + ) + self._path = resolved + + @property + def path(self) -> pathlib.Path: + return self._path + + def __call__(self) -> str: + try: + content = self._path.read_text(encoding="utf-8").strip() + except FileNotFoundError as err: + raise AnthropicError(f"Identity token file not found at {self._path}.") from err + except PermissionError as err: + raise AnthropicError( + f"Identity token file at {self._path} is not readable by this process: {err}. " + f"Check the file mode and the effective uid of the process." + ) from err + except IsADirectoryError as err: + raise AnthropicError( + f"Identity token path {self._path} is a directory, not a file. " + f"Point at the projected token file itself." + ) from err + except (OSError, UnicodeDecodeError) as err: + raise AnthropicError(f"Identity token file at {self._path} could not be read: {err}") from err + if not content: + raise AnthropicError( + f"Identity token file at {self._path} is empty. " + f"If this is a Kubernetes projected service-account token, check the " + f"volume mount and the serviceAccountToken projection audience." + ) + return content + + +class InMemoryConfig(CredentialsFile): + """An :class:`AccessTokenProvider` driven by an in-memory config dict + (same shape as ``configs/.json``) rather than files on disk. + + Intended for callers that want to construct an :class:`anthropic.Anthropic` + client with a fully programmatic credentials setup — equivalent to the Go + SDK's ``option.WithConfig`` / TypeScript SDK's ``ClientOptions.config``. + + Both ``authentication.type`` discriminator values are supported: + + ``"oidc_federation"`` + ``authentication.credentials_path`` is **optional**. If set, exchanged + tokens are cached to / read from that file (same atomic 0600 write as + :class:`CredentialsFile`). If omitted, every call performs a fresh + jwt-bearer exchange with no on-disk cache. + + ``"user_oauth"`` + ``authentication.credentials_path`` is **required** — it is where the + access/refresh tokens live. Behaviour is identical to a file-backed + :class:`CredentialsFile` profile of the same shape. + + The implementation subclasses :class:`CredentialsFile` so the dispatch, + refresh-grant, disk-cache and atomic-write logic are shared verbatim; + only config loading and identity-token resolution are overridden. + """ + + _IN_MEMORY_PATH = pathlib.Path("") + + def __init__( + self, + config: Dict[str, Any], + *, + identity_token_provider: Optional[IdentityTokenProvider] = None, + http_client: Optional[httpx.Client] = None, + ) -> None: + raw_auth = config.get("authentication") + if not isinstance(raw_auth, dict): + raise AnthropicError( + "config dict is missing the 'authentication' object. " + f'Expected shape: {{"authentication": {{"type": "{AUTH_TYPE_OIDC_FEDERATION}"' + f'|"{AUTH_TYPE_USER_OAUTH}", ...}}, ...}}' + ) + auth = cast("Dict[str, Any]", raw_auth) + auth_type = auth.get("type") + if auth_type not in (AUTH_TYPE_OIDC_FEDERATION, AUTH_TYPE_USER_OAUTH): + raise AnthropicError( + f"Unknown authentication.type {auth_type!r}. " + f"Expected {AUTH_TYPE_OIDC_FEDERATION!r} or {AUTH_TYPE_USER_OAUTH!r}." + ) + + credentials_path = auth.get("credentials_path") + if auth_type == AUTH_TYPE_USER_OAUTH and not credentials_path: + raise AnthropicError( + f"authentication.type {AUTH_TYPE_USER_OAUTH!r} requires " + f"'authentication.credentials_path' (where the access/refresh tokens live). " + f"For profile-based resolution, use CredentialsFile instead." + ) + + # CredentialsFile state — set directly rather than calling super().__init__() + # because the parent constructor reads env/disk for profile resolution. + self._profile = "" + self._config_path = self._IN_MEMORY_PATH + self._bound_base_url: Optional[str] = None + self._http_client = http_client + self._owned_http_client: Optional[httpx.Client] = None + self._workload_delegate: Optional[WorkloadIdentityCredentials] = None + self._identity_token_provider_override = identity_token_provider + + self._config = config + self._credentials_path = pathlib.Path(str(credentials_path)).expanduser() if credentials_path else None + self._base_url = self._resolve_base_url(config) + _require_https(self._base_url, field="config: base_url") + + @override + def _load_config(self) -> Dict[str, Any]: + assert self._config is not None + return self._config + + @override + def reload(self) -> None: + # Config is fixed at construction; only drop the workload delegate so + # a re-exchange picks up rotated identity-token state. + self._workload_delegate = None + + @override + def _build_workload_delegate(self, auth: Dict[str, Any]) -> WorkloadIdentityCredentials: + if self._identity_token_provider_override is None: + return super()._build_workload_delegate(auth) + + from ._workload import WorkloadIdentityError, WorkloadIdentityCredentials + + federation_rule_id = auth.get("federation_rule_id") + assert self._config is not None + organization_id = self._config.get("organization_id") + if not federation_rule_id or not organization_id: + raise WorkloadIdentityError( + f"config dict with authentication.type {AUTH_TYPE_OIDC_FEDERATION!r} must include " + f"'authentication.federation_rule_id' and top-level 'organization_id'" + ) + delegate = WorkloadIdentityCredentials( + identity_token_provider=self._identity_token_provider_override, + federation_rule_id=federation_rule_id, + organization_id=organization_id, + service_account_id=auth.get("service_account_id"), + workspace_id=self._config.get("workspace_id"), + scope=auth.get("scope"), + http_client=self._get_http_client(), + ) + delegate.bind_base_url(self._base_url) + return delegate diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/_types.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/_types.py new file mode 100644 index 0000000000000000000000000000000000000000..edf3a328ca3cb042258c167145f76714f5279b7e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/_types.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +from typing import Dict, Callable, Optional, Protocol +from dataclasses import field, dataclass + + +def _empty_headers() -> Dict[str, str]: + return {} + + +__all__ = ["AccessToken", "AccessTokenProvider", "IdentityTokenProvider", "CredentialResult"] + + +@dataclass(frozen=True) +class AccessToken: + """An Anthropic API access token with optional expiry. + + ``expires_at`` is unix seconds; ``None`` means no expiry information + (the token will be treated as never-expires by :class:`TokenCache`). + """ + + token: str + expires_at: Optional[int] = None + + +class AccessTokenProvider(Protocol): + """Callable that mints or returns a cached access token. + + Re-invoking the provider IS the refresh mechanism — providers have no + separate ``refresh()`` method. Providers may be stateful (hold config / + paths) but the *cache* lives in :class:`TokenCache`, not here. + + The optional ``force_refresh`` flag is set by + :meth:`TokenCache.invalidate` after a 401: providers with on-disk caches + (user_oauth, oidc_federation) must bypass their freshness short-circuit + and always fetch fresh when it is True. Providers without a cache can + accept and ignore the flag. + """ + + def __call__(self, *, force_refresh: bool = False) -> AccessToken: ... + + +# Innermost layer: returns the raw external JWT string (used as the +# ``identity_token_provider`` argument to :class:`WorkloadIdentityCredentials`). +IdentityTokenProvider = Callable[[], str] + + +@dataclass(frozen=True) +class CredentialResult: + """Bundles an :class:`AccessTokenProvider` with config-level metadata. + + Returned by :func:`default_credentials`. The ``extra_headers`` dict + carries headers that should be set on every API request (e.g. + ``anthropic-workspace-id``). The client merges these into its default + headers at construction time. + + ``base_url`` is the API host the resolved profile is configured for + (e.g. a staging endpoint). The client adopts it as its request + ``base_url`` *only* when the user did not supply one explicitly via + the ``base_url=`` kwarg or ``ANTHROPIC_BASE_URL`` — see the + constructor in ``_client.py``. ``None`` means the profile did not + specify a host and the client keeps its own default. + """ + + provider: AccessTokenProvider + extra_headers: Dict[str, str] = field(default_factory=_empty_headers) + base_url: Optional[str] = None diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/_workload.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/_workload.py new file mode 100644 index 0000000000000000000000000000000000000000..c5f8d215523efdadc9b2d305a62c1cf933775ad5 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/credentials/_workload.py @@ -0,0 +1,351 @@ +from __future__ import annotations + +import time +import logging +from types import TracebackType +from typing import Any, Dict, Type, Optional +from typing_extensions import override + +import httpx + +from ._types import AccessToken, IdentityTokenProvider +from ._constants import ( + TOKEN_ENDPOINT, + DEFAULT_BASE_URL, + GRANT_TYPE_JWT_BEARER, + OAUTH_API_BETA_HEADER, + FEDERATION_BETA_HEADER, + TOKEN_EXCHANGE_TIMEOUT, + _user_agent, + _require_https, +) +from ..._exceptions import AnthropicError + +# jwt-bearer POSTs require BOTH beta headers — oauth-2025-04-20 unlocks the +# token endpoint family, and oidc-federation-2026-04-01 routes the POST to the +# Go userauth handler rather than the Python oauth_server. +_JWT_BEARER_BETA_HEADER = f"{OAUTH_API_BETA_HEADER},{FEDERATION_BETA_HEADER}" + +# Max characters of response body kept on WorkloadIdentityError.body and in +# exception messages. Token endpoints sometimes echo back the assertion JWT or +# other sensitive material on error; truncating limits the blast radius if the +# exception ends up in user logs or crash reports. +_MAX_ERROR_BODY_CHARS = 256 + +# Hard limits on the wire size of the assertion JWT we send and the response +# body we accept from the token endpoint. JWTs from real IdPs are <4 KiB; a +# 16 KiB ceiling catches misconfiguration (e.g. a PEM cert path passed as the +# token) before we POST it. The 1 MiB response cap bounds memory if a misrouted +# endpoint streams back something pathological. +_MAX_ASSERTION_BYTES = 16 * 1024 +_MAX_TOKEN_RESPONSE_BYTES = 1 << 20 + + +def _request_id(resp: httpx.Response) -> Optional[str]: + rid: Optional[str] = resp.headers.get("Request-Id") or resp.headers.get("request-id") + return rid + + +def _redact_body(body: Any) -> Any: + """Truncate a token-endpoint error body for safe inclusion in an exception.""" + if body is None: + return None + if isinstance(body, str): + if len(body) <= _MAX_ERROR_BODY_CHARS: + return body + return body[:_MAX_ERROR_BODY_CHARS] + f"... <{len(body) - _MAX_ERROR_BODY_CHARS} more chars>" + # For dict payloads, only keep OAuth standard error fields (RFC 6749 §5.2). + if isinstance(body, dict): + kept: Dict[str, Any] = {} + for key in ("error", "error_description", "error_uri"): + if key in body: + kept[key] = body[key] + return kept + return None + + +def _raise_token_endpoint_error(resp: httpx.Response, *, message_prefix: str, hint: Optional[str] = None) -> None: + """Raise a redacted :class:`WorkloadIdentityError` from a non-200 token-endpoint response. + + Shared between the jwt-bearer exchange path in this module and the + refresh_token grant path in :mod:`_providers`. + + ``hint`` is an optional caller-supplied diagnostic appended verbatim to the + error message (after the redacted body). Callers gate it on the response + status and their own state — this helper does not inspect ``resp`` for it. + """ + try: + payload: Any = resp.json() + except ValueError: + payload = resp.text + redacted = _redact_body(payload) + message = f"{message_prefix} (HTTP {resp.status_code}): {redacted}" + if hint: + message = f"{message} {hint}" + raise WorkloadIdentityError( + message, + status_code=resp.status_code, + body=redacted, + request_id=_request_id(resp), + ) + + +__all__ = ["WorkloadIdentityCredentials", "WorkloadIdentityError", "exchange_federation_assertion"] + +log: logging.Logger = logging.getLogger(__name__) + + +class WorkloadIdentityError(AnthropicError): + """Raised when the OIDC token exchange (``POST /v1/oauth/token``) fails.""" + + status_code: Optional[int] + body: Any + request_id: Optional[str] + + def __init__( + self, + message: str, + *, + status_code: Optional[int] = None, + body: Any = None, + request_id: Optional[str] = None, + ) -> None: + super().__init__(message) + self.status_code = status_code + self.body = body + self.request_id = request_id + + @override + def __str__(self) -> str: + base = super().__str__() + if self.request_id: + return f"{base} [request_id={self.request_id}]" + return base + + +class WorkloadIdentityCredentials: + """Exchanges an external OIDC JWT for an Anthropic access token via the + RFC 7523 ``jwt-bearer`` grant. + + This is an :class:`AccessTokenProvider`: calling it performs a *fresh* token + exchange. Wrap in a :class:`TokenCache` (done automatically when passed as + ``credentials=`` to :class:`anthropic.Anthropic`) to avoid exchanging on every + request. + + Args: + organization_id: The organization's raw UUID string (organizations do + not use tagged IDs). + workspace_id: Optional ``wrkspc_*`` tagged ID, or the literal + ``"default"`` to scope the token to the organization's default + workspace. When omitted the server picks the rule's sole enabled + workspace, else the org default if the rule covers it. Required + when the rule enables more than one non-default workspace, or to + target a specific workspace other than the one the server would + pick. The minted token is workspace-scoped: per-request workspace + selection (the ``anthropic-workspace-id`` header) is not supported + for federation tokens — switching workspaces requires a new token + exchange with a different ``workspace_id``. + """ + + def __init__( + self, + *, + identity_token_provider: IdentityTokenProvider, + federation_rule_id: str, + organization_id: str, + service_account_id: Optional[str] = None, + workspace_id: Optional[str] = None, + scope: Optional[str] = None, + http_client: Optional[httpx.Client] = None, + ) -> None: + self._identity_token_provider = identity_token_provider + self._federation_rule_id = federation_rule_id + self._organization_id = organization_id + self._service_account_id = service_account_id + self._workspace_id = workspace_id + # Scope is informational only for federation: the server derives the + # effective scope from the matching federation rule and the gateway + # transform drops unknown body fields, so it is intentionally NOT sent + # on the jwt-bearer request. + self._scope = scope + # The client passing this object as ``credentials=`` calls + # :meth:`bind_base_url` to set its own endpoint, so the token exchange + # and the API calls hit the same deployment. There is intentionally no + # constructor kwarg for this: a token minted by one deployment is only + # valid against that deployment, so splitting exchange-base from + # client-base is always a bug. + self._bound_base_url: Optional[str] = None + if http_client is None: + self._http_client = httpx.Client(timeout=TOKEN_EXCHANGE_TIMEOUT) + self._owns_http_client = True + else: + self._http_client = http_client + self._owns_http_client = False + + @property + def scope(self) -> Optional[str]: + return self._scope + + @property + def _base_url(self) -> str: + return self._bound_base_url or DEFAULT_BASE_URL + + def bind_base_url(self, base_url: str) -> None: + """Set the API ``base_url`` the token exchange POSTs to. + + Called by :class:`anthropic.Anthropic` when this object is passed as + ``credentials=``, so callers don't pass the same URL twice. For + standalone use (no client) or tests, call this directly. + """ + bound = base_url.rstrip("/") + _require_https(bound, field="base_url") + self._bound_base_url = bound + + def close(self) -> None: + """Close the underlying ``httpx.Client`` if we created it.""" + if self._owns_http_client: + self._http_client.close() + + def __enter__(self) -> "WorkloadIdentityCredentials": + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc: Optional[BaseException], + tb: Optional[TracebackType], + ) -> None: + self.close() + + def __call__(self, *, force_refresh: bool = False) -> AccessToken: + # Re-invoke the identity token provider every time — the underlying + # file (e.g. a k8s projected SA token) may have rotated. force_refresh + # is a no-op: this provider has no cache to bypass. + del force_refresh + jwt = self._identity_token_provider() + + if len(jwt.encode("utf-8")) > _MAX_ASSERTION_BYTES: + raise WorkloadIdentityError( + f"Identity token assertion is {len(jwt.encode('utf-8'))} bytes, which exceeds the " + f"{_MAX_ASSERTION_BYTES}-byte limit. This is almost certainly not a JWT — check " + f"that the identity-token path points at the projected token, not a key or cert." + ) + + body: Dict[str, str] = { + "grant_type": GRANT_TYPE_JWT_BEARER, + "assertion": jwt, + "federation_rule_id": self._federation_rule_id, + "organization_id": self._organization_id, + } + if self._service_account_id is not None: + body["service_account_id"] = self._service_account_id + if self._workspace_id is not None: + body["workspace_id"] = self._workspace_id + + url = f"{self._base_url}{TOKEN_ENDPOINT}" + try: + resp = self._http_client.post( + url, + json=body, + headers={ + "anthropic-beta": _JWT_BEARER_BETA_HEADER, + "Content-Type": "application/json", + "User-Agent": _user_agent(), + }, + ) + except httpx.HTTPError as err: + raise WorkloadIdentityError(f"Failed to reach token endpoint {url}: {err}") from err + + request_id = _request_id(resp) + + if len(resp.content) > _MAX_TOKEN_RESPONSE_BYTES: + raise WorkloadIdentityError( + f"Token endpoint response body exceeds {_MAX_TOKEN_RESPONSE_BYTES} bytes " + f"(got {len(resp.content)}); refusing to parse.", + status_code=resp.status_code, + request_id=request_id, + ) + + if resp.status_code >= 400: + # A 401 is almost always a federation-rule mismatch. Point at the + # rule and the Console auth-event log; when the caller hasn't pinned + # a workspace, also surface the multi-workspace fix rather than + # making them dig through docs. + hint: Optional[str] = None + if resp.status_code == 401: + hint = "Ensure your federation rule matches your identity token. " + if self._workspace_id is None: + hint += ( + "If your federation rule is scoped to multiple workspaces, set the " + "ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' " + "config key, or the workspace_id= argument. " + ) + hint += "View your authentication events in the Workload identity page of Claude Console for more details." + _raise_token_endpoint_error(resp, message_prefix="Token exchange failed", hint=hint) + + try: + data = resp.json() + except ValueError as err: + redacted = _redact_body(resp.text) + raise WorkloadIdentityError( + f"Token endpoint returned non-JSON response (status {resp.status_code}): {redacted}", + status_code=resp.status_code, + body=redacted, + request_id=request_id, + ) from err + + token_type = data.get("token_type") + if token_type is not None and str(token_type).lower() != "bearer": + raise WorkloadIdentityError( + f"Token endpoint returned unsupported token_type {token_type!r} (expected 'Bearer').", + status_code=resp.status_code, + body=_redact_body(data), + request_id=request_id, + ) + + try: + token = data["access_token"] + # ``expires_in`` is a JSON number per RFC 6749 §5.1; coerce to int seconds. + expires_in = int(data["expires_in"]) + except (KeyError, TypeError, ValueError) as err: + raise WorkloadIdentityError( + "Token endpoint response missing required fields (access_token / expires_in).", + status_code=resp.status_code, + body=_redact_body(data), + request_id=request_id, + ) from err + + return AccessToken(token=token, expires_at=int(time.time()) + expires_in) + + +def exchange_federation_assertion( + *, + assertion: str, + federation_rule_id: str, + organization_id: str, + service_account_id: Optional[str] = None, + workspace_id: Optional[str] = None, + base_url: Optional[str] = None, + http_client: Optional[httpx.Client] = None, +) -> AccessToken: + """Perform a single RFC 7523 ``jwt-bearer`` exchange and return the resulting + :class:`AccessToken`. + + This is a one-shot convenience wrapper around :class:`WorkloadIdentityCredentials` + for callers that already have the assertion JWT in hand and just want the + Anthropic access token back (no caching, no provider plumbing). + """ + creds = WorkloadIdentityCredentials( + identity_token_provider=lambda: assertion, + federation_rule_id=federation_rule_id, + organization_id=organization_id, + service_account_id=service_account_id, + workspace_id=workspace_id, + http_client=http_client, + ) + if base_url is not None: + creds.bind_base_url(base_url) + try: + return creds() + finally: + creds.close() diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/foundry.md b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/foundry.md new file mode 100644 index 0000000000000000000000000000000000000000..dd0a3475bd839cfa90579ea586859be48dc6326e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/foundry.md @@ -0,0 +1,127 @@ +# Anthropic Foundry + +To use this library with Foundry, use the `AnthropicFoundry` class instead of the `Anthropic` class. + + +## Installation + +```bash +pip install anthropic +``` + +## Usage + +### Basic Usage with API Key + +```python +from anthropic import AnthropicFoundry + +client = AnthropicFoundry( + api_key="...", # defaults to ANTHROPIC_FOUNDRY_API_KEY environment variable + resource="my-resource", # your Foundry resource +) + +message = client.messages.create( + model="claude-3-5-sonnet-20241022", + max_tokens=1024, + messages=[{"role": "user", "content": "Hello!"}], +) + +print(message.content[0].text) +``` + +### Using Azure AD Token Provider + +For enhanced security, you can use Azure AD (Microsoft Entra) authentication instead of an API key: + +```python +from anthropic import AnthropicFoundry +from azure.identity import DefaultAzureCredential +from azure.identity import get_bearer_token_provider + +credential = DefaultAzureCredential() +token_provider = get_bearer_token_provider( + credential, + "https://ai.azure.com/.default" +) + +client = AnthropicFoundry( + azure_ad_token_provider=token_provider, + resource="my-resource", +) + +message = client.messages.create( + model="claude-3-5-sonnet-20241022", + max_tokens=1024, + messages=[{"role": "user", "content": "Hello!"}], +) + +print(message.content[0].text) +``` + +## Examples + +### Streaming Messages + +```python +from anthropic import AnthropicFoundry + +client = AnthropicFoundry( + api_key="...", + resource="my-resource", +) + +with client.messages.stream( + model="claude-3-5-sonnet-20241022", + max_tokens=1024, + messages=[{"role": "user", "content": "Write a haiku about programming"}], +) as stream: + for text in stream.text_stream: + print(text, end="", flush=True) +``` + +### Async Usage + +```python +from anthropic import AsyncAnthropicFoundry + +async def main(): + client = AsyncAnthropicFoundry( + api_key="...", + resource="my-resource", + ) + + message = await client.messages.create( + model="claude-3-5-sonnet-20241022", + max_tokens=1024, + messages=[{"role": "user", "content": "Hello!"}], + ) + + print(message.content[0].text) + +import asyncio +asyncio.run(main()) +``` + +### Async Streaming + +```python +from anthropic import AsyncAnthropicFoundry + +async def main(): + client = AsyncAnthropicFoundry( + api_key="...", + resource="my-resource", + ) + + async with client.messages.stream( + model="claude-3-5-sonnet-20241022", + max_tokens=1024, + messages=[{"role": "user", "content": "Write a haiku about programming"}], + ) as stream: + async for text in stream.text_stream: + print(text, end="", flush=True) + +import asyncio +asyncio.run(main()) +``` \ No newline at end of file diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/foundry.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/foundry.py new file mode 100644 index 0000000000000000000000000000000000000000..fde5be54f12c408223427044ad2d5a72fa0d9ffe --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/foundry.py @@ -0,0 +1,455 @@ +from __future__ import annotations + +import os +import inspect +from typing import Any, Union, Mapping, TypeVar, Callable, Awaitable, cast, overload +from functools import cached_property +from typing_extensions import Self, override + +import httpx + +from .._types import NOT_GIVEN, Omit, Timeout, NotGiven +from .._utils import is_given +from .._client import Anthropic, AsyncAnthropic +from .._compat import model_copy +from .._models import FinalRequestOptions +from .._streaming import Stream, AsyncStream +from .._exceptions import AnthropicError +from .._base_client import DEFAULT_MAX_RETRIES, BaseClient +from ..resources.beta import Beta, AsyncBeta +from ..resources.messages import Messages, AsyncMessages +from ..resources.beta.messages import Messages as BetaMessages, AsyncMessages as AsyncBetaMessages + +AzureADTokenProvider = Callable[[], str] +AsyncAzureADTokenProvider = Callable[[], "str | Awaitable[str]"] +_HttpxClientT = TypeVar("_HttpxClientT", bound=Union[httpx.Client, httpx.AsyncClient]) +_DefaultStreamT = TypeVar("_DefaultStreamT", bound=Union[Stream[Any], AsyncStream[Any]]) + + +class MutuallyExclusiveAuthError(AnthropicError): + def __init__(self) -> None: + super().__init__( + "The `api_key` and `azure_ad_token_provider` arguments are mutually exclusive; Only one can be passed at a time" + ) + + +class BaseFoundryClient(BaseClient[_HttpxClientT, _DefaultStreamT]): ... + + +class MessagesFoundry(Messages): + @cached_property + @override + def batches(self) -> None: # type: ignore[override] + """Batches endpoint is not supported for Anthropic Foundry client.""" + return None + + +class BetaFoundryMessages(BetaMessages): + @cached_property + @override + def batches(self) -> None: # type: ignore[override] + """Batches endpoint is not supported for Anthropic Foundry client.""" + return None + + +class BetaFoundry(Beta): + @cached_property + @override + def messages(self) -> BetaMessages: # type: ignore[override] + """Return beta messages resource instance with excluded unsupported endpoints.""" + return BetaFoundryMessages(self._client) + + +class AsyncMessagesFoundry(AsyncMessages): + @cached_property + @override + def batches(self) -> None: # type: ignore[override] + """Batches endpoint is not supported for Anthropic Foundry client.""" + return None + + +class AsyncBetaFoundryMessages(AsyncBetaMessages): + @cached_property + @override + def batches(self) -> None: # type: ignore[override] + """Batches endpoint is not supported for Anthropic Foundry client.""" + return None + + +class AsyncBetaFoundry(AsyncBeta): + @cached_property + @override + def messages(self) -> AsyncBetaMessages: # type: ignore[override] + """Return beta messages resource instance with excluded unsupported endpoints.""" + return AsyncBetaFoundryMessages(self._client) + + +# ============================================================================== + + +class AnthropicFoundry(BaseFoundryClient[httpx.Client, Stream[Any]], Anthropic): + @overload + def __init__( + self, + *, + resource: str | None = None, + api_key: str | None = None, + azure_ad_token_provider: AzureADTokenProvider | None = None, + webhook_key: str | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + http_client: httpx.Client | None = None, + _strict_response_validation: bool = False, + ) -> None: ... + + @overload + def __init__( + self, + *, + base_url: str, + api_key: str | None = None, + azure_ad_token_provider: AzureADTokenProvider | None = None, + webhook_key: str | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + http_client: httpx.Client | None = None, + _strict_response_validation: bool = False, + ) -> None: ... + + def __init__( + self, + *, + resource: str | None = None, + api_key: str | None = None, + azure_ad_token_provider: AzureADTokenProvider | None = None, + webhook_key: str | None = None, + base_url: str | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + http_client: httpx.Client | None = None, + _strict_response_validation: bool = False, + ) -> None: + """Construct a new synchronous Anthropic Foundry client instance. + + This automatically infers the following arguments from their corresponding environment variables if they are not provided: + - `api_key` from `ANTHROPIC_FOUNDRY_API_KEY` + - `resource` from `ANTHROPIC_FOUNDRY_RESOURCE` + - `base_url` from `ANTHROPIC_FOUNDRY_BASE_URL` + + Args: + resource: Your Foundry resource name, e.g. `example-resource` for `https://example-resource.services.ai.azure.com/anthropic/` + azure_ad_token_provider: A function that returns an Azure Active Directory token, will be invoked on every request. + """ + api_key = api_key if api_key is not None else os.environ.get("ANTHROPIC_FOUNDRY_API_KEY") + resource = resource if resource is not None else os.environ.get("ANTHROPIC_FOUNDRY_RESOURCE") + base_url = base_url if base_url is not None else os.environ.get("ANTHROPIC_FOUNDRY_BASE_URL") + + if api_key is None and azure_ad_token_provider is None: + raise AnthropicError( + "Missing credentials. Please pass one of `api_key`, `azure_ad_token_provider`, or the `ANTHROPIC_FOUNDRY_API_KEY` environment variable." + ) + + if base_url is None: + if resource is None: + raise ValueError( + "Must provide one of the `base_url` or `resource` arguments, or the `ANTHROPIC_FOUNDRY_RESOURCE` environment variable" + ) + base_url = f"https://{resource}.services.ai.azure.com/anthropic/" + elif resource is not None: + raise ValueError("base_url and resource are mutually exclusive") + + super().__init__( + api_key=api_key, + webhook_key=webhook_key, + base_url=base_url, + timeout=timeout, + max_retries=max_retries, + default_headers=default_headers, + default_query=default_query, + http_client=http_client, + _strict_response_validation=_strict_response_validation, + ) + self._azure_ad_token_provider = azure_ad_token_provider + + @cached_property + @override + def models(self) -> None: # type: ignore[override] + """Models endpoint is not supported for Anthropic Foundry client.""" + return None + + @cached_property + @override + def messages(self) -> MessagesFoundry: # type: ignore[override] + """Return messages resource instance with excluded unsupported endpoints.""" + return MessagesFoundry(client=self) + + @cached_property + @override + def beta(self) -> Beta: # type: ignore[override] + """Return beta resource instance with excluded unsupported endpoints.""" + return BetaFoundry(self) + + @override + def copy( # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] — subclass intentionally drops `credentials` + self, + *, + api_key: str | None = None, + azure_ad_token_provider: AzureADTokenProvider | None = None, + auth_token: str | None = None, + webhook_key: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + http_client: httpx.Client | None = None, + max_retries: int | NotGiven = NOT_GIVEN, + default_headers: Mapping[str, str] | None = None, + set_default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + set_default_query: Mapping[str, object] | None = None, + _extra_kwargs: Mapping[str, Any] = {}, + ) -> Self: + """ + Create a new client instance re-using the same options given to the current client with optional overriding. + """ + return super().copy( + api_key=api_key, + auth_token=auth_token, + webhook_key=webhook_key, + base_url=base_url, + timeout=timeout, + http_client=http_client, + max_retries=max_retries, + default_headers=default_headers, + set_default_headers=set_default_headers, + default_query=default_query, + set_default_query=set_default_query, + _extra_kwargs={ + "azure_ad_token_provider": azure_ad_token_provider or self._azure_ad_token_provider, + **_extra_kwargs, + }, + ) + + with_options = copy # type: ignore[assignment] + + def _get_azure_ad_token(self) -> str | None: + provider = self._azure_ad_token_provider + if provider is not None: + token = provider() + if not token or not isinstance(token, str): # pyright: ignore[reportUnnecessaryIsInstance] + raise ValueError( + f"Expected `azure_ad_token_provider` argument to return a string but it returned {token}", + ) + return token + + return None + + @override + def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions: + headers: dict[str, str | Omit] = {**options.headers} if is_given(options.headers) else {} + + options = model_copy(options) + options.headers = headers + + azure_ad_token = self._get_azure_ad_token() + if azure_ad_token is not None: + if headers.get("Authorization") is None: + headers["Authorization"] = f"Bearer {azure_ad_token}" + elif self.api_key is not None: + if headers.get("api-key") is None: + assert self.api_key is not None + headers["api-key"] = self.api_key + else: + # should never be hit + raise ValueError("Unable to handle auth") + + return options + + +class AsyncAnthropicFoundry(BaseFoundryClient[httpx.AsyncClient, AsyncStream[Any]], AsyncAnthropic): + @overload + def __init__( + self, + *, + resource: str | None = None, + api_key: str | None = None, + azure_ad_token_provider: AsyncAzureADTokenProvider | None = None, + webhook_key: str | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + http_client: httpx.AsyncClient | None = None, + _strict_response_validation: bool = False, + ) -> None: ... + + @overload + def __init__( + self, + *, + base_url: str, + api_key: str | None = None, + azure_ad_token_provider: AsyncAzureADTokenProvider | None = None, + webhook_key: str | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + http_client: httpx.AsyncClient | None = None, + _strict_response_validation: bool = False, + ) -> None: ... + + def __init__( + self, + *, + resource: str | None = None, + api_key: str | None = None, + azure_ad_token_provider: AsyncAzureADTokenProvider | None = None, + webhook_key: str | None = None, + base_url: str | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + http_client: httpx.AsyncClient | None = None, + _strict_response_validation: bool = False, + ) -> None: + """Construct a new asynchronous Anthropic Foundry client instance. + + This automatically infers the following arguments from their corresponding environment variables if they are not provided: + - `api_key` from `ANTHROPIC_FOUNDRY_API_KEY` + - `resource` from `ANTHROPIC_FOUNDRY_RESOURCE` + - `base_url` from `ANTHROPIC_FOUNDRY_BASE_URL` + + Args: + resource: Your Foundry resource name, e.g. `example-resource` for `https://example-resource.services.ai.azure.com/anthropic/` + azure_ad_token_provider: A function that returns an Azure Active Directory token, will be invoked on every request. + """ + api_key = api_key if api_key is not None else os.environ.get("ANTHROPIC_FOUNDRY_API_KEY") + resource = resource if resource is not None else os.environ.get("ANTHROPIC_FOUNDRY_RESOURCE") + base_url = base_url if base_url is not None else os.environ.get("ANTHROPIC_FOUNDRY_BASE_URL") + + if api_key is None and azure_ad_token_provider is None: + raise AnthropicError( + "Missing credentials. Please pass one of `api_key`, `azure_ad_token_provider`, or the `ANTHROPIC_FOUNDRY_API_KEY` environment variable." + ) + + if base_url is None: + if resource is None: + raise ValueError( + "Must provide one of the `base_url` or `resource` arguments, or the `ANTHROPIC_FOUNDRY_RESOURCE` environment variable" + ) + base_url = f"https://{resource}.services.ai.azure.com/anthropic/" + elif resource is not None: + raise ValueError("base_url and resource are mutually exclusive") + + super().__init__( + api_key=api_key, + webhook_key=webhook_key, + base_url=base_url, + timeout=timeout, + max_retries=max_retries, + default_headers=default_headers, + default_query=default_query, + http_client=http_client, + _strict_response_validation=_strict_response_validation, + ) + self._azure_ad_token_provider = azure_ad_token_provider + + @cached_property + @override + def models(self) -> None: # type: ignore[override] + """Models endpoint is not supported for Azure Anthropic client.""" + return None + + @cached_property + @override + def messages(self) -> AsyncMessagesFoundry: # type: ignore[override] + """Return messages resource instance with excluded unsupported endpoints.""" + return AsyncMessagesFoundry(client=self) + + @cached_property + @override + def beta(self) -> AsyncBetaFoundry: # type: ignore[override] + """Return beta resource instance with excluded unsupported endpoints.""" + return AsyncBetaFoundry(client=self) + + @override + def copy( # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] — subclass intentionally drops `credentials` + self, + *, + api_key: str | None = None, + azure_ad_token_provider: AsyncAzureADTokenProvider | None = None, + auth_token: str | None = None, + webhook_key: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + http_client: httpx.AsyncClient | None = None, + max_retries: int | NotGiven = NOT_GIVEN, + default_headers: Mapping[str, str] | None = None, + set_default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + set_default_query: Mapping[str, object] | None = None, + _extra_kwargs: Mapping[str, Any] = {}, + ) -> Self: + """ + Create a new client instance re-using the same options given to the current client with optional overriding. + """ + return super().copy( + api_key=api_key, + auth_token=auth_token, + webhook_key=webhook_key, + base_url=base_url, + timeout=timeout, + http_client=http_client, + max_retries=max_retries, + default_headers=default_headers, + set_default_headers=set_default_headers, + default_query=default_query, + set_default_query=set_default_query, + _extra_kwargs={ + "azure_ad_token_provider": azure_ad_token_provider or self._azure_ad_token_provider, + **_extra_kwargs, + }, + ) + + with_options = copy # type: ignore[assignment] + + async def _get_azure_ad_token(self) -> str | None: + provider = self._azure_ad_token_provider + if provider is not None: + token = provider() + if inspect.isawaitable(token): + token = await token + if not token or not isinstance(cast(Any, token), str): + raise ValueError( + f"Expected `azure_ad_token_provider` argument to return a string but it returned {token}", + ) + return str(token) + + return None + + @override + async def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions: + headers: dict[str, str | Omit] = {**options.headers} if is_given(options.headers) else {} + + options = model_copy(options) + options.headers = headers + + azure_ad_token = await self._get_azure_ad_token() + if azure_ad_token is not None: + if headers.get("Authorization") is None: + headers["Authorization"] = f"Bearer {azure_ad_token}" + elif self.api_key is not None: + assert self.api_key is not None + if headers.get("api-key") is None: + headers["api-key"] = self.api_key + else: + # should never be hit + raise ValueError("Unable to handle auth") + + return options diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/__init__.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2f717c005f41728d6f7df977523a30631ee2f913 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/__init__.py @@ -0,0 +1,39 @@ +from typing_extensions import TypeAlias + +from ._types import ( + TextEvent as TextEvent, + InputJsonEvent as InputJsonEvent, + MessageStopEvent as MessageStopEvent, + MessageStreamEvent as MessageStreamEvent, + ContentBlockStopEvent as ContentBlockStopEvent, + ParsedMessageStopEvent as ParsedMessageStopEvent, + ParsedMessageStreamEvent as ParsedMessageStreamEvent, + ParsedContentBlockStopEvent as ParsedContentBlockStopEvent, +) +from ._messages import ( + MessageStream as MessageStream, + AsyncMessageStream as AsyncMessageStream, + MessageStreamManager as MessageStreamManager, + AsyncMessageStreamManager as AsyncMessageStreamManager, +) +from ._beta_types import ( + BetaInputJsonEvent as BetaInputJsonEvent, + ParsedBetaTextEvent as ParsedBetaTextEvent, + ParsedBetaMessageStopEvent as ParsedBetaMessageStopEvent, + ParsedBetaMessageStreamEvent as ParsedBetaMessageStreamEvent, + ParsedBetaContentBlockStopEvent as ParsedBetaContentBlockStopEvent, +) + +# For backwards compatibility +BetaTextEvent: TypeAlias = ParsedBetaTextEvent +BetaMessageStopEvent: TypeAlias = ParsedBetaMessageStopEvent[object] +BetaMessageStreamEvent: TypeAlias = ParsedBetaMessageStreamEvent +BetaContentBlockStopEvent: TypeAlias = ParsedBetaContentBlockStopEvent[object] + + +from ._beta_messages import ( + BetaMessageStream as BetaMessageStream, + BetaAsyncMessageStream as BetaAsyncMessageStream, + BetaMessageStreamManager as BetaMessageStreamManager, + BetaAsyncMessageStreamManager as BetaAsyncMessageStreamManager, +) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/__pycache__/__init__.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fe9fe072480ecc9b20b02327d3d3da953327565 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/__pycache__/__init__.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/__pycache__/_beta_messages.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/__pycache__/_beta_messages.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc9f9720b47b692a3987c951fb82c17aa063b555 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/__pycache__/_beta_messages.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/__pycache__/_beta_types.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/__pycache__/_beta_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4828c46b94f940e86036c70167e3c2b57b240aae Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/__pycache__/_beta_types.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/__pycache__/_messages.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/__pycache__/_messages.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..747acc027f7e051ae606aac112c01a9015fbc7c4 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/__pycache__/_messages.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/__pycache__/_types.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/__pycache__/_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..187d1d3a369055abd7ea039df555130aaacd496f Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/__pycache__/_types.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/_beta_messages.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/_beta_messages.py new file mode 100644 index 0000000000000000000000000000000000000000..5a5a562a06a2341deb6723bf1c83d2d32bac6225 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/_beta_messages.py @@ -0,0 +1,557 @@ +from __future__ import annotations + +import builtins +from types import TracebackType +from typing import TYPE_CHECKING, Any, Type, Generic, Callable, cast +from typing_extensions import Self, Iterator, Awaitable, AsyncIterator, assert_never + +import httpx +from pydantic import BaseModel + +from anthropic.types.beta.beta_tool_use_block import BetaToolUseBlock +from anthropic.types.beta.beta_mcp_tool_use_block import BetaMCPToolUseBlock +from anthropic.types.beta.beta_server_tool_use_block import BetaServerToolUseBlock + +from ..._types import NOT_GIVEN, NotGiven +from ..._utils import consume_sync_iterator, consume_async_iterator +from ..._models import build, construct_type, construct_type_unchecked +from ._beta_types import ( + BetaCitationEvent, + BetaThinkingEvent, + BetaInputJsonEvent, + BetaSignatureEvent, + BetaCompactionEvent, + ParsedBetaTextEvent, + ParsedBetaMessageStopEvent, + ParsedBetaMessageStreamEvent, + ParsedBetaContentBlockStopEvent, +) +from ..._streaming import Stream, AsyncStream +from ...types.beta import BetaRawMessageStreamEvent +from ..._utils._utils import is_given +from .._parse._response import ResponseFormatT, parse_text +from ...types.beta.parsed_beta_message import ParsedBetaMessage, ParsedBetaContentBlock + + +class BetaMessageStream(Generic[ResponseFormatT]): + text_stream: Iterator[str] + """Iterator over just the text deltas in the stream. + + ```py + for text in stream.text_stream: + print(text, end="", flush=True) + print() + ``` + """ + + def __init__( + self, + raw_stream: Stream[BetaRawMessageStreamEvent], + output_format: ResponseFormatT | NotGiven, + ) -> None: + self._raw_stream = raw_stream + self.text_stream = self.__stream_text__() + self._iterator = self.__stream__() + self.__final_message_snapshot: ParsedBetaMessage[ResponseFormatT] | None = None + self.__output_format = output_format + + @property + def response(self) -> httpx.Response: + return self._raw_stream.response + + @property + def request_id(self) -> str | None: + return self.response.headers.get("request-id") # type: ignore[no-any-return] + + def __next__(self) -> ParsedBetaMessageStreamEvent[ResponseFormatT]: + return self._iterator.__next__() + + def __iter__(self) -> Iterator[ParsedBetaMessageStreamEvent[ResponseFormatT]]: + for item in self._iterator: + yield item + + def __enter__(self) -> Self: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def close(self) -> None: + """ + Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + self._raw_stream.close() + + def get_final_message(self) -> ParsedBetaMessage[ResponseFormatT]: + """Waits until the stream has been read to completion and returns + the accumulated `Message` object. + """ + self.until_done() + assert self.__final_message_snapshot is not None + return self.__final_message_snapshot + + def get_final_text(self) -> str: + """Returns all `text` content blocks concatenated together. + + > [!NOTE] + > Currently the API will only respond with a single content block. + + Will raise an error if no `text` content blocks were returned. + """ + message = self.get_final_message() + text_blocks: list[str] = [] + for block in message.content: + if block.type == "text": + text_blocks.append(block.text) + + if not text_blocks: + raise RuntimeError( + f".get_final_text() can only be called when the API returns a `text` content block.\nThe API returned {','.join([b.type for b in message.content])} content block type(s) that you can access by calling get_final_message().content" + ) + + return "".join(text_blocks) + + def until_done(self) -> None: + """Blocks until the stream has been consumed""" + consume_sync_iterator(self) + + # properties + @property + def current_message_snapshot(self) -> ParsedBetaMessage[ResponseFormatT]: + assert self.__final_message_snapshot is not None + return self.__final_message_snapshot + + def __stream__(self) -> Iterator[ParsedBetaMessageStreamEvent[ResponseFormatT]]: + for sse_event in self._raw_stream: + self.__final_message_snapshot = accumulate_event( + event=sse_event, + current_snapshot=self.__final_message_snapshot, + request_headers=self.response.request.headers, + output_format=self.__output_format, + ) + + events_to_fire = build_events(event=sse_event, message_snapshot=self.current_message_snapshot) + for event in events_to_fire: + yield event + + def __stream_text__(self) -> Iterator[str]: + for chunk in self: + if chunk.type == "content_block_delta" and chunk.delta.type == "text_delta": + yield chunk.delta.text + + +class BetaMessageStreamManager(Generic[ResponseFormatT]): + """Wrapper over MessageStream that is returned by `.stream()`. + + ```py + with client.beta.messages.stream(...) as stream: + for chunk in stream: + ... + ``` + """ + + def __init__( + self, + api_request: Callable[[], Stream[BetaRawMessageStreamEvent]], + *, + output_format: ResponseFormatT | NotGiven, + ) -> None: + self.__stream: BetaMessageStream[ResponseFormatT] | None = None + self.__api_request = api_request + self.__output_format = output_format + + def __enter__(self) -> BetaMessageStream[ResponseFormatT]: + raw_stream = self.__api_request() + self.__stream = BetaMessageStream(raw_stream, output_format=self.__output_format) + return self.__stream + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self.__stream is not None: + self.__stream.close() + + +class BetaAsyncMessageStream(Generic[ResponseFormatT]): + text_stream: AsyncIterator[str] + """Async iterator over just the text deltas in the stream. + + ```py + async for text in stream.text_stream: + print(text, end="", flush=True) + print() + ``` + """ + + def __init__( + self, + raw_stream: AsyncStream[BetaRawMessageStreamEvent], + output_format: ResponseFormatT | NotGiven, + ) -> None: + self._raw_stream = raw_stream + self.text_stream = self.__stream_text__() + self._iterator = self.__stream__() + self.__final_message_snapshot: ParsedBetaMessage[ResponseFormatT] | None = None + self.__output_format = output_format + + @property + def response(self) -> httpx.Response: + return self._raw_stream.response + + @property + def request_id(self) -> str | None: + return self.response.headers.get("request-id") # type: ignore[no-any-return] + + async def __anext__(self) -> ParsedBetaMessageStreamEvent[ResponseFormatT]: + return await self._iterator.__anext__() + + async def __aiter__(self) -> AsyncIterator[ParsedBetaMessageStreamEvent[ResponseFormatT]]: + async for item in self._iterator: + yield item + + async def __aenter__(self) -> Self: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + await self.close() + + async def close(self) -> None: + """ + Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + await self._raw_stream.close() + + async def get_final_message(self) -> ParsedBetaMessage[ResponseFormatT]: + """Waits until the stream has been read to completion and returns + the accumulated `Message` object. + """ + await self.until_done() + assert self.__final_message_snapshot is not None + return self.__final_message_snapshot + + async def get_final_text(self) -> str: + """Returns all `text` content blocks concatenated together. + + > [!NOTE] + > Currently the API will only respond with a single content block. + + Will raise an error if no `text` content blocks were returned. + """ + message = await self.get_final_message() + text_blocks: list[str] = [] + for block in message.content: + if block.type == "text": + text_blocks.append(block.text) + + if not text_blocks: + raise RuntimeError( + f".get_final_text() can only be called when the API returns a `text` content block.\nThe API returned {','.join([b.type for b in message.content])} content block type(s) that you can access by calling get_final_message().content" + ) + + return "".join(text_blocks) + + async def until_done(self) -> None: + """Waits until the stream has been consumed""" + await consume_async_iterator(self) + + # properties + @property + def current_message_snapshot(self) -> ParsedBetaMessage[ResponseFormatT]: + assert self.__final_message_snapshot is not None + return self.__final_message_snapshot + + async def __stream__(self) -> AsyncIterator[ParsedBetaMessageStreamEvent[ResponseFormatT]]: + async for sse_event in self._raw_stream: + self.__final_message_snapshot = accumulate_event( + event=sse_event, + current_snapshot=self.__final_message_snapshot, + request_headers=self.response.request.headers, + output_format=self.__output_format, + ) + + events_to_fire = build_events(event=sse_event, message_snapshot=self.current_message_snapshot) + for event in events_to_fire: + yield event + + async def __stream_text__(self) -> AsyncIterator[str]: + async for chunk in self: + if chunk.type == "content_block_delta" and chunk.delta.type == "text_delta": + yield chunk.delta.text + + +class BetaAsyncMessageStreamManager(Generic[ResponseFormatT]): + """Wrapper over BetaAsyncMessageStream that is returned by `.stream()` + so that an async context manager can be used without `await`ing the + original client call. + + ```py + async with client.beta.messages.stream(...) as stream: + async for chunk in stream: + ... + ``` + """ + + def __init__( + self, + api_request: Awaitable[AsyncStream[BetaRawMessageStreamEvent]], + *, + output_format: ResponseFormatT | NotGiven = NOT_GIVEN, + ) -> None: + self.__stream: BetaAsyncMessageStream[ResponseFormatT] | None = None + self.__api_request = api_request + self.__output_format = output_format + + async def __aenter__(self) -> BetaAsyncMessageStream[ResponseFormatT]: + raw_stream = await self.__api_request + self.__stream = BetaAsyncMessageStream(raw_stream, output_format=self.__output_format) + return self.__stream + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self.__stream is not None: + await self.__stream.close() + + +def build_events( + *, + event: BetaRawMessageStreamEvent, + message_snapshot: ParsedBetaMessage[ResponseFormatT], +) -> list[ParsedBetaMessageStreamEvent[ResponseFormatT]]: + events_to_fire: list[ParsedBetaMessageStreamEvent[ResponseFormatT]] = [] + + if event.type == "message_start": + events_to_fire.append(event) + elif event.type == "message_delta": + events_to_fire.append(event) + elif event.type == "message_stop": + events_to_fire.append( + build(ParsedBetaMessageStopEvent[ResponseFormatT], type="message_stop", message=message_snapshot) + ) + elif event.type == "content_block_start": + events_to_fire.append(event) + elif event.type == "content_block_delta": + events_to_fire.append(event) + + content_block = message_snapshot.content[event.index] + if event.delta.type == "text_delta": + if content_block.type == "text": + events_to_fire.append( + build( + ParsedBetaTextEvent, + type="text", + text=event.delta.text, + snapshot=content_block.text, + ) + ) + elif event.delta.type == "input_json_delta": + if content_block.type == "tool_use" or content_block.type == "mcp_tool_use": + events_to_fire.append( + build( + BetaInputJsonEvent, + type="input_json", + partial_json=event.delta.partial_json, + snapshot=content_block.input, + ) + ) + elif event.delta.type == "citations_delta": + if content_block.type == "text": + events_to_fire.append( + build( + BetaCitationEvent, + type="citation", + citation=event.delta.citation, + snapshot=content_block.citations or [], + ) + ) + elif event.delta.type == "thinking_delta": + if content_block.type == "thinking": + events_to_fire.append( + build( + BetaThinkingEvent, + type="thinking", + thinking=event.delta.thinking, + snapshot=content_block.thinking, + ) + ) + elif event.delta.type == "signature_delta": + if content_block.type == "thinking": + events_to_fire.append( + build( + BetaSignatureEvent, + type="signature", + signature=content_block.signature, + ) + ) + pass + elif event.delta.type == "compaction_delta": + if content_block.type == "compaction": + events_to_fire.append( + build( + BetaCompactionEvent, + type="compaction", + content=content_block.content, + ) + ) + else: + # we only want exhaustive checking for linters, not at runtime + if TYPE_CHECKING: # type: ignore[unreachable] + assert_never(event.delta) + elif event.type == "content_block_stop": + content_block = message_snapshot.content[event.index] + + event_to_fire = build( + ParsedBetaContentBlockStopEvent, + type="content_block_stop", + index=event.index, + content_block=content_block, + ) + + events_to_fire.append(event_to_fire) + else: + # we only want exhaustive checking for linters, not at runtime + if TYPE_CHECKING: # type: ignore[unreachable] + assert_never(event) + + return events_to_fire + + +JSON_BUF_PROPERTY = "__json_buf" + +TRACKS_TOOL_INPUT = ( + BetaToolUseBlock, + BetaServerToolUseBlock, + BetaMCPToolUseBlock, +) + + +def accumulate_event( + *, + event: BetaRawMessageStreamEvent, + current_snapshot: ParsedBetaMessage[ResponseFormatT] | None, + request_headers: httpx.Headers, + output_format: ResponseFormatT | NotGiven = NOT_GIVEN, +) -> ParsedBetaMessage[ResponseFormatT]: + if not isinstance(cast(Any, event), BaseModel): + event = cast( # pyright: ignore[reportUnnecessaryCast] + BetaRawMessageStreamEvent, + construct_type_unchecked( + type_=cast(Type[BetaRawMessageStreamEvent], BetaRawMessageStreamEvent), + value=event, + ), + ) + if not isinstance(cast(Any, event), BaseModel): + raise TypeError( + f"Unexpected event runtime type, after deserialising twice - {event} - {builtins.type(event)}" + ) + + if current_snapshot is None: + if event.type == "message_start": + return cast( + ParsedBetaMessage[ResponseFormatT], ParsedBetaMessage.construct(**cast(Any, event.message.to_dict())) + ) + + raise RuntimeError(f'Unexpected event order, got {event.type} before "message_start"') + + if event.type == "content_block_start": + # TODO: check index + current_snapshot.content.append( + cast( + Any, # Pydantic does not support generic unions at runtime + construct_type(type_=ParsedBetaContentBlock, value=event.content_block.to_dict()), + ), + ) + elif event.type == "content_block_delta": + content = current_snapshot.content[event.index] + if event.delta.type == "text_delta": + if content.type == "text": + content.text += event.delta.text + elif event.delta.type == "input_json_delta": + if isinstance(content, TRACKS_TOOL_INPUT): + from jiter import from_json + + # we need to keep track of the raw JSON string as well so that we can + # re-parse it for each delta, for now we just store it as an untyped + # property on the snapshot + json_buf = cast(bytes, getattr(content, JSON_BUF_PROPERTY, b"")) + json_buf += bytes(event.delta.partial_json, "utf-8") + + if json_buf: + try: + anthropic_beta = request_headers.get("anthropic-beta", "") if request_headers else "" + + if "fine-grained-tool-streaming-2025-05-14" in anthropic_beta: + content.input = from_json(json_buf, partial_mode="trailing-strings") + else: + content.input = from_json(json_buf, partial_mode=True) + except ValueError as e: + raise ValueError( + f"Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: {e}. JSON: {json_buf.decode('utf-8')}" + ) from e + + setattr(content, JSON_BUF_PROPERTY, json_buf) + elif event.delta.type == "citations_delta": + if content.type == "text": + if not content.citations: + content.citations = [event.delta.citation] + else: + content.citations.append(event.delta.citation) + elif event.delta.type == "thinking_delta": + if content.type == "thinking": + content.thinking += event.delta.thinking + elif event.delta.type == "signature_delta": + if content.type == "thinking": + content.signature = event.delta.signature + elif event.delta.type == "compaction_delta": + if content.type == "compaction": + content.content = event.delta.content + else: + # we only want exhaustive checking for linters, not at runtime + if TYPE_CHECKING: # type: ignore[unreachable] + assert_never(event.delta) + elif event.type == "content_block_stop": + content_block = current_snapshot.content[event.index] + if content_block.type == "text" and is_given(output_format): + content_block.parsed_output = parse_text(content_block.text, output_format) + elif event.type == "message_delta": + current_snapshot.container = event.delta.container + current_snapshot.stop_reason = event.delta.stop_reason + current_snapshot.stop_sequence = event.delta.stop_sequence + if event.delta.stop_details is not None: + current_snapshot.stop_details = event.delta.stop_details + current_snapshot.usage.output_tokens = event.usage.output_tokens + current_snapshot.context_management = event.context_management + + # Update other usage fields if they exist in the event + if event.usage.input_tokens is not None: + current_snapshot.usage.input_tokens = event.usage.input_tokens + if event.usage.cache_creation_input_tokens is not None: + current_snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens + if event.usage.cache_read_input_tokens is not None: + current_snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens + if event.usage.server_tool_use is not None: + current_snapshot.usage.server_tool_use = event.usage.server_tool_use + if event.usage.iterations is not None: + current_snapshot.usage.iterations = event.usage.iterations + + return current_snapshot diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/_beta_types.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/_beta_types.py new file mode 100644 index 0000000000000000000000000000000000000000..3dcf3535407b481693a9f2a8bce1d8b07d2fb97a --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/_beta_types.py @@ -0,0 +1,116 @@ +from typing import TYPE_CHECKING, Any, Dict, Union, Generic, cast +from typing_extensions import List, Literal, Annotated + +import jiter + +from ..._models import BaseModel, GenericModel +from ...types.beta import ( + BetaRawMessageStopEvent, + BetaRawMessageDeltaEvent, + BetaRawMessageStartEvent, + BetaRawContentBlockStopEvent, + BetaRawContentBlockDeltaEvent, + BetaRawContentBlockStartEvent, +) +from .._parse._response import ResponseFormatT +from ..._utils._transform import PropertyInfo +from ...types.beta.parsed_beta_message import ParsedBetaMessage, ParsedBetaContentBlock +from ...types.beta.beta_citations_delta import Citation + + +class ParsedBetaTextEvent(BaseModel): + type: Literal["text"] + + text: str + """The text delta""" + + snapshot: str + """The entire accumulated text""" + + def parsed_snapshot(self) -> Dict[str, Any]: + return cast(Dict[str, Any], jiter.from_json(self.snapshot.encode("utf-8"), partial_mode="trailing-strings")) + + +class BetaCitationEvent(BaseModel): + type: Literal["citation"] + + citation: Citation + """The new citation""" + + snapshot: List[Citation] + """All of the accumulated citations""" + + +class BetaThinkingEvent(BaseModel): + type: Literal["thinking"] + + thinking: str + """The thinking delta""" + + snapshot: str + """The accumulated thinking so far""" + + +class BetaSignatureEvent(BaseModel): + type: Literal["signature"] + + signature: str + """The signature of the thinking block""" + + +class BetaInputJsonEvent(BaseModel): + type: Literal["input_json"] + + partial_json: str + """A partial JSON string delta + + e.g. `'"San Francisco,'` + """ + + snapshot: object + """The currently accumulated parsed object. + + + e.g. `{'location': 'San Francisco, CA'}` + """ + + +class BetaCompactionEvent(BaseModel): + type: Literal["compaction"] + + content: Union[str, None] + """The compaction content""" + + +class ParsedBetaMessageStopEvent(BetaRawMessageStopEvent, GenericModel, Generic[ResponseFormatT]): + type: Literal["message_stop"] + + message: ParsedBetaMessage[ResponseFormatT] + + +class ParsedBetaContentBlockStopEvent(BetaRawContentBlockStopEvent, GenericModel, Generic[ResponseFormatT]): + type: Literal["content_block_stop"] + + if TYPE_CHECKING: + content_block: ParsedBetaContentBlock[ResponseFormatT] + else: + content_block: ParsedBetaContentBlock + + +ParsedBetaMessageStreamEvent = Annotated[ + Union[ + ParsedBetaTextEvent, + BetaCitationEvent, + BetaThinkingEvent, + BetaSignatureEvent, + BetaInputJsonEvent, + BetaCompactionEvent, + BetaRawMessageStartEvent, + BetaRawMessageDeltaEvent, + ParsedBetaMessageStopEvent[ResponseFormatT], + BetaRawContentBlockStartEvent, + BetaRawContentBlockDeltaEvent, + ParsedBetaContentBlockStopEvent[ResponseFormatT], + ], + PropertyInfo(discriminator="type"), +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/_messages.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/_messages.py new file mode 100644 index 0000000000000000000000000000000000000000..5c0da9992601ddbbeb1a523cc009f603ef35606c --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/_messages.py @@ -0,0 +1,520 @@ +from __future__ import annotations + +from types import TracebackType +from typing import TYPE_CHECKING, Any, Type, Generic, Callable, cast +from typing_extensions import Self, Iterator, Awaitable, AsyncIterator, assert_never + +import httpx +from pydantic import BaseModel + +from anthropic.types.tool_use_block import ToolUseBlock +from anthropic.types.server_tool_use_block import ServerToolUseBlock + +from ._types import ( + TextEvent, + CitationEvent, + ThinkingEvent, + InputJsonEvent, + SignatureEvent, + ParsedMessageStopEvent, + ParsedMessageStreamEvent, + ParsedContentBlockStopEvent, +) +from ...types import RawMessageStreamEvent +from ..._types import NOT_GIVEN, NotGiven +from ..._utils import consume_sync_iterator, consume_async_iterator +from ..._models import build, construct_type, construct_type_unchecked +from ..._streaming import Stream, AsyncStream +from ..._utils._utils import is_given +from .._parse._response import ResponseFormatT, parse_text +from ...types.parsed_message import ParsedMessage, ParsedContentBlock + + +class MessageStream(Generic[ResponseFormatT]): + text_stream: Iterator[str] + """Iterator over just the text deltas in the stream. + + ```py + for text in stream.text_stream: + print(text, end="", flush=True) + print() + ``` + """ + + def __init__( + self, + raw_stream: Stream[RawMessageStreamEvent], + output_format: ResponseFormatT | NotGiven, + ) -> None: + self._raw_stream = raw_stream + self.text_stream = self.__stream_text__() + self._iterator = self.__stream__() + self.__final_message_snapshot: ParsedMessage[ResponseFormatT] | None = None + self.__output_format = output_format + + @property + def response(self) -> httpx.Response: + return self._raw_stream.response + + @property + def request_id(self) -> str | None: + return self.response.headers.get("request-id") # type: ignore[no-any-return] + + def __next__(self) -> ParsedMessageStreamEvent[ResponseFormatT]: + return self._iterator.__next__() + + def __iter__(self) -> Iterator[ParsedMessageStreamEvent[ResponseFormatT]]: + for item in self._iterator: + yield item + + def __enter__(self) -> Self: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def close(self) -> None: + """ + Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + self._raw_stream.close() + + def get_final_message(self) -> ParsedMessage[ResponseFormatT]: + """Waits until the stream has been read to completion and returns + the accumulated `Message` object. + """ + self.until_done() + assert self.__final_message_snapshot is not None + return self.__final_message_snapshot + + def get_final_text(self) -> str: + """Returns all `text` content blocks concatenated together. + + > [!NOTE] + > Currently the API will only respond with a single content block. + + Will raise an error if no `text` content blocks were returned. + """ + message = self.get_final_message() + text_blocks: list[str] = [] + for block in message.content: + if block.type == "text": + text_blocks.append(block.text) + + if not text_blocks: + raise RuntimeError( + f".get_final_text() can only be called when the API returns a `text` content block.\nThe API returned {','.join([b.type for b in message.content])} content block type(s) that you can access by calling get_final_message().content" + ) + + return "".join(text_blocks) + + def until_done(self) -> None: + """Blocks until the stream has been consumed""" + consume_sync_iterator(self) + + # properties + @property + def current_message_snapshot(self) -> ParsedMessage[ResponseFormatT]: + assert self.__final_message_snapshot is not None + return self.__final_message_snapshot + + def __stream__(self) -> Iterator[ParsedMessageStreamEvent[ResponseFormatT]]: + for sse_event in self._raw_stream: + self.__final_message_snapshot = accumulate_event( + event=sse_event, + current_snapshot=self.__final_message_snapshot, + output_format=self.__output_format, + ) + + events_to_fire = build_events(event=sse_event, message_snapshot=self.current_message_snapshot) + for event in events_to_fire: + yield event + + def __stream_text__(self) -> Iterator[str]: + for chunk in self: + if chunk.type == "content_block_delta" and chunk.delta.type == "text_delta": + yield chunk.delta.text + + +class MessageStreamManager(Generic[ResponseFormatT]): + """Wrapper over MessageStream that is returned by `.stream()`. + + ```py + with client.messages.stream(...) as stream: + for chunk in stream: + ... + ``` + """ + + def __init__( + self, + api_request: Callable[[], Stream[RawMessageStreamEvent]], + *, + output_format: ResponseFormatT | NotGiven, + ) -> None: + self.__stream: MessageStream[ResponseFormatT] | None = None + self.__api_request = api_request + self.__output_format = output_format + + def __enter__(self) -> MessageStream[ResponseFormatT]: + raw_stream = self.__api_request() + self.__stream = MessageStream(raw_stream, output_format=self.__output_format) + return self.__stream + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self.__stream is not None: + self.__stream.close() + + +class AsyncMessageStream(Generic[ResponseFormatT]): + text_stream: AsyncIterator[str] + """Async iterator over just the text deltas in the stream. + + ```py + async for text in stream.text_stream: + print(text, end="", flush=True) + print() + ``` + """ + + def __init__( + self, + raw_stream: AsyncStream[RawMessageStreamEvent], + output_format: ResponseFormatT | NotGiven, + ) -> None: + self._raw_stream = raw_stream + self.text_stream = self.__stream_text__() + self._iterator = self.__stream__() + self.__final_message_snapshot: ParsedMessage[ResponseFormatT] | None = None + self.__output_format = output_format + + @property + def response(self) -> httpx.Response: + return self._raw_stream.response + + @property + def request_id(self) -> str | None: + return self.response.headers.get("request-id") # type: ignore[no-any-return] + + async def __anext__(self) -> ParsedMessageStreamEvent[ResponseFormatT]: + return await self._iterator.__anext__() + + async def __aiter__(self) -> AsyncIterator[ParsedMessageStreamEvent[ResponseFormatT]]: + async for item in self._iterator: + yield item + + async def __aenter__(self) -> Self: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + await self.close() + + async def close(self) -> None: + """ + Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + await self._raw_stream.close() + + async def get_final_message(self) -> ParsedMessage[ResponseFormatT]: + """Waits until the stream has been read to completion and returns + the accumulated `Message` object. + """ + await self.until_done() + assert self.__final_message_snapshot is not None + return self.__final_message_snapshot + + async def get_final_text(self) -> str: + """Returns all `text` content blocks concatenated together. + + > [!NOTE] + > Currently the API will only respond with a single content block. + + Will raise an error if no `text` content blocks were returned. + """ + message = await self.get_final_message() + text_blocks: list[str] = [] + for block in message.content: + if block.type == "text": + text_blocks.append(block.text) + + if not text_blocks: + raise RuntimeError( + f".get_final_text() can only be called when the API returns a `text` content block.\nThe API returned {','.join([b.type for b in message.content])} content block type(s) that you can access by calling get_final_message().content" + ) + + return "".join(text_blocks) + + async def until_done(self) -> None: + """Waits until the stream has been consumed""" + await consume_async_iterator(self) + + # properties + @property + def current_message_snapshot(self) -> ParsedMessage[ResponseFormatT]: + assert self.__final_message_snapshot is not None + return self.__final_message_snapshot + + async def __stream__(self) -> AsyncIterator[ParsedMessageStreamEvent[ResponseFormatT]]: + async for sse_event in self._raw_stream: + self.__final_message_snapshot = accumulate_event( + event=sse_event, + current_snapshot=self.__final_message_snapshot, + output_format=self.__output_format, + ) + + events_to_fire = build_events(event=sse_event, message_snapshot=self.current_message_snapshot) + for event in events_to_fire: + yield event + + async def __stream_text__(self) -> AsyncIterator[str]: + async for chunk in self: + if chunk.type == "content_block_delta" and chunk.delta.type == "text_delta": + yield chunk.delta.text + + +class AsyncMessageStreamManager(Generic[ResponseFormatT]): + """Wrapper over AsyncMessageStream that is returned by `.stream()` + so that an async context manager can be used without `await`ing the + original client call. + + ```py + async with client.messages.stream(...) as stream: + async for chunk in stream: + ... + ``` + """ + + def __init__( + self, + api_request: Awaitable[AsyncStream[RawMessageStreamEvent]], + *, + output_format: ResponseFormatT | NotGiven = NOT_GIVEN, + ) -> None: + self.__stream: AsyncMessageStream[ResponseFormatT] | None = None + self.__api_request = api_request + self.__output_format = output_format + + async def __aenter__(self) -> AsyncMessageStream[ResponseFormatT]: + raw_stream = await self.__api_request + self.__stream = AsyncMessageStream(raw_stream, output_format=self.__output_format) + return self.__stream + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self.__stream is not None: + await self.__stream.close() + + +def build_events( + *, + event: RawMessageStreamEvent, + message_snapshot: ParsedMessage[ResponseFormatT], +) -> list[ParsedMessageStreamEvent[ResponseFormatT]]: + events_to_fire: list[ParsedMessageStreamEvent[ResponseFormatT]] = [] + + if event.type == "message_start": + events_to_fire.append(event) + elif event.type == "message_delta": + events_to_fire.append(event) + elif event.type == "message_stop": + events_to_fire.append( + build(ParsedMessageStopEvent[ResponseFormatT], type="message_stop", message=message_snapshot) + ) + elif event.type == "content_block_start": + events_to_fire.append(event) + elif event.type == "content_block_delta": + events_to_fire.append(event) + + content_block = message_snapshot.content[event.index] + if event.delta.type == "text_delta": + if content_block.type == "text": + events_to_fire.append( + build( + TextEvent, + type="text", + text=event.delta.text, + snapshot=content_block.text, + ) + ) + elif event.delta.type == "input_json_delta": + if content_block.type == "tool_use": + events_to_fire.append( + build( + InputJsonEvent, + type="input_json", + partial_json=event.delta.partial_json, + snapshot=content_block.input, + ) + ) + elif event.delta.type == "citations_delta": + if content_block.type == "text": + events_to_fire.append( + build( + CitationEvent, + type="citation", + citation=event.delta.citation, + snapshot=content_block.citations or [], + ) + ) + elif event.delta.type == "thinking_delta": + if content_block.type == "thinking": + events_to_fire.append( + build( + ThinkingEvent, + type="thinking", + thinking=event.delta.thinking, + snapshot=content_block.thinking, + ) + ) + elif event.delta.type == "signature_delta": + if content_block.type == "thinking": + events_to_fire.append( + build( + SignatureEvent, + type="signature", + signature=content_block.signature, + ) + ) + pass + else: + # we only want exhaustive checking for linters, not at runtime + if TYPE_CHECKING: # type: ignore[unreachable] + assert_never(event.delta) + elif event.type == "content_block_stop": + content_block = message_snapshot.content[event.index] + + event_to_fire = build( + ParsedContentBlockStopEvent, + type="content_block_stop", + index=event.index, + content_block=content_block, + ) + + events_to_fire.append(event_to_fire) + else: + # we only want exhaustive checking for linters, not at runtime + if TYPE_CHECKING: # type: ignore[unreachable] + assert_never(event) + + return events_to_fire + + +JSON_BUF_PROPERTY = "__json_buf" + +TRACKS_TOOL_INPUT = ( + ToolUseBlock, + ServerToolUseBlock, +) + + +def accumulate_event( + *, + event: RawMessageStreamEvent, + current_snapshot: ParsedMessage[ResponseFormatT] | None, + output_format: ResponseFormatT | NotGiven = NOT_GIVEN, +) -> ParsedMessage[ResponseFormatT]: + if not isinstance(cast(Any, event), BaseModel): + event = cast( # pyright: ignore[reportUnnecessaryCast] + RawMessageStreamEvent, + construct_type_unchecked( + type_=cast(Type[RawMessageStreamEvent], RawMessageStreamEvent), + value=event, + ), + ) + if not isinstance(cast(Any, event), BaseModel): + raise TypeError(f"Unexpected event runtime type, after deserialising twice - {event} - {type(event)}") + + if current_snapshot is None: + if event.type == "message_start": + return cast(ParsedMessage[ResponseFormatT], ParsedMessage.construct(**cast(Any, event.message.to_dict()))) + + raise RuntimeError(f'Unexpected event order, got {event.type} before "message_start"') + + if event.type == "content_block_start": + # TODO: check index + current_snapshot.content.append( + cast( + Any, # Pydantic does not support generic unions at runtime + construct_type(type_=ParsedContentBlock, value=event.content_block.model_dump()), + ), + ) + elif event.type == "content_block_delta": + content = current_snapshot.content[event.index] + if event.delta.type == "text_delta": + if content.type == "text": + content.text += event.delta.text + elif event.delta.type == "input_json_delta": + if isinstance(content, TRACKS_TOOL_INPUT): + from jiter import from_json + + # we need to keep track of the raw JSON string as well so that we can + # re-parse it for each delta, for now we just store it as an untyped + # property on the snapshot + json_buf = cast(bytes, getattr(content, JSON_BUF_PROPERTY, b"")) + json_buf += bytes(event.delta.partial_json, "utf-8") + + if json_buf: + content.input = from_json(json_buf, partial_mode=True) + + setattr(content, JSON_BUF_PROPERTY, json_buf) + elif event.delta.type == "citations_delta": + if content.type == "text": + if not content.citations: + content.citations = [event.delta.citation] + else: + content.citations.append(event.delta.citation) + elif event.delta.type == "thinking_delta": + if content.type == "thinking": + content.thinking += event.delta.thinking + elif event.delta.type == "signature_delta": + if content.type == "thinking": + content.signature = event.delta.signature + else: + # we only want exhaustive checking for linters, not at runtime + if TYPE_CHECKING: # type: ignore[unreachable] + assert_never(event.delta) + elif event.type == "content_block_stop": + content_block = current_snapshot.content[event.index] + if content_block.type == "text" and is_given(output_format): + content_block.parsed_output = parse_text(content_block.text, output_format) + elif event.type == "message_delta": + current_snapshot.stop_reason = event.delta.stop_reason + current_snapshot.stop_sequence = event.delta.stop_sequence + if event.delta.stop_details is not None: + current_snapshot.stop_details = event.delta.stop_details + current_snapshot.usage.output_tokens = event.usage.output_tokens + + # Update other usage fields if they exist in the event + if event.usage.input_tokens is not None: + current_snapshot.usage.input_tokens = event.usage.input_tokens + if event.usage.cache_creation_input_tokens is not None: + current_snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens + if event.usage.cache_read_input_tokens is not None: + current_snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens + if event.usage.server_tool_use is not None: + current_snapshot.usage.server_tool_use = event.usage.server_tool_use + + return current_snapshot diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/_types.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/_types.py new file mode 100644 index 0000000000000000000000000000000000000000..7399e76f417a4138ff87bbbc3b530cbfe7f52ada --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/streaming/_types.py @@ -0,0 +1,140 @@ +from typing import TYPE_CHECKING, Any, Dict, Union, Generic, cast +from typing_extensions import List, Literal, Annotated + +import jiter + +from ...types import ( + Message, + ContentBlock, + MessageDeltaEvent as RawMessageDeltaEvent, + MessageStartEvent as RawMessageStartEvent, + RawMessageStopEvent, + ContentBlockDeltaEvent as RawContentBlockDeltaEvent, + ContentBlockStartEvent as RawContentBlockStartEvent, + RawContentBlockStopEvent, +) +from ..._models import BaseModel, GenericModel +from .._parse._response import ResponseFormatT +from ..._utils._transform import PropertyInfo +from ...types.parsed_message import ParsedMessage, ParsedContentBlock +from ...types.citations_delta import Citation + + +class TextEvent(BaseModel): + type: Literal["text"] + + text: str + """The text delta""" + + snapshot: str + """The entire accumulated text""" + + def parsed_snapshot(self) -> Dict[str, Any]: + return cast(Dict[str, Any], jiter.from_json(self.snapshot.encode("utf-8"), partial_mode="trailing-strings")) + + +class CitationEvent(BaseModel): + type: Literal["citation"] + + citation: Citation + """The new citation""" + + snapshot: List[Citation] + """All of the accumulated citations""" + + +class ThinkingEvent(BaseModel): + type: Literal["thinking"] + + thinking: str + """The thinking delta""" + + snapshot: str + """The accumulated thinking so far""" + + +class SignatureEvent(BaseModel): + type: Literal["signature"] + + signature: str + """The signature of the thinking block""" + + +class InputJsonEvent(BaseModel): + type: Literal["input_json"] + + partial_json: str + """A partial JSON string delta + + e.g. `'"San Francisco,'` + """ + + snapshot: object + """The currently accumulated parsed object. + + + e.g. `{'location': 'San Francisco, CA'}` + """ + + +class MessageStopEvent(RawMessageStopEvent): + type: Literal["message_stop"] + + message: Message + + +class ContentBlockStopEvent(RawContentBlockStopEvent): + type: Literal["content_block_stop"] + + content_block: ContentBlock + + +MessageStreamEvent = Annotated[ + Union[ + TextEvent, + CitationEvent, + ThinkingEvent, + SignatureEvent, + InputJsonEvent, + RawMessageStartEvent, + RawMessageDeltaEvent, + MessageStopEvent, + RawContentBlockStartEvent, + RawContentBlockDeltaEvent, + ContentBlockStopEvent, + ], + PropertyInfo(discriminator="type"), +] + + +class ParsedMessageStopEvent(RawMessageStopEvent, GenericModel, Generic[ResponseFormatT]): + type: Literal["message_stop"] + + message: ParsedMessage[ResponseFormatT] + + +class ParsedContentBlockStopEvent(RawContentBlockStopEvent, GenericModel, Generic[ResponseFormatT]): + type: Literal["content_block_stop"] + + if TYPE_CHECKING: + content_block: ParsedContentBlock[ResponseFormatT] + else: + content_block: ParsedContentBlock + + +ParsedMessageStreamEvent = Annotated[ + Union[ + TextEvent, + CitationEvent, + ThinkingEvent, + SignatureEvent, + InputJsonEvent, + RawMessageStartEvent, + RawMessageDeltaEvent, + ParsedMessageStopEvent[ResponseFormatT], + RawContentBlockStartEvent, + RawContentBlockDeltaEvent, + ParsedContentBlockStopEvent[ResponseFormatT], + ], + PropertyInfo(discriminator="type"), +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/__init__.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b8593e1180a98724eb8e60f2ce3eb0a50912f0fe --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/__init__.py @@ -0,0 +1,29 @@ +from ._beta_runner import BetaToolRunner, BetaAsyncToolRunner, BetaStreamingToolRunner, BetaAsyncStreamingToolRunner +from ._beta_functions import ( + ToolError, + BetaFunctionTool, + BetaAsyncFunctionTool, + BetaBuiltinFunctionTool, + BetaFunctionToolResultType, + BetaAsyncBuiltinFunctionTool, + beta_tool, + beta_async_tool, +) +from ._beta_builtin_memory_tool import BetaAbstractMemoryTool, BetaAsyncAbstractMemoryTool + +__all__ = [ + "beta_tool", + "beta_async_tool", + "BetaFunctionTool", + "BetaAsyncFunctionTool", + "BetaBuiltinFunctionTool", + "BetaAsyncBuiltinFunctionTool", + "BetaToolRunner", + "BetaAsyncStreamingToolRunner", + "BetaStreamingToolRunner", + "BetaAsyncToolRunner", + "BetaFunctionToolResultType", + "BetaAbstractMemoryTool", + "BetaAsyncAbstractMemoryTool", + "ToolError", +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/__pycache__/__init__.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40305560e2f99daa4ddc136bbe2ac6bc84ba571f Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/__pycache__/__init__.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/__pycache__/_beta_builtin_memory_tool.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/__pycache__/_beta_builtin_memory_tool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a581242f9a678751fef089235a9b02058e39b6c Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/__pycache__/_beta_builtin_memory_tool.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/__pycache__/_beta_compaction_control.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/__pycache__/_beta_compaction_control.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c267d90a70ce01deaaa6753185336bfffd75a12 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/__pycache__/_beta_compaction_control.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/__pycache__/_beta_functions.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/__pycache__/_beta_functions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d37307e3e3c2d82e9e955a85fb663ef3fc019853 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/__pycache__/_beta_functions.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/__pycache__/_beta_runner.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/__pycache__/_beta_runner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b0a35496bc692e6e08cd772c71f65312b9f0e14 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/__pycache__/_beta_runner.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/__pycache__/mcp.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/__pycache__/mcp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebc2219941936fde149ea45eb3a9c0dbc19d6297 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/__pycache__/mcp.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/_beta_builtin_memory_tool.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/_beta_builtin_memory_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..edb948a2636f9a022144c7b01c4cd1ca59226e23 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/_beta_builtin_memory_tool.py @@ -0,0 +1,875 @@ +from __future__ import annotations + +import os +import uuid +import shutil +from abc import abstractmethod +from typing import TYPE_CHECKING, Any, List, cast +from pathlib import Path +from typing_extensions import override, assert_never + +from anyio import Path as AsyncPath +from anyio.to_thread import run_sync + +from anthropic.types.beta import ( + BetaMemoryTool20250818ViewCommand, + BetaMemoryTool20250818CreateCommand, + BetaMemoryTool20250818DeleteCommand, + BetaMemoryTool20250818InsertCommand, + BetaMemoryTool20250818RenameCommand, + BetaMemoryTool20250818StrReplaceCommand, +) + +from ..._models import construct_type_unchecked +from ...types.beta import ( + BetaMemoryTool20250818Param, + BetaMemoryTool20250818Command, + BetaCacheControlEphemeralParam, + BetaMemoryTool20250818ViewCommand, + BetaMemoryTool20250818CreateCommand, + BetaMemoryTool20250818DeleteCommand, + BetaMemoryTool20250818InsertCommand, + BetaMemoryTool20250818RenameCommand, + BetaMemoryTool20250818StrReplaceCommand, +) +from ._beta_functions import ( + ToolError, + BetaBuiltinFunctionTool, + BetaFunctionToolResultType, + BetaAsyncBuiltinFunctionTool, +) + +MAX_LINES = 999999 +LINE_NUMBER_WIDTH = len(str(MAX_LINES)) + +# Owner read/write only. Avoids 0o666 which, in environments with a permissive +# umask (e.g. Docker where umask is often 0o000), would make memory files +# world-readable or even world-writable. +_FILE_CREATE_MODE = 0o600 +# The default mkdir mode is 0o777, but we want to be more restrictive for memory +# directories to avoid them being world-accessible in environments with permissive umasks +# (eg Docker) +_DIR_CREATE_MODE = 0o700 + + +class BetaAbstractMemoryTool(BetaBuiltinFunctionTool): + """Abstract base class for memory tool implementations. + + This class provides the interface for implementing a custom memory backend for Claude. + + Subclass this to create your own memory storage solution (e.g., database, cloud storage, encrypted files, etc.). + + Example usage: + + ```py + class MyMemoryTool(BetaAbstractMemoryTool): + def view(self, command: BetaMemoryTool20250818ViewCommand) -> BetaFunctionToolResultType: + ... + return "view result" + + def create(self, command: BetaMemoryTool20250818CreateCommand) -> BetaFunctionToolResultType: + ... + return "created successfully" + + # ... implement other abstract methods + + + client = Anthropic() + memory_tool = MyMemoryTool() + message = client.beta.messages.run_tools( + model="claude-sonnet-4-5", + messages=[{"role": "user", "content": "Remember that I like coffee"}], + tools=[memory_tool], + ).until_done() + ``` + """ + + def __init__(self, *, cache_control: BetaCacheControlEphemeralParam | None = None) -> None: + super().__init__() + self._cache_control = cache_control + + @override + def to_dict(self) -> BetaMemoryTool20250818Param: + param: BetaMemoryTool20250818Param = {"type": "memory_20250818", "name": "memory"} + + if self._cache_control is not None: + param["cache_control"] = self._cache_control + + return param + + @override + def call(self, input: object) -> BetaFunctionToolResultType: + command = cast( + BetaMemoryTool20250818Command, + construct_type_unchecked(value=input, type_=cast(Any, BetaMemoryTool20250818Command)), + ) + return self.execute(command) + + def execute(self, command: BetaMemoryTool20250818Command) -> BetaFunctionToolResultType: + """Execute a memory command and return the result. + + This method dispatches to the appropriate handler method based on the + command type (view, create, str_replace, insert, delete, rename). + + You typically don't need to override this method. + """ + if command.command == "view": + return self.view(command) + elif command.command == "create": + return self.create(command) + elif command.command == "str_replace": + return self.str_replace(command) + elif command.command == "insert": + return self.insert(command) + elif command.command == "delete": + return self.delete(command) + elif command.command == "rename": + return self.rename(command) + elif TYPE_CHECKING: # type: ignore[unreachable] + assert_never(command) + else: + raise NotImplementedError(f"Unknown command: {command.command}") + + @abstractmethod + def view(self, command: BetaMemoryTool20250818ViewCommand) -> BetaFunctionToolResultType: + """View the contents of a memory path.""" + pass + + @abstractmethod + def create(self, command: BetaMemoryTool20250818CreateCommand) -> BetaFunctionToolResultType: + """Create a new memory file with the specified content.""" + pass + + @abstractmethod + def str_replace(self, command: BetaMemoryTool20250818StrReplaceCommand) -> BetaFunctionToolResultType: + """Replace text in a memory file.""" + pass + + @abstractmethod + def insert(self, command: BetaMemoryTool20250818InsertCommand) -> BetaFunctionToolResultType: + """Insert text at a specific line number in a memory file.""" + pass + + @abstractmethod + def delete(self, command: BetaMemoryTool20250818DeleteCommand) -> BetaFunctionToolResultType: + """Delete a memory file or directory.""" + pass + + @abstractmethod + def rename(self, command: BetaMemoryTool20250818RenameCommand) -> BetaFunctionToolResultType: + """Rename or move a memory file or directory.""" + pass + + def clear_all_memory(self) -> BetaFunctionToolResultType: + """Clear all memory data.""" + raise NotImplementedError("clear_all_memory not implemented") + + +class BetaAsyncAbstractMemoryTool(BetaAsyncBuiltinFunctionTool): + """Abstract base class for memory tool implementations. + + This class provides the interface for implementing a custom memory backend for Claude. + + Subclass this to create your own memory storage solution (e.g., database, cloud storage, encrypted files, etc.). + + Example usage: + + ```py + class MyMemoryTool(BetaAbstractMemoryTool): + def view(self, command: BetaMemoryTool20250818ViewCommand) -> BetaFunctionToolResultType: + ... + return "view result" + + def create(self, command: BetaMemoryTool20250818CreateCommand) -> BetaFunctionToolResultType: + ... + return "created successfully" + + # ... implement other abstract methods + + + client = Anthropic() + memory_tool = MyMemoryTool() + message = client.beta.messages.run_tools( + model="claude-sonnet-4-5", + messages=[{"role": "user", "content": "Remember that I like coffee"}], + tools=[memory_tool], + ).until_done() + ``` + """ + + def __init__(self, *, cache_control: BetaCacheControlEphemeralParam | None = None) -> None: + super().__init__() + self._cache_control = cache_control + + @override + def to_dict(self) -> BetaMemoryTool20250818Param: + param: BetaMemoryTool20250818Param = {"type": "memory_20250818", "name": "memory"} + + if self._cache_control is not None: + param["cache_control"] = self._cache_control + + return param + + @override + async def call(self, input: object) -> BetaFunctionToolResultType: + command = cast( + BetaMemoryTool20250818Command, + construct_type_unchecked(value=input, type_=cast(Any, BetaMemoryTool20250818Command)), + ) + return await self.execute(command) + + async def execute(self, command: BetaMemoryTool20250818Command) -> BetaFunctionToolResultType: + """Execute a memory command and return the result. + + This method dispatches to the appropriate handler method based on the + command type (view, create, str_replace, insert, delete, rename). + + You typically don't need to override this method. + """ + if command.command == "view": + return await self.view(command) + elif command.command == "create": + return await self.create(command) + elif command.command == "str_replace": + return await self.str_replace(command) + elif command.command == "insert": + return await self.insert(command) + elif command.command == "delete": + return await self.delete(command) + elif command.command == "rename": + return await self.rename(command) + elif TYPE_CHECKING: # type: ignore[unreachable] + assert_never(command) + else: + raise NotImplementedError(f"Unknown command: {command.command}") + + @abstractmethod + async def view(self, command: BetaMemoryTool20250818ViewCommand) -> BetaFunctionToolResultType: + """View the contents of a memory path.""" + pass + + @abstractmethod + async def create(self, command: BetaMemoryTool20250818CreateCommand) -> BetaFunctionToolResultType: + """Create a new memory file with the specified content.""" + pass + + @abstractmethod + async def str_replace(self, command: BetaMemoryTool20250818StrReplaceCommand) -> BetaFunctionToolResultType: + """Replace text in a memory file.""" + pass + + @abstractmethod + async def insert(self, command: BetaMemoryTool20250818InsertCommand) -> BetaFunctionToolResultType: + """Insert text at a specific line number in a memory file.""" + pass + + @abstractmethod + async def delete(self, command: BetaMemoryTool20250818DeleteCommand) -> BetaFunctionToolResultType: + """Delete a memory file or directory.""" + pass + + @abstractmethod + async def rename(self, command: BetaMemoryTool20250818RenameCommand) -> BetaFunctionToolResultType: + """Rename or move a memory file or directory.""" + pass + + async def clear_all_memory(self) -> BetaFunctionToolResultType: + """Clear all memory data.""" + raise NotImplementedError("clear_all_memory not implemented") + + +def _atomic_write_file(target_path: Path, content: str) -> None: + dir_path = target_path.parent + temp_path = dir_path / f".tmp-{os.getpid()}-{uuid.uuid4()}" + data = content.encode("utf-8") + + try: + fd = os.open(temp_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, _FILE_CREATE_MODE) + try: + offset = 0 + while offset < len(data): + written = os.write(fd, data[offset:]) + if written == 0: + raise OSError("os.write returned 0") + offset += written + + os.fsync(fd) + finally: + os.close(fd) + + os.replace(temp_path, target_path) + except Exception: + temp_path.unlink(missing_ok=True) + raise + + +def _validate_no_symlink_escape(target_path: Path, memory_root: Path) -> None: + resolved_root = memory_root.resolve() + + current = target_path + while True: + try: + resolved = current.resolve() + if resolved != resolved_root and not str(resolved).startswith(str(resolved_root) + os.sep): + raise ToolError("Path would escape /memories directory via symlink") + return + except (FileNotFoundError, OSError): + parent = current.parent + if parent == current or current == memory_root: + return + current = parent + + +def _read_file_content(full_path: Path, memory_path: str) -> str: + try: + return full_path.read_text(encoding="utf-8") + except FileNotFoundError as err: + raise ToolError( + f"The file {memory_path} no longer exists (may have been deleted or renamed concurrently)." + ) from err + + +def _format_file_size(bytes_size: int) -> str: + if bytes_size == 0: + return "0B" + k = 1024 + sizes = ["B", "K", "M", "G"] + i = int(bytes_size.bit_length() - 1) // 10 + i = min(i, len(sizes) - 1) + size = bytes_size / (k**i) + + if size == int(size): + return f"{int(size)}{sizes[i]}" + else: + return f"{size:.1f}{sizes[i]}" + + +class BetaLocalFilesystemMemoryTool(BetaAbstractMemoryTool): + """File-based memory storage implementation for Claude conversations""" + + def __init__(self, base_path: str = "./memory"): + super().__init__() + self.base_path = Path(base_path) + self.memory_root = self.base_path / "memories" + self.memory_root.mkdir(parents=True, exist_ok=True, mode=_DIR_CREATE_MODE) + + def _validate_path(self, path: str) -> Path: + """Validate and resolve memory paths""" + if not path.startswith("/memories"): + raise ToolError(f"Path must start with /memories, got: {path}") + + relative_path = path[len("/memories") :].lstrip("/") + full_path = self.memory_root / relative_path if relative_path else self.memory_root + + resolved_path = full_path.resolve() + resolved_root = self.memory_root.resolve() + if resolved_path != resolved_root and not str(resolved_path).startswith(str(resolved_root) + os.sep): + raise ToolError(f"Path {path} would escape /memories directory") + + _validate_no_symlink_escape(resolved_path, self.memory_root) + + return resolved_path + + @override + def view(self, command: BetaMemoryTool20250818ViewCommand) -> str: + full_path = self._validate_path(command.path) + + if not full_path.exists(): + raise ToolError(f"The path {command.path} does not exist. Please provide a valid path.") + + if full_path.is_dir(): + items: List[tuple[str, str]] = [] + + def collect_items(dir_path: Path, relative_path: str, depth: int) -> None: + if depth > 2: + return + + try: + dir_contents = sorted(dir_path.iterdir(), key=lambda x: x.name) + except Exception: + return + + for item in dir_contents: + if item.name.startswith("."): + continue + item_relative_path = f"{relative_path}/{item.name}" if relative_path else item.name + try: + stat = item.stat() + except Exception: + continue + + if item.is_dir(): + items.append((_format_file_size(stat.st_size), f"{item_relative_path}/")) + if depth < 2: + collect_items(item, item_relative_path, depth + 1) + elif item.is_file(): + items.append((_format_file_size(stat.st_size), item_relative_path)) + + collect_items(full_path, "", 1) + + header = f"Here're the files and directories up to 2 levels deep in {command.path}, excluding hidden items:" + dir_stat = full_path.stat() + dir_size = _format_file_size(dir_stat.st_size) + lines = [f"{dir_size}\t{command.path}"] + lines.extend([f"{size}\t{command.path}/{path}" for size, path in items]) + + return f"{header}\n" + "\n".join(lines) + + elif full_path.is_file(): + content = _read_file_content(full_path, command.path) + lines = content.split("\n") + + if len(lines) > MAX_LINES: + raise ToolError(f"File {command.path} exceeds maximum line limit of 999,999 lines.") + + display_lines = lines + start_num = 1 + + if command.view_range and len(command.view_range) == 2: + start_line = max(1, command.view_range[0]) - 1 + end_line = len(lines) if command.view_range[1] == -1 else command.view_range[1] + display_lines = lines[start_line:end_line] + start_num = start_line + 1 + + numbered_lines = [ + f"{str(i + start_num).rjust(LINE_NUMBER_WIDTH)}\t{line}" for i, line in enumerate(display_lines) + ] + + return f"Here's the content of {command.path} with line numbers:\n" + "\n".join(numbered_lines) + else: + raise ToolError(f"Unsupported file type for {command.path}") + + @override + def create(self, command: BetaMemoryTool20250818CreateCommand) -> str: + full_path = self._validate_path(command.path) + + full_path.parent.mkdir(parents=True, exist_ok=True, mode=_DIR_CREATE_MODE) + + try: + fd = os.open(full_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, _FILE_CREATE_MODE) + try: + os.write(fd, command.file_text.encode("utf-8")) + os.fsync(fd) + finally: + os.close(fd) + except FileExistsError as err: + raise ToolError(f"File {command.path} already exists") from err + + return f"File created successfully at: {command.path}" + + @override + def str_replace(self, command: BetaMemoryTool20250818StrReplaceCommand) -> str: + full_path = self._validate_path(command.path) + + if not full_path.exists(): + raise ToolError(f"The path {command.path} does not exist. Please provide a valid path.") + + if not full_path.is_file(): + raise ToolError(f"The path {command.path} is not a file.") + + content = _read_file_content(full_path, command.path) + + count = content.count(command.old_str) + if count == 0: + raise ToolError( + f"No replacement was performed, old_str `{command.old_str}` did not appear verbatim in {command.path}." + ) + elif count > 1: + matching_lines: List[int] = [] + start = 0 + while True: + pos = content.find(command.old_str, start) + if pos == -1: + break + matching_lines.append(content[:pos].count("\n") + 1) + start = pos + 1 + raise ToolError( + f"No replacement was performed. Multiple occurrences of old_str `{command.old_str}` in lines: {', '.join(map(str, matching_lines))}. Please ensure it is unique" + ) + + pos = content.find(command.old_str) + changed_line_index = content[:pos].count("\n") + new_content = content.replace(command.old_str, command.new_str) + _atomic_write_file(full_path, new_content) + + new_lines = new_content.split("\n") + context_start = max(0, changed_line_index - 2) + context_end = min(len(new_lines), changed_line_index + 3) + snippet = [ + f"{str(line_num).rjust(LINE_NUMBER_WIDTH)}\t{new_lines[line_num - 1]}" + for line_num in range(context_start + 1, context_end + 1) + ] + + return ( + f"The memory file has been edited. Here is the snippet showing the change (with line numbers):\n" + + "\n".join(snippet) + ) + + @override + def insert(self, command: BetaMemoryTool20250818InsertCommand) -> str: + full_path = self._validate_path(command.path) + + if not full_path.exists(): + raise ToolError(f"The path {command.path} does not exist. Please provide a valid path.") + + if not full_path.is_file(): + raise ToolError(f"The path {command.path} is not a file.") + + content = _read_file_content(full_path, command.path) + lines = content.splitlines() + + if command.insert_line < 0 or command.insert_line > len(lines): + raise ToolError( + f"Invalid `insert_line` parameter: {command.insert_line}. " + f"It should be within the range [0, {len(lines)}]." + ) + + lines.insert(command.insert_line, command.insert_text.rstrip("\n")) + new_content = "\n".join(lines) + if not new_content.endswith("\n"): + new_content += "\n" + _atomic_write_file(full_path, content=new_content) + return f"The file {command.path} has been edited." + + @override + def delete(self, command: BetaMemoryTool20250818DeleteCommand) -> str: + full_path = self._validate_path(command.path) + + if command.path == "/memories": + raise ToolError("Cannot delete the /memories directory itself") + + try: + if full_path.is_file(): + full_path.unlink() + elif full_path.is_dir(): + shutil.rmtree(full_path) + else: + raise ToolError(f"The path {command.path} does not exist") + except FileNotFoundError as err: + raise ToolError(f"The path {command.path} does not exist") from err + + return f"Successfully deleted {command.path}" + + @override + def rename(self, command: BetaMemoryTool20250818RenameCommand) -> str: + old_full_path = self._validate_path(command.old_path) + new_full_path = self._validate_path(command.new_path) + + if new_full_path.exists(): + raise ToolError(f"The destination {command.new_path} already exists") + + new_full_path.parent.mkdir(parents=True, exist_ok=True, mode=_DIR_CREATE_MODE) + + try: + old_full_path.rename(new_full_path) + except FileNotFoundError as err: + raise ToolError(f"The path {command.old_path} does not exist") from err + + return f"Successfully renamed {command.old_path} to {command.new_path}" + + @override + def clear_all_memory(self) -> str: + """Override the base implementation to provide file system clearing.""" + if self.memory_root.exists(): + shutil.rmtree(self.memory_root) + self.memory_root.mkdir(parents=True, exist_ok=True, mode=_DIR_CREATE_MODE) + return "All memory cleared" + + +async def _async_atomic_write_file(target_path: AsyncPath, content: str) -> None: + temp_path = target_path.parent / f".tmp-{os.getpid()}-{uuid.uuid4()}" + sync_target_path = Path(str(target_path)) + sync_temp_path = Path(str(temp_path)) + data = content.encode("utf-8") + + try: + + def write_replace_and_sync() -> None: + fd = os.open(sync_temp_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, _FILE_CREATE_MODE) + try: + offset = 0 + while offset < len(data): + written = os.write(fd, data[offset:]) + if written == 0: + raise OSError("os.write returned 0") + offset += written + + os.fsync(fd) + finally: + os.close(fd) + + os.replace(sync_temp_path, sync_target_path) + + await run_sync(write_replace_and_sync) + + except Exception: + await temp_path.unlink(missing_ok=True) + raise + + +async def _async_validate_no_symlink_escape(target_path: AsyncPath, memory_root: AsyncPath) -> None: + sync_target = Path(str(target_path)) + sync_root = Path(str(memory_root)) + await run_sync(_validate_no_symlink_escape, sync_target, sync_root) + + +async def _async_read_file_content(full_path: AsyncPath, memory_path: str) -> str: + try: + return await full_path.read_text(encoding="utf-8") + except FileNotFoundError as err: + raise ToolError( + f"The file {memory_path} no longer exists (may have been deleted or renamed concurrently)." + ) from err + + +class BetaAsyncLocalFilesystemMemoryTool(BetaAsyncAbstractMemoryTool): + """Async file-based memory storage implementation for Claude conversations""" + + def __init__(self, base_path: str = "./memory"): + super().__init__() + self.base_path = AsyncPath(base_path) + self.memory_root = self.base_path / "memories" + # Note: Directory creation is deferred to async methods since __init__ can't be async + + async def _ensure_memory_root(self) -> None: + """Ensure the memory root directory exists""" + await self.memory_root.mkdir(parents=True, exist_ok=True, mode=_DIR_CREATE_MODE) + + async def _validate_path(self, path: str) -> AsyncPath: + """Validate and resolve memory paths""" + if not path.startswith("/memories"): + raise ToolError(f"Path must start with /memories, got: {path}") + + relative_path = path[len("/memories") :].lstrip("/") + full_path = self.memory_root / relative_path if relative_path else self.memory_root + + sync_memory_root = Path(str(self.memory_root)) + sync_full_path = Path(str(full_path)) + + resolved_path = sync_full_path.resolve() + resolved_root = sync_memory_root.resolve() + if resolved_path != resolved_root and not str(resolved_path).startswith(str(resolved_root) + os.sep): + raise ToolError(f"Path {path} would escape /memories directory") + + await _async_validate_no_symlink_escape(full_path, self.memory_root) + + return AsyncPath(resolved_path) + + @override + async def view(self, command: BetaMemoryTool20250818ViewCommand) -> str: + await self._ensure_memory_root() + full_path = await self._validate_path(command.path) + + if not await full_path.exists(): + raise ToolError(f"The path {command.path} does not exist. Please provide a valid path.") + + if await full_path.is_dir(): + items: List[tuple[str, str]] = [] + + async def collect_items(dir_path: AsyncPath, relative_path: str, depth: int) -> None: + if depth > 2: + return + + try: + dir_items = [item async for item in dir_path.iterdir()] + dir_contents = sorted(dir_items, key=lambda x: x.name) + except Exception: + return + + for item in dir_contents: + if item.name.startswith("."): + continue + item_relative_path = f"{relative_path}/{item.name}" if relative_path else item.name + try: + sync_item = Path(str(item)) + stat = await run_sync(sync_item.stat) + except Exception: + continue + + if await item.is_dir(): + items.append((_format_file_size(stat.st_size), f"{item_relative_path}/")) + if depth < 2: + await collect_items(item, item_relative_path, depth + 1) + elif await item.is_file(): + items.append((_format_file_size(stat.st_size), item_relative_path)) + + await collect_items(full_path, "", 1) + + header = f"Here're the files and directories up to 2 levels deep in {command.path}, excluding hidden items:" + sync_full_path = Path(str(full_path)) + dir_stat = await run_sync(sync_full_path.stat) + dir_size = _format_file_size(dir_stat.st_size) + lines = [f"{dir_size}\t{command.path}"] + lines.extend([f"{size}\t{command.path}/{path}" for size, path in items]) + + return f"{header}\n" + "\n".join(lines) + + elif await full_path.is_file(): + content = await _async_read_file_content(full_path, command.path) + lines = content.split("\n") + + if len(lines) > MAX_LINES: + raise ToolError(f"File {command.path} exceeds maximum line limit of 999,999 lines.") + + display_lines = lines + start_num = 1 + + if command.view_range and len(command.view_range) == 2: + start_line = max(1, command.view_range[0]) - 1 + end_line = len(lines) if command.view_range[1] == -1 else command.view_range[1] + display_lines = lines[start_line:end_line] + start_num = start_line + 1 + + numbered_lines = [ + f"{str(i + start_num).rjust(LINE_NUMBER_WIDTH)}\t{line}" for i, line in enumerate(display_lines) + ] + + return f"Here's the content of {command.path} with line numbers:\n" + "\n".join(numbered_lines) + else: + raise ToolError(f"Unsupported file type for {command.path}") + + @override + async def create(self, command: BetaMemoryTool20250818CreateCommand) -> str: + await self._ensure_memory_root() + full_path = await self._validate_path(command.path) + + await full_path.parent.mkdir(parents=True, exist_ok=True, mode=_DIR_CREATE_MODE) + + try: + sync_full_path = Path(str(full_path)) + + def create_exclusive() -> None: + fd = os.open(sync_full_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, _FILE_CREATE_MODE) + try: + os.write(fd, command.file_text.encode("utf-8")) + os.fsync(fd) + finally: + os.close(fd) + + await run_sync(create_exclusive) + except FileExistsError as err: + raise ToolError(f"File {command.path} already exists") from err + + return f"File created successfully at: {command.path}" + + @override + async def str_replace(self, command: BetaMemoryTool20250818StrReplaceCommand) -> str: + await self._ensure_memory_root() + full_path = await self._validate_path(command.path) + + if not await full_path.exists(): + raise ToolError(f"The path {command.path} does not exist. Please provide a valid path.") + + if not await full_path.is_file(): + raise ToolError(f"The path {command.path} is not a file.") + + content = await _async_read_file_content(full_path, command.path) + + count = content.count(command.old_str) + if count == 0: + raise ToolError( + f"No replacement was performed, old_str `{command.old_str}` did not appear verbatim in {command.path}." + ) + elif count > 1: + matching_lines: List[int] = [] + start = 0 + while True: + pos = content.find(command.old_str, start) + if pos == -1: + break + matching_lines.append(content[:pos].count("\n") + 1) + start = pos + 1 + raise ToolError( + f"No replacement was performed. Multiple occurrences of old_str `{command.old_str}` in lines: {', '.join(map(str, matching_lines))}. Please ensure it is unique" + ) + + pos = content.find(command.old_str) + changed_line_index = content[:pos].count("\n") + new_content = content.replace(command.old_str, command.new_str) + await _async_atomic_write_file(full_path, new_content) + + new_lines = new_content.split("\n") + context_start = max(0, changed_line_index - 2) + context_end = min(len(new_lines), changed_line_index + 3) + snippet = [ + f"{str(line_num).rjust(LINE_NUMBER_WIDTH)}\t{new_lines[line_num - 1]}" + for line_num in range(context_start + 1, context_end + 1) + ] + + return ( + f"The memory file has been edited. Here is the snippet showing the change (with line numbers):\n" + + "\n".join(snippet) + ) + + @override + async def insert(self, command: BetaMemoryTool20250818InsertCommand) -> str: + await self._ensure_memory_root() + full_path = await self._validate_path(command.path) + + if not await full_path.exists(): + raise ToolError(f"The path {command.path} does not exist. Please provide a valid path.") + + if not await full_path.is_file(): + raise ToolError(f"The path {command.path} is not a file.") + + content = await _async_read_file_content(full_path, command.path) + lines = content.splitlines() + + if command.insert_line < 0 or command.insert_line > len(lines): + raise ToolError( + f"Invalid `insert_line` parameter: {command.insert_line}. " + f"It should be within the range [0, {len(lines)}]." + ) + + lines.insert(command.insert_line, command.insert_text.rstrip("\n")) + new_content = "\n".join(lines) + if not new_content.endswith("\n"): + new_content += "\n" + await _async_atomic_write_file(full_path, content=new_content) + return f"The file {command.path} has been edited." + + @override + async def delete(self, command: BetaMemoryTool20250818DeleteCommand) -> str: + await self._ensure_memory_root() + full_path = await self._validate_path(command.path) + + if command.path == "/memories": + raise ToolError("Cannot delete the /memories directory itself") + + try: + if await full_path.is_file(): + await full_path.unlink() + elif await full_path.is_dir(): + await run_sync(shutil.rmtree, str(full_path)) + else: + raise ToolError(f"The path {command.path} does not exist") + except FileNotFoundError as err: + raise ToolError(f"The path {command.path} does not exist") from err + + return f"Successfully deleted {command.path}" + + @override + async def rename(self, command: BetaMemoryTool20250818RenameCommand) -> str: + await self._ensure_memory_root() + old_full_path = await self._validate_path(command.old_path) + new_full_path = await self._validate_path(command.new_path) + + if await new_full_path.exists(): + raise ToolError(f"The destination {command.new_path} already exists") + + await new_full_path.parent.mkdir(parents=True, exist_ok=True, mode=_DIR_CREATE_MODE) + + try: + await old_full_path.rename(new_full_path) + except FileNotFoundError as err: + raise ToolError(f"The path {command.old_path} does not exist") from err + + return f"Successfully renamed {command.old_path} to {command.new_path}" + + @override + async def clear_all_memory(self) -> str: + """Override the base implementation to provide file system clearing.""" + if await self.memory_root.exists(): + await run_sync(shutil.rmtree, str(self.memory_root)) + await self.memory_root.mkdir(parents=True, exist_ok=True, mode=_DIR_CREATE_MODE) + return "All memory cleared" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/_beta_compaction_control.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/_beta_compaction_control.py new file mode 100644 index 0000000000000000000000000000000000000000..e1e07b6a1ac623bd1d90ea63e26864b5a7b5285c --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/_beta_compaction_control.py @@ -0,0 +1,55 @@ +from typing import TypedDict +from typing_extensions import Required + +DEFAULT_SUMMARY_PROMPT = """You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include: +1. Task Overview +The user's core request and success criteria +Any clarifications or constraints they specified +2. Current State +What has been completed so far +Files created, modified, or analyzed (with paths if relevant) +Key outputs or artifacts produced +3. Important Discoveries +Technical constraints or requirements uncovered +Decisions made and their rationale +Errors encountered and how they were resolved +What approaches were tried that didn't work (and why) +4. Next Steps +Specific actions needed to complete the task +Any blockers or open questions to resolve +Priority order if multiple steps remain +5. Context to Preserve +User preferences or style requirements +Domain-specific details that aren't obvious +Any promises made to the user +Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task. +Wrap your summary in tags.""" + +DEFAULT_THRESHOLD = 100_000 + + +class CompactionControl(TypedDict, total=False): + """Client-side compaction control configuration. + + .. deprecated:: + Use server-side compaction instead by passing + ``edits=[{"type": "compact_20260112"}]`` in the params passed to ``tool_runner()``. + See https://platform.claude.com/docs/en/build-with-claude/compaction + """ + context_token_threshold: int + """The context token threshold at which to trigger compaction. + + When the cumulative token count (input + output) across all messages exceeds this threshold, + the message history will be automatically summarized and compressed. Defaults to 100,000 tokens. + """ + + model: str + """ + The model to use for generating the compaction summary. + If not specified, defaults to the same model used for the tool runner. + """ + + summary_prompt: str + """The prompt used to instruct the model on how to generate the summary.""" + + enabled: Required[bool] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/_beta_functions.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/_beta_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..c5d73b07b87fb6870296d607955acb4c6220ec2a --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/_beta_functions.py @@ -0,0 +1,429 @@ +from __future__ import annotations + +import logging +from abc import ABC, abstractmethod +from typing import Any, Union, Generic, TypeVar, Callable, Iterable, Coroutine, cast, overload +from inspect import iscoroutinefunction +from typing_extensions import Literal, TypeAlias, override + +import pydantic +import docstring_parser +from pydantic import BaseModel + +from ... import _compat +from ..._utils import is_dict +from ..._compat import cached_property +from ..._models import TypeAdapter +from ...types.beta import BetaToolParam, BetaToolUnionParam, BetaCacheControlEphemeralParam +from ..._utils._utils import CallableT +from ...types.tool_param import InputSchema +from ...types.beta.beta_tool_result_block_param import Content as BetaContent + +log = logging.getLogger(__name__) + +BetaFunctionToolResultType: TypeAlias = Union[str, Iterable[BetaContent]] + + +class ToolError(Exception): + """Error that can be raised from a tool to return structured content with ``is_error: True``. + + When the tool runner catches this error, it will use the :attr:`content` + property as the tool result instead of ``repr(exc)``. + + Example:: + + raise ToolError( + [ + {"type": "text", "text": "Error details here"}, + {"type": "image", "source": {"type": "base64", "data": "...", "media_type": "image/png"}}, + ] + ) + """ + + content: BetaFunctionToolResultType + + def __init__(self, content: BetaFunctionToolResultType) -> None: + if isinstance(content, str): + message = content + else: + parts: list[str] = [] + for block in content: + text = block.get("text") + if text is not None: + parts.append(str(text)) + else: + parts.append(f"[{block.get('type', 'unknown')}]") + message = " ".join(parts) if parts else "Tool error" + super().__init__(message) + self.content = content + + +Function = Callable[..., BetaFunctionToolResultType] +FunctionT = TypeVar("FunctionT", bound=Function) + +AsyncFunction = Callable[..., Coroutine[Any, Any, BetaFunctionToolResultType]] +AsyncFunctionT = TypeVar("AsyncFunctionT", bound=AsyncFunction) + + +class BetaBuiltinFunctionTool(ABC): + @abstractmethod + def to_dict(self) -> BetaToolUnionParam: ... + + @abstractmethod + def call(self, input: object) -> BetaFunctionToolResultType: ... + + @property + def name(self) -> str: + raw = self.to_dict() + if "mcp_server_name" in raw: + return raw["mcp_server_name"] + return raw["name"] + + +class BetaAsyncBuiltinFunctionTool(ABC): + @abstractmethod + def to_dict(self) -> BetaToolUnionParam: ... + + @abstractmethod + async def call(self, input: object) -> BetaFunctionToolResultType: ... + + @property + def name(self) -> str: + raw = self.to_dict() + if "mcp_server_name" in raw: + return raw["mcp_server_name"] + return raw["name"] + + +class BaseFunctionTool(Generic[CallableT]): + func: CallableT + """The function this tool is wrapping""" + + name: str + """The name of the tool that will be sent to the API""" + + description: str + + input_schema: InputSchema + + def __init__( + self, + func: CallableT, + *, + name: str | None = None, + description: str | None = None, + input_schema: InputSchema | type[BaseModel] | None = None, + defer_loading: bool | None = None, + cache_control: BetaCacheControlEphemeralParam | None = None, + allowed_callers: list[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] | None = None, + eager_input_streaming: bool | None = None, + input_examples: Iterable[dict[str, object]] | None = None, + strict: bool | None = None, + ) -> None: + if _compat.PYDANTIC_V1: + raise RuntimeError("Tool functions are only supported with Pydantic v2") + + self.func = func + self._func_with_validate = pydantic.validate_call(func) + self.name = name or func.__name__ + self._defer_loading = defer_loading + self._cache_control = cache_control + self._allowed_callers = allowed_callers + self._eager_input_streaming = eager_input_streaming + self._input_examples = input_examples + self._strict = strict + + self.description = description or self._get_description_from_docstring() + + if input_schema is not None: + if isinstance(input_schema, type): + self.input_schema: InputSchema = input_schema.model_json_schema() + else: + self.input_schema = input_schema + else: + self.input_schema = self._create_schema_from_function() + + @property + def __call__(self) -> CallableT: + return self.func + + def to_dict(self) -> BetaToolParam: + defn: BetaToolParam = { + "name": self.name, + "description": self.description, + "input_schema": self.input_schema, + } + if self._defer_loading is not None: + defn["defer_loading"] = self._defer_loading + if self._cache_control is not None: + defn["cache_control"] = self._cache_control + if self._allowed_callers is not None: + defn["allowed_callers"] = self._allowed_callers + if self._eager_input_streaming is not None: + defn["eager_input_streaming"] = self._eager_input_streaming + if self._input_examples is not None: + defn["input_examples"] = self._input_examples + if self._strict is not None: + defn["strict"] = self._strict + return defn + + @cached_property + def _parsed_docstring(self) -> docstring_parser.Docstring: + return docstring_parser.parse(self.func.__doc__ or "") + + def _get_description_from_docstring(self) -> str: + """Extract description from parsed docstring.""" + if self._parsed_docstring.short_description: + description = self._parsed_docstring.short_description + if self._parsed_docstring.long_description: + description += f"\n\n{self._parsed_docstring.long_description}" + return description + return "" + + def _create_schema_from_function(self) -> InputSchema: + """Create JSON schema from function signature using pydantic.""" + + from pydantic_core import CoreSchema + from pydantic.json_schema import JsonSchemaValue, GenerateJsonSchema + from pydantic_core.core_schema import ArgumentsParameter + + class CustomGenerateJsonSchema(GenerateJsonSchema): + def __init__(self, *, func: Callable[..., Any], parsed_docstring: Any) -> None: + super().__init__() + self._func = func + self._parsed_docstring = parsed_docstring + + def __call__(self, *_args: Any, **_kwds: Any) -> "CustomGenerateJsonSchema": # noqa: ARG002 + return self + + @override + def kw_arguments_schema( + self, + arguments: "list[ArgumentsParameter]", + var_kwargs_schema: CoreSchema | None, + ) -> JsonSchemaValue: + schema = super().kw_arguments_schema(arguments, var_kwargs_schema) + if schema.get("type") != "object": + return schema + + properties = schema.get("properties") + if not properties or not is_dict(properties): + return schema + + # Add parameter descriptions from docstring + for param in self._parsed_docstring.params: + prop_schema = properties.get(param.arg_name) + if not prop_schema or not is_dict(prop_schema): + continue + + if param.description and "description" not in prop_schema: + prop_schema["description"] = param.description + + return schema + + schema_generator = CustomGenerateJsonSchema(func=self.func, parsed_docstring=self._parsed_docstring) + return self._adapter.json_schema(schema_generator=schema_generator) # type: ignore + + @cached_property + def _adapter(self) -> TypeAdapter[Any]: + return TypeAdapter(self._func_with_validate) + + +class BetaFunctionTool(BaseFunctionTool[FunctionT]): + def call(self, input: object) -> BetaFunctionToolResultType: + if iscoroutinefunction(self.func): + raise RuntimeError("Cannot call a coroutine function synchronously. Use `@async_tool` instead.") + + if not is_dict(input): + raise TypeError(f"Input must be a dictionary, got {type(input).__name__}") + + try: + return self._func_with_validate(**cast(Any, input)) + except pydantic.ValidationError as e: + raise ValueError(f"Invalid arguments for function {self.name}") from e + + +class BetaAsyncFunctionTool(BaseFunctionTool[AsyncFunctionT]): + async def call(self, input: object) -> BetaFunctionToolResultType: + if not iscoroutinefunction(self.func): + raise RuntimeError("Cannot call a synchronous function asynchronously. Use `@tool` instead.") + + if not is_dict(input): + raise TypeError(f"Input must be a dictionary, got {type(input).__name__}") + + try: + return await self._func_with_validate(**cast(Any, input)) + except pydantic.ValidationError as e: + raise ValueError(f"Invalid arguments for function {self.name}") from e + + +@overload +def beta_tool(func: FunctionT) -> BetaFunctionTool[FunctionT]: ... + + +@overload +def beta_tool( + func: FunctionT, + *, + name: str | None = None, + description: str | None = None, + input_schema: InputSchema | type[BaseModel] | None = None, + defer_loading: bool | None = None, + cache_control: BetaCacheControlEphemeralParam | None = None, + allowed_callers: list[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] | None = None, + eager_input_streaming: bool | None = None, + input_examples: Iterable[dict[str, object]] | None = None, + strict: bool | None = None, +) -> BetaFunctionTool[FunctionT]: ... + + +@overload +def beta_tool( + *, + name: str | None = None, + description: str | None = None, + input_schema: InputSchema | type[BaseModel] | None = None, + defer_loading: bool | None = None, + cache_control: BetaCacheControlEphemeralParam | None = None, + allowed_callers: list[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] | None = None, + eager_input_streaming: bool | None = None, + input_examples: Iterable[dict[str, object]] | None = None, + strict: bool | None = None, +) -> Callable[[FunctionT], BetaFunctionTool[FunctionT]]: ... + + +def beta_tool( + func: FunctionT | None = None, + *, + name: str | None = None, + description: str | None = None, + input_schema: InputSchema | type[BaseModel] | None = None, + defer_loading: bool | None = None, + cache_control: BetaCacheControlEphemeralParam | None = None, + allowed_callers: list[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] | None = None, + eager_input_streaming: bool | None = None, + input_examples: Iterable[dict[str, object]] | None = None, + strict: bool | None = None, +) -> BetaFunctionTool[FunctionT] | Callable[[FunctionT], BetaFunctionTool[FunctionT]]: + """Create a FunctionTool from a function with automatic schema inference. + + Can be used as a decorator with or without parentheses: + + @function_tool + def my_func(x: int) -> str: ... + + @function_tool() + def my_func(x: int) -> str: ... + + @function_tool(name="custom_name") + def my_func(x: int) -> str: ... + """ + if _compat.PYDANTIC_V1: + raise RuntimeError("Tool functions are only supported with Pydantic v2") + + def _make(fn: FunctionT) -> BetaFunctionTool[FunctionT]: + return BetaFunctionTool( + fn, + name=name, + description=description, + input_schema=input_schema, + defer_loading=defer_loading, + cache_control=cache_control, + allowed_callers=allowed_callers, + eager_input_streaming=eager_input_streaming, + input_examples=input_examples, + strict=strict, + ) + + if func is not None: + return _make(func) + + return _make + + +@overload +def beta_async_tool(func: AsyncFunctionT) -> BetaAsyncFunctionTool[AsyncFunctionT]: ... + + +@overload +def beta_async_tool( + func: AsyncFunctionT, + *, + name: str | None = None, + description: str | None = None, + input_schema: InputSchema | type[BaseModel] | None = None, + defer_loading: bool | None = None, + cache_control: BetaCacheControlEphemeralParam | None = None, + allowed_callers: list[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] | None = None, + eager_input_streaming: bool | None = None, + input_examples: Iterable[dict[str, object]] | None = None, + strict: bool | None = None, +) -> BetaAsyncFunctionTool[AsyncFunctionT]: ... # noqa: E501 + + +@overload +def beta_async_tool( + *, + name: str | None = None, + description: str | None = None, + input_schema: InputSchema | type[BaseModel] | None = None, + defer_loading: bool | None = None, + cache_control: BetaCacheControlEphemeralParam | None = None, + allowed_callers: list[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] | None = None, + eager_input_streaming: bool | None = None, + input_examples: Iterable[dict[str, object]] | None = None, + strict: bool | None = None, +) -> Callable[[AsyncFunctionT], BetaAsyncFunctionTool[AsyncFunctionT]]: ... + + +def beta_async_tool( + func: AsyncFunctionT | None = None, + *, + name: str | None = None, + description: str | None = None, + input_schema: InputSchema | type[BaseModel] | None = None, + defer_loading: bool | None = None, + cache_control: BetaCacheControlEphemeralParam | None = None, + allowed_callers: list[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] | None = None, + eager_input_streaming: bool | None = None, + input_examples: Iterable[dict[str, object]] | None = None, + strict: bool | None = None, +) -> BetaAsyncFunctionTool[AsyncFunctionT] | Callable[[AsyncFunctionT], BetaAsyncFunctionTool[AsyncFunctionT]]: + """Create an AsyncFunctionTool from a function with automatic schema inference. + + Can be used as a decorator with or without parentheses: + + @async_tool + async def my_func(x: int) -> str: ... + + @async_tool() + async def my_func(x: int) -> str: ... + + @async_tool(name="custom_name") + async def my_func(x: int) -> str: ... + """ + if _compat.PYDANTIC_V1: + raise RuntimeError("Tool functions are only supported with Pydantic v2") + + def _make(fn: AsyncFunctionT) -> BetaAsyncFunctionTool[AsyncFunctionT]: + return BetaAsyncFunctionTool( + fn, + name=name, + description=description, + input_schema=input_schema, + defer_loading=defer_loading, + cache_control=cache_control, + allowed_callers=allowed_callers, + eager_input_streaming=eager_input_streaming, + input_examples=input_examples, + strict=strict, + ) + + if func is not None: + return _make(func) + + return _make + + +BetaRunnableTool = Union[BetaFunctionTool[Any], BetaBuiltinFunctionTool] +BetaAsyncRunnableTool = Union[BetaAsyncFunctionTool[Any], BetaAsyncBuiltinFunctionTool] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/_beta_runner.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/_beta_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..52e4869883a1ee5674d8d0c6fa29e8d3a2f6324d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/_beta_runner.py @@ -0,0 +1,685 @@ +from __future__ import annotations + +import logging +import warnings +from abc import ABC, abstractmethod +from typing import ( + TYPE_CHECKING, + Any, + List, + Union, + Generic, + TypeVar, + Callable, + Iterable, + Iterator, + Coroutine, + AsyncIterator, +) +from contextlib import contextmanager, asynccontextmanager +from typing_extensions import TypedDict, override + +import httpx + +from ..._types import Body, Query, Headers, NotGiven +from ..._utils import consume_sync_iterator, consume_async_iterator +from ...types.beta import BetaMessage, BetaMessageParam +from ._beta_functions import ( + ToolError, + BetaFunctionTool, + BetaRunnableTool, + BetaAsyncFunctionTool, + BetaAsyncRunnableTool, + BetaBuiltinFunctionTool, + BetaAsyncBuiltinFunctionTool, +) +from .._stainless_helpers import stainless_helper_header +from ._beta_compaction_control import DEFAULT_THRESHOLD, DEFAULT_SUMMARY_PROMPT, CompactionControl +from ..streaming._beta_messages import BetaMessageStream, BetaAsyncMessageStream +from ...types.beta.parsed_beta_message import ResponseFormatT, ParsedBetaMessage, ParsedBetaContentBlock +from ...types.beta.message_create_params import ParseMessageCreateParamsBase +from ...types.beta.beta_tool_result_block_param import BetaToolResultBlockParam + +if TYPE_CHECKING: + from ..._client import Anthropic, AsyncAnthropic + + +AnyFunctionToolT = TypeVar( + "AnyFunctionToolT", + bound=Union[ + BetaFunctionTool[Any], BetaAsyncFunctionTool[Any], BetaBuiltinFunctionTool, BetaAsyncBuiltinFunctionTool + ], +) +RunnerItemT = TypeVar("RunnerItemT") + +log = logging.getLogger(__name__) + + +class RequestOptions(TypedDict, total=False): + extra_headers: Headers | None + extra_query: Query | None + extra_body: Body | None + timeout: float | httpx.Timeout | None | NotGiven + + +class BaseToolRunner(Generic[AnyFunctionToolT, ResponseFormatT]): + def __init__( + self, + *, + params: ParseMessageCreateParamsBase[ResponseFormatT], + options: RequestOptions, + tools: Iterable[AnyFunctionToolT], + max_iterations: int | None = None, + compaction_control: CompactionControl | None = None, + ) -> None: + self._tools_by_name = {tool.name: tool for tool in tools} + self._params: ParseMessageCreateParamsBase[ResponseFormatT] = { + **params, + "messages": [message for message in params["messages"]], + } + helper_header = stainless_helper_header( + tools=self._tools_by_name.values(), + messages=params.get("messages"), + ) + if helper_header: + merged_headers = {**helper_header, **(options.get("extra_headers") or {})} + options = {**options, "extra_headers": merged_headers} + self._options = options + self._messages_modified = False + self._cached_tool_call_response: BetaMessageParam | None = None + self._max_iterations = max_iterations + self._iteration_count = 0 + self._compaction_control = compaction_control + + def set_messages_params( + self, + params: ParseMessageCreateParamsBase[ResponseFormatT] + | Callable[[ParseMessageCreateParamsBase[ResponseFormatT]], ParseMessageCreateParamsBase[ResponseFormatT]], + ) -> None: + """ + Update the parameters for the next API call. This invalidates any cached tool responses. + + Args: + params (ParsedMessageCreateParamsBase[ResponseFormatT] | Callable): Either new parameters or a function to mutate existing parameters + """ + if callable(params): + params = params(self._params) + self._params = params + + def append_messages(self, *messages: BetaMessageParam | ParsedBetaMessage[ResponseFormatT]) -> None: + """Add one or more messages to the conversation history. + + This invalidates the cached tool response, i.e. if tools were already called, then they will + be called again on the next loop iteration. + """ + message_params: List[BetaMessageParam] = [ + {"role": message.role, "content": message.content} if isinstance(message, BetaMessage) else message + for message in messages + ] + self._messages_modified = True + self.set_messages_params(lambda params: {**params, "messages": [*params["messages"], *message_params]}) + self._cached_tool_call_response = None + + def _should_stop(self) -> bool: + if self._max_iterations is not None and self._iteration_count >= self._max_iterations: + return True + return False + + +class BaseSyncToolRunner(BaseToolRunner[BetaRunnableTool, ResponseFormatT], Generic[RunnerItemT, ResponseFormatT], ABC): + def __init__( + self, + *, + params: ParseMessageCreateParamsBase[ResponseFormatT], + options: RequestOptions, + tools: Iterable[BetaRunnableTool], + client: Anthropic, + max_iterations: int | None = None, + compaction_control: CompactionControl | None = None, + ) -> None: + super().__init__( + params=params, + options=options, + tools=tools, + max_iterations=max_iterations, + compaction_control=compaction_control, + ) + self._client = client + + if compaction_control is not None and compaction_control.get("enabled"): + warnings.warn( + "The 'compaction_control' parameter is deprecated and will be removed in a future version. " + "Use server-side compaction instead by passing `edits=[{'type': 'compact_20260112'}]` in your " + "the params passed to `tool_runner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction", + DeprecationWarning, + stacklevel=3, + ) + + self._iterator = self.__run__() + self._last_message: ( + Callable[[], ParsedBetaMessage[ResponseFormatT]] | ParsedBetaMessage[ResponseFormatT] | None + ) = None + + def __next__(self) -> RunnerItemT: + return self._iterator.__next__() + + def __iter__(self) -> Iterator[RunnerItemT]: + for item in self._iterator: + yield item + + @abstractmethod + @contextmanager + def _handle_request(self) -> Iterator[RunnerItemT]: + raise NotImplementedError() + yield # type: ignore[unreachable] + + def _check_and_compact(self) -> bool: + """ + Check token usage and compact messages if threshold exceeded. + Returns True if compaction was performed, False otherwise. + """ + if self._compaction_control is None or not self._compaction_control["enabled"]: + return False + + message = self._get_last_message() + tokens_used = 0 + if message is not None: + total_input_tokens = ( + message.usage.input_tokens + + (message.usage.cache_creation_input_tokens or 0) + + (message.usage.cache_read_input_tokens or 0) + ) + tokens_used = total_input_tokens + message.usage.output_tokens + + threshold = self._compaction_control.get("context_token_threshold", DEFAULT_THRESHOLD) + + if tokens_used < threshold: + return False + + # Perform compaction + log.info(f"Token usage {tokens_used} has exceeded the threshold of {threshold}. Performing compaction.") + + model = self._compaction_control.get("model", self._params["model"]) + + messages = list(self._params["messages"]) + + if messages[-1]["role"] == "assistant": + # Remove tool_use blocks from the last message to avoid 400 error + # (tool_use requires tool_result, which we don't have yet) + non_tool_blocks = [ + block + for block in messages[-1]["content"] + if isinstance(block, dict) and block.get("type") != "tool_use" + ] + + if non_tool_blocks: + messages[-1]["content"] = non_tool_blocks + else: + messages.pop() + + messages = [ + *messages, + BetaMessageParam( + role="user", + content=self._compaction_control.get("summary_prompt", DEFAULT_SUMMARY_PROMPT), + ), + ] + + response = self._client.beta.messages.create( + model=model, + messages=messages, + max_tokens=self._params["max_tokens"], + extra_headers={"X-Stainless-Helper": "compaction"}, + ) + + log.info(f"Compaction complete. New token usage: {response.usage.output_tokens}") + + first_content = list(response.content)[0] + + if first_content.type != "text": + raise ValueError("Compaction response content is not of type 'text'") + + self.set_messages_params( + lambda params: { + **params, + "messages": [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": first_content.text, + } + ], + } + ], + } + ) + return True + + def __run__(self) -> Iterator[RunnerItemT]: + while not self._should_stop(): + with self._handle_request() as item: + yield item + message = self._get_last_message() + assert message is not None + + # Update container from response for programmatic tool calling support + last_assistant_message = self._get_last_assistant_message() + if last_assistant_message is not None and last_assistant_message.container is not None: + self._params["container"] = last_assistant_message.container.id + + self._iteration_count += 1 + + # If the compaction was performed, skip tool call generation this iteration + if not self._check_and_compact(): + response = self.generate_tool_call_response() + if response is None: + log.debug("Tool call was not requested, exiting from tool runner loop.") + return + + if not self._messages_modified: + self.append_messages(message, response) + + self._messages_modified = False + self._cached_tool_call_response = None + + def until_done(self) -> ParsedBetaMessage[ResponseFormatT]: + """ + Consumes the tool runner stream and returns the last message if it has not been consumed yet. + If it has, it simply returns the last message. + """ + consume_sync_iterator(self) + last_message = self._get_last_message() + assert last_message is not None + return last_message + + def generate_tool_call_response(self) -> BetaMessageParam | None: + """Generate a MessageParam by calling tool functions with any tool use blocks from the last message. + + Note the tool call response is cached, repeated calls to this method will return the same response. + + None can be returned if no tool call was applicable. + """ + if self._cached_tool_call_response is not None: + log.debug("Returning cached tool call response.") + return self._cached_tool_call_response + response = self._generate_tool_call_response() + self._cached_tool_call_response = response + return response + + def _generate_tool_call_response(self) -> BetaMessageParam | None: + content = self._get_last_assistant_message_content() + if not content: + return None + + tool_use_blocks = [block for block in content if block.type == "tool_use"] + if not tool_use_blocks: + return None + + results: list[BetaToolResultBlockParam] = [] + + for tool_use in tool_use_blocks: + tool = self._tools_by_name.get(tool_use.name) + if tool is None: + warnings.warn( + f"Tool '{tool_use.name}' not found in tool runner. " + f"Available tools: {list(self._tools_by_name.keys())}. " + f"If using a raw tool definition, handle the tool call manually and use `append_messages()` to add the result. " + f"Otherwise, pass the tool using `beta_tool(func)` or a `@beta_tool` decorated function.", + UserWarning, + stacklevel=3, + ) + results.append( + { + "type": "tool_result", + "tool_use_id": tool_use.id, + "content": f"Error: Tool '{tool_use.name}' not found", + "is_error": True, + } + ) + continue + + try: + result = tool.call(tool_use.input) + results.append({"type": "tool_result", "tool_use_id": tool_use.id, "content": result}) + except ToolError as exc: + results.append( + { + "type": "tool_result", + "tool_use_id": tool_use.id, + "content": exc.content, + "is_error": True, + } + ) + except Exception as exc: + log.exception(f"Error occurred while calling tool: {tool.name}", exc_info=exc) + results.append( + { + "type": "tool_result", + "tool_use_id": tool_use.id, + "content": repr(exc), + "is_error": True, + } + ) + + return {"role": "user", "content": results} + + def _get_last_message(self) -> ParsedBetaMessage[ResponseFormatT] | None: + if callable(self._last_message): + return self._last_message() + return self._last_message + + def _get_last_assistant_message(self) -> ParsedBetaMessage[ResponseFormatT] | None: + last_message = self._get_last_message() + if last_message is None or last_message.role != "assistant" or not last_message.content: + return None + + return last_message + + def _get_last_assistant_message_content(self) -> list[ParsedBetaContentBlock[ResponseFormatT]] | None: + last_assistant_message = self._get_last_assistant_message() + if last_assistant_message is None: + return None + + return last_assistant_message.content + + +class BetaToolRunner(BaseSyncToolRunner[ParsedBetaMessage[ResponseFormatT], ResponseFormatT]): + @override + @contextmanager + def _handle_request(self) -> Iterator[ParsedBetaMessage[ResponseFormatT]]: + message = self._client.beta.messages.parse(**self._params, **self._options) + self._last_message = message + yield message + + +class BetaStreamingToolRunner(BaseSyncToolRunner[BetaMessageStream[ResponseFormatT], ResponseFormatT]): + @override + @contextmanager + def _handle_request(self) -> Iterator[BetaMessageStream[ResponseFormatT]]: + with self._client.beta.messages.stream(**self._params, **self._options) as stream: + self._last_message = stream.get_final_message + yield stream + + +class BaseAsyncToolRunner( + BaseToolRunner[BetaAsyncRunnableTool, ResponseFormatT], Generic[RunnerItemT, ResponseFormatT], ABC +): + def __init__( + self, + *, + params: ParseMessageCreateParamsBase[ResponseFormatT], + options: RequestOptions, + tools: Iterable[BetaAsyncRunnableTool], + client: AsyncAnthropic, + max_iterations: int | None = None, + compaction_control: CompactionControl | None = None, + ) -> None: + super().__init__( + params=params, + options=options, + tools=tools, + max_iterations=max_iterations, + compaction_control=compaction_control, + ) + self._client = client + + if compaction_control is not None and compaction_control.get("enabled"): + warnings.warn( + "The 'compaction_control' parameter is deprecated and will be removed in a future version. " + "Use server-side compaction instead by passing `edits=[{'type': 'compact_20260112'}]` in your " + "the params passed to `tool_runner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction", + DeprecationWarning, + stacklevel=3, + ) + + self._iterator = self.__run__() + self._last_message: ( + Callable[[], Coroutine[None, None, ParsedBetaMessage[ResponseFormatT]]] + | ParsedBetaMessage[ResponseFormatT] + | None + ) = None + + async def __anext__(self) -> RunnerItemT: + return await self._iterator.__anext__() + + async def __aiter__(self) -> AsyncIterator[RunnerItemT]: + async for item in self._iterator: + yield item + + @abstractmethod + @asynccontextmanager + async def _handle_request(self) -> AsyncIterator[RunnerItemT]: + raise NotImplementedError() + yield # type: ignore[unreachable] + + async def _check_and_compact(self) -> bool: + """ + Check token usage and compact messages if threshold exceeded. + Returns True if compaction was performed, False otherwise. + """ + if self._compaction_control is None or not self._compaction_control["enabled"]: + return False + + message = await self._get_last_message() + tokens_used = 0 + if message is not None: + total_input_tokens = ( + message.usage.input_tokens + + (message.usage.cache_creation_input_tokens or 0) + + (message.usage.cache_read_input_tokens or 0) + ) + tokens_used = total_input_tokens + message.usage.output_tokens + + threshold = self._compaction_control.get("context_token_threshold", DEFAULT_THRESHOLD) + + if tokens_used < threshold: + return False + + # Perform compaction + log.info(f"Token usage {tokens_used} has exceeded the threshold of {threshold}. Performing compaction.") + + model = self._compaction_control.get("model", self._params["model"]) + + messages = list(self._params["messages"]) + + if messages[-1]["role"] == "assistant": + # Remove tool_use blocks from the last message to avoid 400 error + # (tool_use requires tool_result, which we don't have yet) + non_tool_blocks = [ + block + for block in messages[-1]["content"] + if isinstance(block, dict) and block.get("type") != "tool_use" + ] + + if non_tool_blocks: + messages[-1]["content"] = non_tool_blocks + else: + messages.pop() + + messages = [ + *messages, + BetaMessageParam( + role="user", + content=self._compaction_control.get("summary_prompt", DEFAULT_SUMMARY_PROMPT), + ), + ] + + response = await self._client.beta.messages.create( + model=model, + messages=messages, + max_tokens=self._params["max_tokens"], + extra_headers={"X-Stainless-Helper": "compaction"}, + ) + + log.info(f"Compaction complete. New token usage: {response.usage.output_tokens}") + + first_content = list(response.content)[0] + + if first_content.type != "text": + raise ValueError("Compaction response content is not of type 'text'") + + self.set_messages_params( + lambda params: { + **params, + "messages": [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": first_content.text, + } + ], + } + ], + } + ) + return True + + async def __run__(self) -> AsyncIterator[RunnerItemT]: + while not self._should_stop(): + async with self._handle_request() as item: + yield item + message = await self._get_last_message() + assert message is not None + + # Update container from response for programmatic tool calling support + last_assistant_message = await self._get_last_assistant_message() + if last_assistant_message is not None and last_assistant_message.container is not None: + self._params["container"] = last_assistant_message.container.id + + self._iteration_count += 1 + + # If the compaction was performed, skip tool call generation this iteration + if not await self._check_and_compact(): + response = await self.generate_tool_call_response() + if response is None: + log.debug("Tool call was not requested, exiting from tool runner loop.") + return + + if not self._messages_modified: + self.append_messages(message, response) + + self._messages_modified = False + self._cached_tool_call_response = None + + async def until_done(self) -> ParsedBetaMessage[ResponseFormatT]: + """ + Consumes the tool runner stream and returns the last message if it has not been consumed yet. + If it has, it simply returns the last message. + """ + await consume_async_iterator(self) + last_message = await self._get_last_message() + assert last_message is not None + return last_message + + async def generate_tool_call_response(self) -> BetaMessageParam | None: + """Generate a MessageParam by calling tool functions with any tool use blocks from the last message. + + Note the tool call response is cached, repeated calls to this method will return the same response. + + None can be returned if no tool call was applicable. + """ + if self._cached_tool_call_response is not None: + log.debug("Returning cached tool call response.") + return self._cached_tool_call_response + + response = await self._generate_tool_call_response() + self._cached_tool_call_response = response + return response + + async def _get_last_message(self) -> ParsedBetaMessage[ResponseFormatT] | None: + if callable(self._last_message): + return await self._last_message() + return self._last_message + + async def _get_last_assistant_message(self) -> ParsedBetaMessage[ResponseFormatT] | None: + last_message = await self._get_last_message() + if last_message is None or last_message.role != "assistant" or not last_message.content: + return None + + return last_message + + async def _get_last_assistant_message_content(self) -> list[ParsedBetaContentBlock[ResponseFormatT]] | None: + last_assistant_message = await self._get_last_assistant_message() + if last_assistant_message is None: + return None + + return last_assistant_message.content + + async def _generate_tool_call_response(self) -> BetaMessageParam | None: + content = await self._get_last_assistant_message_content() + if not content: + return None + + tool_use_blocks = [block for block in content if block.type == "tool_use"] + if not tool_use_blocks: + return None + + results: list[BetaToolResultBlockParam] = [] + + for tool_use in tool_use_blocks: + tool = self._tools_by_name.get(tool_use.name) + if tool is None: + warnings.warn( + f"Tool '{tool_use.name}' not found in tool runner. " + f"Available tools: {list(self._tools_by_name.keys())}. " + f"If using a raw tool definition, handle the tool call manually and use `append_messages()` to add the result. " + f"Otherwise, pass the tool using `beta_async_tool(func)` or a `@beta_async_tool` decorated function.", + UserWarning, + stacklevel=3, + ) + results.append( + { + "type": "tool_result", + "tool_use_id": tool_use.id, + "content": f"Error: Tool '{tool_use.name}' not found", + "is_error": True, + } + ) + continue + + try: + result = await tool.call(tool_use.input) + results.append({"type": "tool_result", "tool_use_id": tool_use.id, "content": result}) + except ToolError as exc: + results.append( + { + "type": "tool_result", + "tool_use_id": tool_use.id, + "content": exc.content, + "is_error": True, + } + ) + except Exception as exc: + log.exception(f"Error occurred while calling tool: {tool.name}", exc_info=exc) + results.append( + { + "type": "tool_result", + "tool_use_id": tool_use.id, + "content": repr(exc), + "is_error": True, + } + ) + + return {"role": "user", "content": results} + + +class BetaAsyncToolRunner(BaseAsyncToolRunner[ParsedBetaMessage[ResponseFormatT], ResponseFormatT]): + @override + @asynccontextmanager + async def _handle_request(self) -> AsyncIterator[ParsedBetaMessage[ResponseFormatT]]: + message = await self._client.beta.messages.parse(**self._params, **self._options) + self._last_message = message + yield message + + +class BetaAsyncStreamingToolRunner(BaseAsyncToolRunner[BetaAsyncMessageStream[ResponseFormatT], ResponseFormatT]): + @override + @asynccontextmanager + async def _handle_request(self) -> AsyncIterator[BetaAsyncMessageStream[ResponseFormatT]]: + async with self._client.beta.messages.stream(**self._params, **self._options) as stream: + self._last_message = stream.get_final_message + yield stream diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/mcp.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..219f5cca9a678846d13a563fbf1a33e79a9e5b30 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/tools/mcp.py @@ -0,0 +1,442 @@ +"""Helpers for integrating MCP (Model Context Protocol) SDK types with the Anthropic SDK. + +These helpers reduce boilerplate when converting between MCP types and Anthropic API types. + +Usage:: + + from anthropic.lib.tools.mcp import mcp_tool, async_mcp_tool, mcp_message + +This module requires the ``mcp`` package to be installed. +""" +# pyright: reportUnknownArgumentType=false, reportUnknownMemberType=false, reportUnknownVariableType=false, reportMissingImports=false, reportUnknownParameterType=false + +from __future__ import annotations + +import json +import base64 +from typing import Any, Iterable +from urllib.parse import urlparse +from typing_extensions import Literal + +try: + from mcp.types import ( # type: ignore[import-not-found] + Tool, + TextContent, + ContentBlock, + ImageContent, + PromptMessage, + CallToolResult, + EmbeddedResource, + ReadResourceResult, + BlobResourceContents, + TextResourceContents, + ) + from mcp.client.session import ClientSession # type: ignore[import-not-found] +except ImportError as _err: + raise ImportError( + "The `mcp` package is required to use MCP helpers. Install it with: pip install anthropic[mcp]. Requires Python 3.10 or higher." + ) from _err + +from ...types.beta import ( + BetaBase64PDFSourceParam, + BetaPlainTextSourceParam, + BetaBase64ImageSourceParam, + BetaCacheControlEphemeralParam, +) +from ._beta_functions import ( + ToolError, + BetaFunctionTool, + BetaAsyncFunctionTool, + BetaFunctionToolResultType, + beta_tool, + beta_async_tool, +) +from .._stainless_helpers import tag_helper +from ...types.beta.beta_tool_result_block_param import Content as BetaContent + +__all__ = [ + "mcp_tool", + "async_mcp_tool", + "mcp_content", + "mcp_message", + "mcp_resource_to_content", + "mcp_resource_to_file", + "UnsupportedMCPValueError", +] + +# ----------------------------------------------------------------------- +# Supported MIME types +# ----------------------------------------------------------------------- + +_SUPPORTED_IMAGE_TYPES = frozenset({"image/jpeg", "image/png", "image/gif", "image/webp"}) + + +class _TaggedDict(dict): # type: ignore[type-arg] + """A dict subclass that can carry a ``_stainless_helper`` attribute. + + Behaves identically to a regular dict for serialization and isinstance checks, + but allows attaching tracking metadata that won't appear in JSON output. + """ + + +class _TaggedTuple(tuple): # type: ignore[type-arg] + """A tuple subclass that can carry a ``_stainless_helper`` attribute.""" + + +def _is_supported_image_type(mime_type: str) -> bool: + return mime_type in _SUPPORTED_IMAGE_TYPES + + +def _is_supported_resource_mime_type(mime_type: str | None) -> bool: + return ( + mime_type is None + or mime_type.startswith("text/") + or mime_type == "application/pdf" + or _is_supported_image_type(mime_type) + ) + + +# ----------------------------------------------------------------------- +# Errors +# ----------------------------------------------------------------------- + + +class UnsupportedMCPValueError(Exception): + """Raised when an MCP value cannot be converted to a format supported by the Claude API.""" + + +# ----------------------------------------------------------------------- +# Content conversion +# ----------------------------------------------------------------------- + + +def mcp_content( + content: ContentBlock, + *, + cache_control: BetaCacheControlEphemeralParam | None = None, +) -> BetaContent: + """Convert a single MCP content block to an Anthropic content block. + + Handles text, image, and embedded resource content types. + Raises :class:`UnsupportedMCPValueError` for audio and resource_link types. + """ + if isinstance(content, TextContent): + block = _TaggedDict({"type": "text", "text": content.text}) + if cache_control is not None: + block["cache_control"] = cache_control + tag_helper(block, "mcp_content") + return block # type: ignore[return-value] + + if isinstance(content, ImageContent): + if not _is_supported_image_type(content.mimeType): + raise UnsupportedMCPValueError(f"Unsupported image MIME type: {content.mimeType}") + image_block = _TaggedDict( + { + "type": "image", + "source": BetaBase64ImageSourceParam( + type="base64", + data=content.data, + media_type=content.mimeType, # type: ignore[typeddict-item] + ), + } + ) + if cache_control is not None: + image_block["cache_control"] = cache_control + tag_helper(image_block, "mcp_content") + return image_block # type: ignore[return-value] + + if isinstance(content, EmbeddedResource): + return _resource_contents_to_block(content.resource, cache_control=cache_control) + + # audio, resource_link, or unknown + content_type = getattr(content, "type", type(content).__name__) + raise UnsupportedMCPValueError(f"Unsupported MCP content type: {content_type}") + + +def _resource_contents_to_block( + resource: TextResourceContents | BlobResourceContents, + *, + cache_control: BetaCacheControlEphemeralParam | None = None, +) -> BetaContent: + """Convert MCP resource contents to an Anthropic content block.""" + mime_type = resource.mimeType + + # Images + if mime_type is not None and _is_supported_image_type(mime_type): + if not isinstance(resource, BlobResourceContents): + raise UnsupportedMCPValueError(f"Image resource must have blob data, not text. URI: {resource.uri}") + image_block = _TaggedDict( + { + "type": "image", + "source": BetaBase64ImageSourceParam( + type="base64", + data=resource.blob, + media_type=mime_type, # type: ignore[typeddict-item] + ), + } + ) + if cache_control is not None: + image_block["cache_control"] = cache_control + tag_helper(image_block, "mcp_resource_to_content") + return image_block # type: ignore[return-value] + + # PDFs + if mime_type == "application/pdf": + if not isinstance(resource, BlobResourceContents): + raise UnsupportedMCPValueError(f"PDF resource must have blob data, not text. URI: {resource.uri}") + pdf_block = _TaggedDict( + { + "type": "document", + "source": BetaBase64PDFSourceParam( + type="base64", + data=resource.blob, + media_type="application/pdf", + ), + } + ) + if cache_control is not None: + pdf_block["cache_control"] = cache_control + tag_helper(pdf_block, "mcp_resource_to_content") + return pdf_block # type: ignore[return-value] + + # Text (text/*, or no MIME type) + if mime_type is None or mime_type.startswith("text/"): + if isinstance(resource, TextResourceContents): + data = resource.text + else: + data = base64.b64decode(resource.blob).decode("utf-8") + text_block = _TaggedDict( + { + "type": "document", + "source": BetaPlainTextSourceParam( + type="text", + data=data, + media_type="text/plain", + ), + } + ) + if cache_control is not None: + text_block["cache_control"] = cache_control + tag_helper(text_block, "mcp_resource_to_content") + return text_block # type: ignore[return-value] + + raise UnsupportedMCPValueError(f'Unsupported MIME type "{mime_type}" for resource: {resource.uri}') + + +# ----------------------------------------------------------------------- +# Message conversion +# ----------------------------------------------------------------------- + + +def mcp_message( + message: PromptMessage, + *, + cache_control: BetaCacheControlEphemeralParam | None = None, +) -> dict[str, Any]: + """Convert an MCP prompt message to an Anthropic ``BetaMessageParam``.""" + result = _TaggedDict( + { + "role": message.role, + "content": [mcp_content(message.content, cache_control=cache_control)], + } + ) + tag_helper(result, "mcp_message") + return result + + +# ----------------------------------------------------------------------- +# Resource conversion +# ----------------------------------------------------------------------- + + +def mcp_resource_to_content( + result: ReadResourceResult, + *, + cache_control: BetaCacheControlEphemeralParam | None = None, +) -> BetaContent: + """Convert MCP resource contents to an Anthropic content block. + + Finds the first resource with a supported MIME type from the result's + ``contents`` list. + """ + if not result.contents: + raise UnsupportedMCPValueError("Resource contents array must contain at least one item") + + supported = next( + (c for c in result.contents if _is_supported_resource_mime_type(c.mimeType)), + None, + ) + if supported is None: + mime_types = [c.mimeType for c in result.contents if c.mimeType is not None] + raise UnsupportedMCPValueError( + f"No supported MIME type found in resource contents. Available: {', '.join(mime_types)}" + ) + + return _resource_contents_to_block(supported, cache_control=cache_control) + + +def mcp_resource_to_file( + result: ReadResourceResult, +) -> tuple[str | None, bytes, str | None]: + """Convert MCP resource contents to a file tuple for ``files.upload()``. + + Returns a ``(filename, content_bytes, mime_type)`` tuple compatible with + the SDK's ``FileTypes``. + """ + if not result.contents: + raise UnsupportedMCPValueError("Resource contents array must contain at least one item") + + resource = result.contents[0] + uri_str = str(resource.uri) + + # Extract filename from URI + path = urlparse(uri_str).path + name = path.rsplit("/", 1)[-1] if path else None + + # Get bytes + if isinstance(resource, BlobResourceContents): + content_bytes = base64.b64decode(resource.blob) + else: + content_bytes = resource.text.encode("utf-8") + + file_tuple = _TaggedTuple((name, content_bytes, resource.mimeType)) + tag_helper(file_tuple, "mcp_resource_to_file") + return file_tuple + + +# ----------------------------------------------------------------------- +# Tool result conversion (used by tool call handlers) +# ----------------------------------------------------------------------- + + +def _convert_tool_result(result: CallToolResult) -> BetaFunctionToolResultType: + """Convert MCP ``CallToolResult`` to a value suitable for returning from ``call()``.""" + if result.isError: + raise ToolError([mcp_content(item) for item in result.content]) + + # If content is empty but structuredContent is present, JSON-encode it + if not result.content and result.structuredContent is not None: + return json.dumps(result.structuredContent) + + return [mcp_content(item) for item in result.content] + + +# ----------------------------------------------------------------------- +# Public factory functions +# ----------------------------------------------------------------------- + + +def mcp_tool( + tool: Tool, + client: ClientSession, + *, + cache_control: BetaCacheControlEphemeralParam | None = None, + defer_loading: bool | None = None, + allowed_callers: list[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] | None = None, + eager_input_streaming: bool | None = None, + input_examples: Iterable[dict[str, object]] | None = None, + strict: bool | None = None, +) -> BetaFunctionTool[Any]: + """Convert an MCP tool to a sync runnable tool for ``tool_runner()``. + + Example:: + + from anthropic.lib.tools.mcp import mcp_tool + + tools_result = await mcp_client.list_tools() + runner = client.beta.messages.tool_runner( + model="claude-sonnet-4-20250514", + max_tokens=1024, + tools=[mcp_tool(t, mcp_client) for t in tools_result.tools], + messages=[{"role": "user", "content": "Use the available tools"}], + ) + + Args: + tool: An MCP tool definition from ``client.list_tools()``. + client: The MCP ``ClientSession`` used to call the tool. + cache_control: Cache control configuration. + defer_loading: If true, tool will not be included in initial system prompt. + allowed_callers: Which callers may use this tool. + eager_input_streaming: Enable eager input streaming for this tool. + input_examples: Example inputs for the tool. + strict: When true, guarantees schema validation on tool names and inputs. + """ + import anyio.from_thread + + tool_name = tool.name + + def call_mcp(**kwargs: Any) -> BetaFunctionToolResultType: + result = anyio.from_thread.run(client.call_tool, tool_name, kwargs) + return _convert_tool_result(result) + + result = beta_tool( + call_mcp, + name=tool_name, + description=tool.description, + input_schema=tool.inputSchema, + cache_control=cache_control, + defer_loading=defer_loading, + allowed_callers=allowed_callers, + eager_input_streaming=eager_input_streaming, + input_examples=input_examples, + strict=strict, + ) + tag_helper(result, "mcp_tool") + return result + + +def async_mcp_tool( + tool: Tool, + client: ClientSession, + *, + cache_control: BetaCacheControlEphemeralParam | None = None, + defer_loading: bool | None = None, + allowed_callers: list[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] | None = None, + eager_input_streaming: bool | None = None, + input_examples: Iterable[dict[str, object]] | None = None, + strict: bool | None = None, +) -> BetaAsyncFunctionTool[Any]: + """Convert an MCP tool to an async runnable tool for ``tool_runner()``. + + Example:: + + from anthropic.lib.tools.mcp import async_mcp_tool + + tools_result = await mcp_client.list_tools() + runner = await client.beta.messages.tool_runner( + model="claude-sonnet-4-20250514", + max_tokens=1024, + tools=[async_mcp_tool(t, mcp_client) for t in tools_result.tools], + messages=[{"role": "user", "content": "Use the available tools"}], + ) + + Args: + tool: An MCP tool definition from ``client.list_tools()``. + client: The MCP ``ClientSession`` used to call the tool. + cache_control: Cache control configuration. + defer_loading: If true, tool will not be included in initial system prompt. + allowed_callers: Which callers may use this tool. + eager_input_streaming: Enable eager input streaming for this tool. + input_examples: Example inputs for the tool. + strict: When true, guarantees schema validation on tool names and inputs. + """ + tool_name = tool.name + + async def call_mcp(**kwargs: Any) -> BetaFunctionToolResultType: + result = await client.call_tool(name=tool_name, arguments=kwargs) + return _convert_tool_result(result) + + result = beta_async_tool( + call_mcp, + name=tool_name, + description=tool.description, + input_schema=tool.inputSchema, + cache_control=cache_control, + defer_loading=defer_loading, + allowed_callers=allowed_callers, + eager_input_streaming=eager_input_streaming, + input_examples=input_examples, + strict=strict, + ) + tag_helper(result, "mcp_tool") + return result diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/__init__.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..45b6301e4c8aa5daf9a5b5a6d6b0a436b38ab822 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/__init__.py @@ -0,0 +1 @@ +from ._client import AnthropicVertex as AnthropicVertex, AsyncAnthropicVertex as AsyncAnthropicVertex diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/__pycache__/__init__.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99910d77655a5fe8c71c24b489c3a54f14a8f6d2 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/__pycache__/__init__.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/__pycache__/_auth.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/__pycache__/_auth.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e4b25e4cf52f41b03d7fb4978218ebb8fc03819 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/__pycache__/_auth.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/__pycache__/_beta.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/__pycache__/_beta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1226beb109237bdb50f9b51a108ce6c6e9a7cd4 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/__pycache__/_beta.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/__pycache__/_beta_messages.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/__pycache__/_beta_messages.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4896294e1f336e98d1104e3e3cf627948e268e3a Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/__pycache__/_beta_messages.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/__pycache__/_client.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/__pycache__/_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..837099f8bfab6dd9e0b838a1024e123d35ba44cc Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/__pycache__/_client.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/_auth.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..7502fbf93ed2f67c131a59940ca46644226c35bd --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/_auth.py @@ -0,0 +1,44 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, cast + +from .._extras import google_auth + +if TYPE_CHECKING: + from google.auth.credentials import Credentials # type: ignore[import-untyped] + +# pyright: reportMissingTypeStubs=false, reportUnknownVariableType=false, reportUnknownMemberType=false, reportUnknownArgumentType=false +# google libraries don't provide types :/ + +# Note: these functions are blocking as they make HTTP requests, the async +# client runs these functions in a separate thread to ensure they do not +# cause synchronous blocking issues. + + +def load_auth(*, project_id: str | None) -> tuple[Credentials, str]: + try: + from google.auth.transport.requests import Request # type: ignore[import-untyped] + except ModuleNotFoundError as err: + raise RuntimeError( + f"Could not import google.auth, you need to install the SDK with `pip install anthropic[vertex]`" + ) from err + + credentials, loaded_project_id = google_auth.default( + scopes=["https://www.googleapis.com/auth/cloud-platform"], + ) + credentials = cast(Any, credentials) + credentials.refresh(Request()) + + if not project_id: + project_id = loaded_project_id + + if not project_id: + raise ValueError("Could not resolve project_id") + + return credentials, project_id + + +def refresh_auth(credentials: Credentials) -> None: + from google.auth.transport.requests import Request # type: ignore[import-untyped] + + credentials.refresh(Request()) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/_beta.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/_beta.py new file mode 100644 index 0000000000000000000000000000000000000000..f2a91b428f73abf787e4943c004229953080f8eb --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/_beta.py @@ -0,0 +1,102 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ._beta_messages import ( + Messages, + AsyncMessages, + MessagesWithRawResponse, + AsyncMessagesWithRawResponse, + MessagesWithStreamingResponse, + AsyncMessagesWithStreamingResponse, +) + +__all__ = ["Beta", "AsyncBeta"] + + +class Beta(SyncAPIResource): + @cached_property + def messages(self) -> Messages: + return Messages(self._client) + + @cached_property + def with_raw_response(self) -> BetaWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers + """ + return BetaWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> BetaWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response + """ + return BetaWithStreamingResponse(self) + + +class AsyncBeta(AsyncAPIResource): + @cached_property + def messages(self) -> AsyncMessages: + return AsyncMessages(self._client) + + @cached_property + def with_raw_response(self) -> AsyncBetaWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers + """ + return AsyncBetaWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncBetaWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response + """ + return AsyncBetaWithStreamingResponse(self) + + +class BetaWithRawResponse: + def __init__(self, beta: Beta) -> None: + self._beta = beta + + @cached_property + def messages(self) -> MessagesWithRawResponse: + return MessagesWithRawResponse(self._beta.messages) + + +class AsyncBetaWithRawResponse: + def __init__(self, beta: AsyncBeta) -> None: + self._beta = beta + + @cached_property + def messages(self) -> AsyncMessagesWithRawResponse: + return AsyncMessagesWithRawResponse(self._beta.messages) + + +class BetaWithStreamingResponse: + def __init__(self, beta: Beta) -> None: + self._beta = beta + + @cached_property + def messages(self) -> MessagesWithStreamingResponse: + return MessagesWithStreamingResponse(self._beta.messages) + + +class AsyncBetaWithStreamingResponse: + def __init__(self, beta: AsyncBeta) -> None: + self._beta = beta + + @cached_property + def messages(self) -> AsyncMessagesWithStreamingResponse: + return AsyncMessagesWithStreamingResponse(self._beta.messages) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/_beta_messages.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/_beta_messages.py new file mode 100644 index 0000000000000000000000000000000000000000..72b97b0494536b6984130cb16eada58956ac4988 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/_beta_messages.py @@ -0,0 +1,97 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from ... import _legacy_response +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ...resources.beta import Messages as FirstPartyMessagesAPI, AsyncMessages as FirstPartyAsyncMessagesAPI + +__all__ = ["Messages", "AsyncMessages"] + + +class Messages(SyncAPIResource): + create = FirstPartyMessagesAPI.create + stream = FirstPartyMessagesAPI.stream + count_tokens = FirstPartyMessagesAPI.count_tokens + + @cached_property + def with_raw_response(self) -> MessagesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers + """ + return MessagesWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> MessagesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response + """ + return MessagesWithStreamingResponse(self) + + +class AsyncMessages(AsyncAPIResource): + create = FirstPartyAsyncMessagesAPI.create + stream = FirstPartyAsyncMessagesAPI.stream + count_tokens = FirstPartyAsyncMessagesAPI.count_tokens + + @cached_property + def with_raw_response(self) -> AsyncMessagesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers + """ + return AsyncMessagesWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncMessagesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response + """ + return AsyncMessagesWithStreamingResponse(self) + + +class MessagesWithRawResponse: + def __init__(self, messages: Messages) -> None: + self._messages = messages + + self.create = _legacy_response.to_raw_response_wrapper( + messages.create, + ) + + +class AsyncMessagesWithRawResponse: + def __init__(self, messages: AsyncMessages) -> None: + self._messages = messages + + self.create = _legacy_response.async_to_raw_response_wrapper( + messages.create, + ) + + +class MessagesWithStreamingResponse: + def __init__(self, messages: Messages) -> None: + self._messages = messages + + self.create = to_streamed_response_wrapper( + messages.create, + ) + + +class AsyncMessagesWithStreamingResponse: + def __init__(self, messages: AsyncMessages) -> None: + self._messages = messages + + self.create = async_to_streamed_response_wrapper( + messages.create, + ) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/_client.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/_client.py new file mode 100644 index 0000000000000000000000000000000000000000..516931815f354337e4b72a2a9eab73349fcbaa04 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/lib/vertex/_client.py @@ -0,0 +1,420 @@ +from __future__ import annotations + +import os +from typing import TYPE_CHECKING, Any, Union, Mapping, TypeVar +from typing_extensions import Self, override + +import httpx + +from ... import _exceptions +from ._auth import load_auth, refresh_auth +from ._beta import Beta, AsyncBeta +from ..._types import NOT_GIVEN, NotGiven +from ..._utils import is_dict, asyncify, is_given +from ..._compat import model_copy, typed_cached_property +from ..._models import FinalRequestOptions +from ..._version import __version__ +from ..._streaming import Stream, AsyncStream +from ..._exceptions import AnthropicError, APIStatusError +from ..._base_client import ( + DEFAULT_MAX_RETRIES, + BaseClient, + SyncAPIClient, + AsyncAPIClient, +) +from ...resources.messages import Messages, AsyncMessages + +if TYPE_CHECKING: + from google.auth.credentials import Credentials as GoogleCredentials # type: ignore + + +DEFAULT_VERSION = "vertex-2023-10-16" + +_HttpxClientT = TypeVar("_HttpxClientT", bound=Union[httpx.Client, httpx.AsyncClient]) +_DefaultStreamT = TypeVar("_DefaultStreamT", bound=Union[Stream[Any], AsyncStream[Any]]) + + +class BaseVertexClient(BaseClient[_HttpxClientT, _DefaultStreamT]): + @typed_cached_property + def region(self) -> str: + raise RuntimeError("region not set") + + @typed_cached_property + def project_id(self) -> str | None: + project_id = os.environ.get("ANTHROPIC_VERTEX_PROJECT_ID") + if project_id: + return project_id + + return None + + @override + def _make_status_error( + self, + err_msg: str, + *, + body: object, + response: httpx.Response, + ) -> APIStatusError: + if response.status_code == 400: + return _exceptions.BadRequestError(err_msg, response=response, body=body) + + if response.status_code == 401: + return _exceptions.AuthenticationError(err_msg, response=response, body=body) + + if response.status_code == 403: + return _exceptions.PermissionDeniedError(err_msg, response=response, body=body) + + if response.status_code == 404: + return _exceptions.NotFoundError(err_msg, response=response, body=body) + + if response.status_code == 409: + return _exceptions.ConflictError(err_msg, response=response, body=body) + + if response.status_code == 422: + return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body) + + if response.status_code == 429: + return _exceptions.RateLimitError(err_msg, response=response, body=body) + + if response.status_code == 503: + return _exceptions.ServiceUnavailableError(err_msg, response=response, body=body) + + if response.status_code == 504: + return _exceptions.DeadlineExceededError(err_msg, response=response, body=body) + + if response.status_code >= 500: + return _exceptions.InternalServerError(err_msg, response=response, body=body) + return APIStatusError(err_msg, response=response, body=body) + + +class AnthropicVertex(BaseVertexClient[httpx.Client, Stream[Any]], SyncAPIClient): + messages: Messages + beta: Beta + + def __init__( + self, + *, + region: str | NotGiven = NOT_GIVEN, + project_id: str | NotGiven = NOT_GIVEN, + access_token: str | None = None, + credentials: GoogleCredentials | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + # Configure a custom httpx client. See the [httpx documentation](https://www.python-httpx.org/api/#client) for more details. + http_client: httpx.Client | None = None, + _strict_response_validation: bool = False, + ) -> None: + if not is_given(region): + region = os.environ.get("CLOUD_ML_REGION", NOT_GIVEN) + if not is_given(region): + raise ValueError( + "No region was given. The client should be instantiated with the `region` argument or the `CLOUD_ML_REGION` environment variable should be set." + ) + + if base_url is None: + base_url = os.environ.get("ANTHROPIC_VERTEX_BASE_URL") + if base_url is None: + if region == "global": + base_url = "https://aiplatform.googleapis.com/v1" + elif region == "us": + base_url = "https://aiplatform.us.rep.googleapis.com/v1" + elif region == "eu": + base_url = "https://aiplatform.eu.rep.googleapis.com/v1" + else: + base_url = f"https://{region}-aiplatform.googleapis.com/v1" + + super().__init__( + version=__version__, + base_url=base_url, + timeout=timeout, + max_retries=max_retries, + custom_headers=default_headers, + custom_query=default_query, + http_client=http_client, + _strict_response_validation=_strict_response_validation, + ) + + if is_given(project_id): + self.project_id = project_id + + self.region = region + self.access_token = access_token + self.credentials = credentials + + self.messages = Messages(self) + self.beta = Beta(self) + + @override + def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions: + return _prepare_options(options, project_id=self.project_id, region=self.region) + + @override + def _prepare_request(self, request: httpx.Request) -> None: + if request.headers.get("Authorization"): + # already authenticated, nothing for us to do + return + + request.headers["Authorization"] = f"Bearer {self._ensure_access_token()}" + + def _ensure_access_token(self) -> str: + if self.access_token is not None: + return self.access_token + + if not self.credentials: + self.credentials, project_id = load_auth(project_id=self.project_id) + if not self.project_id: + self.project_id = project_id + + if self.credentials.expired or not self.credentials.token: + refresh_auth(self.credentials) + + if not self.credentials.token: + raise RuntimeError("Could not resolve API token from the environment") + + assert isinstance(self.credentials.token, str) + return self.credentials.token + + def copy( + self, + *, + region: str | NotGiven = NOT_GIVEN, + project_id: str | NotGiven = NOT_GIVEN, + access_token: str | None = None, + credentials: GoogleCredentials | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + http_client: httpx.Client | None = None, + max_retries: int | NotGiven = NOT_GIVEN, + default_headers: Mapping[str, str] | None = None, + set_default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + set_default_query: Mapping[str, object] | None = None, + _extra_kwargs: Mapping[str, Any] = {}, + ) -> Self: + """ + Create a new client instance re-using the same options given to the current client with optional overriding. + """ + if default_headers is not None and set_default_headers is not None: + raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive") + + if default_query is not None and set_default_query is not None: + raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive") + + headers = self._custom_headers + if default_headers is not None: + headers = {**headers, **default_headers} + elif set_default_headers is not None: + headers = set_default_headers + + params = self._custom_query + if default_query is not None: + params = {**params, **default_query} + elif set_default_query is not None: + params = set_default_query + + http_client = http_client or self._client + + return self.__class__( + region=region if is_given(region) else self.region, + project_id=project_id if is_given(project_id) else self.project_id or NOT_GIVEN, + access_token=access_token or self.access_token, + credentials=credentials or self.credentials, + base_url=base_url or self.base_url, + timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, + http_client=http_client, + max_retries=max_retries if is_given(max_retries) else self.max_retries, + default_headers=headers, + default_query=params, + **_extra_kwargs, + ) + + # Alias for `copy` for nicer inline usage, e.g. + # client.with_options(timeout=10).foo.create(...) + with_options = copy + + +class AsyncAnthropicVertex(BaseVertexClient[httpx.AsyncClient, AsyncStream[Any]], AsyncAPIClient): + messages: AsyncMessages + beta: AsyncBeta + + def __init__( + self, + *, + region: str | NotGiven = NOT_GIVEN, + project_id: str | NotGiven = NOT_GIVEN, + access_token: str | None = None, + credentials: GoogleCredentials | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + # Configure a custom httpx client. See the [httpx documentation](https://www.python-httpx.org/api/#client) for more details. + http_client: httpx.AsyncClient | None = None, + _strict_response_validation: bool = False, + ) -> None: + if not is_given(region): + region = os.environ.get("CLOUD_ML_REGION", NOT_GIVEN) + if not is_given(region): + raise ValueError( + "No region was given. The client should be instantiated with the `region` argument or the `CLOUD_ML_REGION` environment variable should be set." + ) + + if base_url is None: + base_url = os.environ.get("ANTHROPIC_VERTEX_BASE_URL") + if base_url is None: + if region == "global": + base_url = "https://aiplatform.googleapis.com/v1" + elif region == "us": + base_url = "https://aiplatform.us.rep.googleapis.com/v1" + elif region == "eu": + base_url = "https://aiplatform.eu.rep.googleapis.com/v1" + else: + base_url = f"https://{region}-aiplatform.googleapis.com/v1" + + super().__init__( + version=__version__, + base_url=base_url, + timeout=timeout, + max_retries=max_retries, + custom_headers=default_headers, + custom_query=default_query, + http_client=http_client, + _strict_response_validation=_strict_response_validation, + ) + + if is_given(project_id): + self.project_id = project_id + + self.region = region + self.access_token = access_token + self.credentials = credentials + + self.messages = AsyncMessages(self) + self.beta = AsyncBeta(self) + + @override + async def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions: + return _prepare_options(options, project_id=self.project_id, region=self.region) + + @override + async def _prepare_request(self, request: httpx.Request) -> None: + if request.headers.get("Authorization"): + # already authenticated, nothing for us to do + return + + request.headers["Authorization"] = f"Bearer {await self._ensure_access_token()}" + + async def _ensure_access_token(self) -> str: + if self.access_token is not None: + return self.access_token + + if not self.credentials: + self.credentials, project_id = await asyncify(load_auth)(project_id=self.project_id) + if not self.project_id: + self.project_id = project_id + + if self.credentials.expired or not self.credentials.token: + await asyncify(refresh_auth)(self.credentials) + + if not self.credentials.token: + raise RuntimeError("Could not resolve API token from the environment") + + assert isinstance(self.credentials.token, str) + return self.credentials.token + + def copy( + self, + *, + region: str | NotGiven = NOT_GIVEN, + project_id: str | NotGiven = NOT_GIVEN, + access_token: str | None = None, + credentials: GoogleCredentials | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + http_client: httpx.AsyncClient | None = None, + max_retries: int | NotGiven = NOT_GIVEN, + default_headers: Mapping[str, str] | None = None, + set_default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + set_default_query: Mapping[str, object] | None = None, + _extra_kwargs: Mapping[str, Any] = {}, + ) -> Self: + """ + Create a new client instance re-using the same options given to the current client with optional overriding. + """ + if default_headers is not None and set_default_headers is not None: + raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive") + + if default_query is not None and set_default_query is not None: + raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive") + + headers = self._custom_headers + if default_headers is not None: + headers = {**headers, **default_headers} + elif set_default_headers is not None: + headers = set_default_headers + + params = self._custom_query + if default_query is not None: + params = {**params, **default_query} + elif set_default_query is not None: + params = set_default_query + + http_client = http_client or self._client + + return self.__class__( + region=region if is_given(region) else self.region, + project_id=project_id if is_given(project_id) else self.project_id or NOT_GIVEN, + access_token=access_token or self.access_token, + credentials=credentials or self.credentials, + base_url=base_url or self.base_url, + timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, + http_client=http_client, + max_retries=max_retries if is_given(max_retries) else self.max_retries, + default_headers=headers, + default_query=params, + **_extra_kwargs, + ) + + # Alias for `copy` for nicer inline usage, e.g. + # client.with_options(timeout=10).foo.create(...) + with_options = copy + + +def _prepare_options(input_options: FinalRequestOptions, *, project_id: str | None, region: str) -> FinalRequestOptions: + options = model_copy(input_options, deep=True) + + if is_dict(options.json_data): + options.json_data.setdefault("anthropic_version", DEFAULT_VERSION) + + if options.url in {"/v1/messages", "/v1/messages?beta=true"} and options.method == "post": + if project_id is None: + raise RuntimeError( + "No project_id was given and it could not be resolved from credentials. The client should be instantiated with the `project_id` argument or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set." + ) + + if not is_dict(options.json_data): + raise RuntimeError("Expected json data to be a dictionary for post /v1/messages") + + model = options.json_data.pop("model") + stream = options.json_data.get("stream", False) + specifier = "streamRawPredict" if stream else "rawPredict" + + options.url = f"/projects/{project_id}/locations/{region}/publishers/anthropic/models/{model}:{specifier}" + + if options.url in {"/v1/messages/count_tokens", "/v1/messages/count_tokens?beta=true"} and options.method == "post": + if project_id is None: + raise RuntimeError( + "No project_id was given and it could not be resolved from credentials. The client should be instantiated with the `project_id` argument or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set." + ) + + options.url = f"/projects/{project_id}/locations/{region}/publishers/anthropic/models/count-tokens:rawPredict" + + if options.url.startswith("/v1/messages/batches"): + raise AnthropicError("The Batch API is not supported in the Vertex client yet") + + return options diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/__init__.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7359de26a28d45cb78479014634ac0b998ff2adb Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/__init__.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/anthropic_beta_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/anthropic_beta_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5e0f39d4ff6a4ccf8b2929226ad3f38a3a5c47e Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/anthropic_beta_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/base64_image_source_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/base64_image_source_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cb41a82622e68c6546a2856fbac28c15555ef59 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/base64_image_source_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/base64_pdf_source.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/base64_pdf_source.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7b8b980abeeb8efc48ab30222678bb45ccda64b Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/base64_pdf_source.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/base64_pdf_source_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/base64_pdf_source_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..242886db1c6557634e8d46ae24a9cda2a7cea839 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/base64_pdf_source_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_output_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_output_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9db2f5e8f71f45cb001c91289f5dbcc3f4ebd659 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_output_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_output_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_output_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b27b4845dbc4fa3d3e75b454e63750206e683155 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_output_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_result_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_result_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c8a2590f32148934dcc165fbd704dc519d5dc92 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_result_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_result_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_result_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b20dfce937432076e95331b49f60f36a91c3d6f Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_result_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_tool_result_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_tool_result_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28b8d96d25d5bfb65b2e46ebbf989cb7d27583e3 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_tool_result_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_tool_result_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_tool_result_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69340e667bcc165381561ff9dd1d91e3566d199d Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_tool_result_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_tool_result_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_tool_result_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9381b7eb269f955401b28469a0b86c989de04f7e Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_tool_result_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_tool_result_error_code.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_tool_result_error_code.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..586f6ef0fac26c9b3c17ca76f4b4c08db5c5d414 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_tool_result_error_code.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_tool_result_error_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_tool_result_error_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5dea474f712399606304c95abab8e7483bc86ae0 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/bash_code_execution_tool_result_error_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_api_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_api_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d14e7c24fac1a077561afaef46acc458d2c80533 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_api_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_authentication_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_authentication_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab42e97610539e8ff8427a9a84b0dc452e5d7d93 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_authentication_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_billing_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_billing_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f32779a1dda066ece2f696996f1053f08c043ec Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_billing_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b099df30ab595aa11d40daca5e28370092e0025 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_error_response.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_error_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2455f32217c49160381cd45728cddceb0eea0b96 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_error_response.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_gateway_timeout_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_gateway_timeout_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d3779397196d2d62d4ab751fa9b13ecd9ff3f3f Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_gateway_timeout_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_invalid_request_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_invalid_request_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c986d614c48a353630216d03c13c340f69d1a0b Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_invalid_request_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_not_found_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_not_found_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87c350c1bca85334ce1c1d93b21299b5867c26ae Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_not_found_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_overloaded_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_overloaded_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..732e6fadc8655b8432d888bba997b7c903e1c481 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_overloaded_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_permission_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_permission_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..538103032a0be31ec134e57a709af763d2f9cec6 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_permission_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_rate_limit_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_rate_limit_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..681d6d392eb7b66dd3370aff920e55067a4e5a6a Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/beta_rate_limit_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/cache_control_ephemeral_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/cache_control_ephemeral_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f3dcce2715c86447cf6aa216b9a85cf36b6ce4e Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/cache_control_ephemeral_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/cache_creation.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/cache_creation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..865e4b17bcf9689267c2985b69d1378dcb99baae Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/cache_creation.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/capability_support.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/capability_support.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee1feda0545252db20ae11b68ce05e9a574d9528 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/capability_support.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_char_location.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_char_location.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30a27dc9041b4c9de005af1d8c43bc545b5cd84f Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_char_location.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_char_location_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_char_location_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecfb177ca20d8669583e4def0274e17477c5ebb0 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_char_location_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_content_block_location.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_content_block_location.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..402c36af53b67ad27acec5a51167b494a960c635 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_content_block_location.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_content_block_location_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_content_block_location_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4caaf22bcab01384776a62f1133b97482e8db5d Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_content_block_location_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_page_location.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_page_location.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0fedfac3b5e30f70b69829e7e34c2822b2d63824 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_page_location.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_page_location_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_page_location_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1723a973e83b602c9f3c249fb219cf2e84f5582a Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_page_location_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_search_result_location_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_search_result_location_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..321f8a1104b6680230b2aae4b030d4eb2ef90513 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_search_result_location_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_web_search_result_location_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_web_search_result_location_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8be3d2e395d218dc22c5cf89dc4fa633a6ee14d5 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citation_web_search_result_location_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citations_config.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citations_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0cd3806970f72c9c14edc8ea44a82479dfa1d07 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citations_config.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citations_config_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citations_config_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a9103ff2d2e8ee2c2a2c23f1e947f9075809375 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citations_config_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citations_delta.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citations_delta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a8f3eb0cb5a4b492373ed75ddaf64fec4e7e7aa Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citations_delta.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citations_search_result_location.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citations_search_result_location.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e82bfcd8060291d5e0d151609a3a386287a263d8 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citations_search_result_location.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citations_web_search_result_location.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citations_web_search_result_location.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5238bbe9a0707cbf4d9158f5a9dfc6deaf0ff568 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/citations_web_search_result_location.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_output_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_output_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c48fa3370b83d779247e80fc5f47673be0ac00a4 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_output_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_output_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_output_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6919688bbb18babc0be49884d0d349a3d324bee Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_output_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_result_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_result_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1424825da9c2f25a3d953c4e1d362394bf392ba Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_result_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_result_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_result_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab266d24c566c863fbf4f5616906476fa5ea78e4 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_result_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_20250522_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_20250522_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48ecac53c3a070694043c1aa01f70ae5b86e831f Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_20250522_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_20250825_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_20250825_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37804374bf181c02aa0e203384bbb6d4250d669b Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_20250825_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_20260120_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_20260120_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da8993ed2ebf2a26c33ec1f33da5fbba0ad104d4 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_20260120_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_result_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_result_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f45017c57bf4abb52d4e8e73dd8953797a6b9bd5 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_result_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_result_block_content.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_result_block_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3797f5f2794a8c861a6919faac24324d96891513 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_result_block_content.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_result_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_result_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee32863feca1304e727448213c8ca5c5dd32457e Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_result_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_result_block_param_content_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_result_block_param_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..030627e5bdb72c0f28a74878102669bce098e0d5 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_result_block_param_content_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_result_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_result_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b28ecae6bf20385cd7ee8e20027ec29b26bdc227 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_result_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_result_error_code.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_result_error_code.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69f5eecea166c533d024c8d72c086125a17dfbec Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_result_error_code.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_result_error_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_result_error_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef5eefe259a7214d329d794a3810add652f2c8b0 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/code_execution_tool_result_error_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/completion.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/completion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a942c8ea36db2e9a3e955af088cdb0b8791b34a0 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/completion.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/completion_create_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/completion_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7afc036f56fa6d40e5364db1235c6248a74c74c9 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/completion_create_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/container.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/container.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38aa58e37e8e9aebcd0430b5c2c1c63bcce59afa Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/container.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/container_upload_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/container_upload_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..527f0fb5a7a66bd7d0cbd85cc1abf7210830d326 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/container_upload_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/container_upload_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/container_upload_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd62a0cb750ce4b6be11bc69e67c385bc4e5f7b4 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/container_upload_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/content_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/content_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19c2a3016845e61d9005682d06cc6f365fe5eaa4 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/content_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/content_block_delta_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/content_block_delta_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6942fb777d78dd63ca5d4a5eb3af9bb7d4a88fc Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/content_block_delta_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/content_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/content_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9be5a4fc9d84e64b4e2d4ffd205157e3b793d000 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/content_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/content_block_source_content_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/content_block_source_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..037a3f068ab735d81a2916187b3f085da5062e70 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/content_block_source_content_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/content_block_source_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/content_block_source_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..354dc2bb0c5e1198b90ba3597816cd5b6c4163fb Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/content_block_source_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/content_block_start_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/content_block_start_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50c267cc2091d6af3556a16ae8292cb1d96c5b33 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/content_block_start_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/content_block_stop_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/content_block_stop_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0707cdf7b15f6f884792ab1d80524b21e25f232f Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/content_block_stop_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/context_management_capability.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/context_management_capability.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27951df9201dfc90b5ff6dca7271b28f4bdef6a1 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/context_management_capability.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/direct_caller.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/direct_caller.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f586c2a250a5828ff266c6556db51dc751f1e05 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/direct_caller.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/direct_caller_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/direct_caller_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09cbf0dca086314041aca983d4836d099627f8a7 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/direct_caller_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/document_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/document_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4eba071763bc8c7f2161f2b46c916f06e272fe50 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/document_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/document_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/document_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3abccd44b4b2e81d293188a257b6b0d8ac40f760 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/document_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/effort_capability.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/effort_capability.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..083bf6ecba55002fca838fd99387c00d819a18f3 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/effort_capability.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/encrypted_code_execution_result_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/encrypted_code_execution_result_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..871af75dac15468d20384eac102474a40d55c9f6 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/encrypted_code_execution_result_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/encrypted_code_execution_result_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/encrypted_code_execution_result_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1d9491ee76bf8d72b7565efbf456e919d35fde5 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/encrypted_code_execution_result_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/image_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/image_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fb98de8b2337278f3a3d81b9fbb58a9ac9b8a32 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/image_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/input_json_delta.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/input_json_delta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..deb94812e766ef3c336e4977523efd886c0ea819 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/input_json_delta.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/json_output_format_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/json_output_format_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7888647058235e8fcb88337e6d1a2b133b50869a Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/json_output_format_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/memory_tool_20250818_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/memory_tool_20250818_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7f364f80e4e290691925699e5788d1a2f20bdec Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/memory_tool_20250818_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2dd9d244dd7dd0c1ea583cd92c823917e7a1285 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_count_tokens_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_count_tokens_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b2b9ef8e1e2d4cda769e2e7161bdacd8ce85cb3 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_count_tokens_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_count_tokens_tool_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_count_tokens_tool_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e8334f1774a5ca5aa40f7131799721b9a65c288 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_count_tokens_tool_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_create_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4610a342345857e511161beb2b8879e47df2bc4 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_create_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_delta_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_delta_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..778f8e2d51264e1fbf603ae79cc6e769dd81ad0a Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_delta_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_delta_usage.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_delta_usage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..312f32a430d64b7fc5542aa6be5f21fa847476d1 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_delta_usage.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b349f8d09ee090d08dc63d223b7e8fcc8598352d Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_start_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_start_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc8b7195caeec4575fa52a239fee5ca0347f736b Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_start_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_stop_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_stop_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa95454ab1f88dcb43b5331a23a235748b01bdf9 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_stop_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_stream_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_stream_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9c54805ae1c15c5f89760b7826c38d396c8c24d Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_stream_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_tokens_count.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_tokens_count.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c9c346101b9c17f1c45fab412cb1a358dd34eb7 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/message_tokens_count.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/metadata_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/metadata_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8321975638b023cfeb62cc38705a7da51098ad7 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/metadata_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/model.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1bbd50013f853415ea74ef29c6aadf5822ccb31 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/model.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/model_capabilities.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/model_capabilities.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34aad2943bc44794af36a52709ea1709c8ddeddc Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/model_capabilities.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/model_info.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/model_info.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5973a9bb36857d21a4618de8863a70ea849c5ac7 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/model_info.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/model_list_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/model_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b870ccfa41f011f78c1ff97d2f3f42c5ec87604f Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/model_list_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/model_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/model_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..805752c61840828ca3119e41b9a91ee48768331d Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/model_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/output_config_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/output_config_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a475656a7d415926523b5be613d58add6ecb791c Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/output_config_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/parsed_message.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/parsed_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20b942f855d38c6ad80574fc7d04878deef0bb03 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/parsed_message.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/plain_text_source.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/plain_text_source.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb6f3c32e968e09649dbdcf449f079d752936e68 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/plain_text_source.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/plain_text_source_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/plain_text_source_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4d030be72b2d05d3d2d20bf128ae9ca3ec99fb0 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/plain_text_source_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_content_block_delta.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_content_block_delta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed1ac7ab4b1eef30c961d9cd3ac8d4b4d11aa88c Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_content_block_delta.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_content_block_delta_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_content_block_delta_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d7bc5af10114ae9617195b541799a563cf3a182 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_content_block_delta_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_content_block_start_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_content_block_start_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0084eef9f08048581c4567b921712bd68dab1aa3 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_content_block_start_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_content_block_stop_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_content_block_stop_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4ea6355d095066a05c7849c2d1ac6bbabfba8b2 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_content_block_stop_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_message_delta_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_message_delta_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..566da1880e831d0214676517c399e55ad7f0ac8b Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_message_delta_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_message_start_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_message_start_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b9ee772953406427ff2ef7c168d1bb7b908581c Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_message_start_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_message_stop_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_message_stop_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0303d2cd193ebc2287c1512e51181a0a3808a7b8 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_message_stop_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_message_stream_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_message_stream_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6d147454b2c03e335d5002ab058dca4da197f78 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/raw_message_stream_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/redacted_thinking_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/redacted_thinking_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78236e065bec96ab67547cbf59f95f9b16b134b2 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/redacted_thinking_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/redacted_thinking_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/redacted_thinking_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad7a604b3f775d33124c2c38c36af85f57259781 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/redacted_thinking_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/refusal_stop_details.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/refusal_stop_details.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af99d42dbdb87d479288c4866e08e74e3cce9a73 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/refusal_stop_details.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/search_result_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/search_result_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ddb831aa7eba0fa72aab7d3eee48f253692b4b8 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/search_result_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/server_tool_caller.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/server_tool_caller.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4536e307fff86f3a081f1104eb10b8572a14d884 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/server_tool_caller.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/server_tool_caller_20260120.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/server_tool_caller_20260120.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdcb1822beaf7bdb951fa1fcab0e5078328d553e Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/server_tool_caller_20260120.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/server_tool_caller_20260120_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/server_tool_caller_20260120_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b46db57079fb681dcb999c4972311253192552c1 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/server_tool_caller_20260120_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/server_tool_caller_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/server_tool_caller_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4dfa172684fa6ce3a6b8e9e4659f504798c266f6 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/server_tool_caller_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/server_tool_usage.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/server_tool_usage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c42725e2b5f608d19bda52df3c73fc01836fe0d0 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/server_tool_usage.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/server_tool_use_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/server_tool_use_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcefac26a616e76d5a18bd662179b46b5f5c0919 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/server_tool_use_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/server_tool_use_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/server_tool_use_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..211b7d298c69725cbc618cec25dbfc3bc8acdf34 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/server_tool_use_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/signature_delta.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/signature_delta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc800ccf4030ec989daa66b9ee6fb1c90052d24c Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/signature_delta.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/stop_reason.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/stop_reason.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a95acb39141ba7eeb56519a87628dfcfde0b9a20 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/stop_reason.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b92a6ca895d5d86b5006172382f581f916571d5 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4670b8fd8805ed3074c3541e02d92e3a030c67c3 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_citation.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_citation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..491cc03cbe3c8d975e5b6c24872e6aed8a7bd2fa Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_citation.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_citation_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_citation_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6493648ef0d20f93cfc0cc4bc34defdeb0af0f14 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_citation_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_delta.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_delta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6095e7133aa6a9c006a4efcc56de369a27a1ab02 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_delta.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_create_result_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_create_result_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4477c0069bf664f730693fa118924bae6eb7d615 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_create_result_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_create_result_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_create_result_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c41bd22903376b49437708fa672494e6f5034bf Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_create_result_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_str_replace_result_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_str_replace_result_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14ef313ca998e6e48532f964de4bffcc47b2310e Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_str_replace_result_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_str_replace_result_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_str_replace_result_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b967eb10c79eb3050405e02fb5c41529dd912a2 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_str_replace_result_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_tool_result_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_tool_result_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfcf7a72e981530c57b59dfea5d9c7a188aa34f2 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_tool_result_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_tool_result_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_tool_result_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba98164ba0446270661eb2eba82a245b49598604 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_tool_result_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_tool_result_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_tool_result_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c51a8811f36496be77931572aadda173db5dd7b5 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_tool_result_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_tool_result_error_code.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_tool_result_error_code.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c6fbefd15872c7fb1265c61887fcbaf3a065984 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_tool_result_error_code.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_tool_result_error_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_tool_result_error_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd07fa212bbaed4a246a2bd589a70042c0c2aa67 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_tool_result_error_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_view_result_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_view_result_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a9369ee316bddb6872ab20c3e45068d1dd134ba Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_view_result_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_view_result_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_view_result_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be5750197cd5522501004196a927072b420c13d0 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/text_editor_code_execution_view_result_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..828dfae49a89298663690e29cee8e5b4cd219e6e Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..852440cce9af687867775a2f4e220c235517e742 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_capability.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_capability.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2b649f64045c0f83a9f59df189f596f710a296c Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_capability.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_config_adaptive_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_config_adaptive_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9d76d473660175d65acad006b94a51d7225f5e4 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_config_adaptive_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_config_disabled_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_config_disabled_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb094ac809a7250691dd633f04e5da080046aa97 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_config_disabled_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_config_enabled_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_config_enabled_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..900868299f3ea42bf618c4ea87b5bf321380f6f2 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_config_enabled_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_config_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_config_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69801f128546717a47b242cf37148c3693e45614 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_config_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_delta.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_delta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3245d9afb7ffaa7b41625edf94bd2062b54f9cc4 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_delta.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_types.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbd207bc2af1fd6a34e1deba992693ccc967e74c Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/thinking_types.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_bash_20250124_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_bash_20250124_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f91b7be6c199c284a70f947599d0c113edffa4b1 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_bash_20250124_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_choice_any_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_choice_any_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb476c10d90a51fae66063b395ca2fe6ef1c3085 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_choice_any_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_choice_auto_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_choice_auto_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..673b4de36fdd348ad1650e666b5d431964eb9eb1 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_choice_auto_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_choice_none_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_choice_none_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c1e5da0f772bda327b217072cfcd2b8fed775d1 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_choice_none_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_choice_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_choice_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87bd6637fca61f27b63f26be5d3fca1ec331b7fd Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_choice_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_choice_tool_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_choice_tool_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e06732f445f7a4bf4cd688b9d35ffecf92e2569 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_choice_tool_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85b130f6434f4ead9dd6874fa346b7d8f12b7fc7 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_reference_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_reference_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c07f2f672d814edb7bbc73d7f0b285996bca4bd6 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_reference_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_reference_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_reference_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a00bccd23c0b2f385e837dd92d422c8fa6b5743 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_reference_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_result_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_result_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7af1236bd927385bff0f20aa8788c9cc5d8c3dc2 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_result_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_bm25_20251119_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_bm25_20251119_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a719fad6aece1e44616e977025c80f028da33752 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_bm25_20251119_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_regex_20251119_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_regex_20251119_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ede0649c52f89514f8ae912db4450a3d2ba05e0 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_regex_20251119_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_result_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_result_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21ef847829a3338617e2da5a81edd3e2324c59de Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_result_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_result_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_result_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e68c8ab7983e0d37d41d281b8cbeefb53767a51 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_result_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_result_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_result_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcf4e6de852198ecdef2f72f80414296f99eaf0c Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_result_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_result_error_code.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_result_error_code.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4bca5967ed650e72a141586cdbdd35141efdd83 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_result_error_code.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_result_error_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_result_error_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64381397badfe42ffee04d19e44520606b9952d9 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_result_error_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_search_result_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_search_result_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3d33dd3ee811198faaaed7746324b46a76f1ff3 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_search_result_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_search_result_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_search_result_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25b725b377da8c55a65068c6f9e98a8184d65359 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_search_tool_search_result_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_text_editor_20250124_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_text_editor_20250124_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bce15742018f87db997773e7f24076d6df5ddfc8 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_text_editor_20250124_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_text_editor_20250429_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_text_editor_20250429_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a450fd0a09b6684924533344ca8a14d7daf664a Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_text_editor_20250429_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_text_editor_20250728_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_text_editor_20250728_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9fbb5a8682a18ded60d0cef5a6e8c7fa855d4fc8 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_text_editor_20250728_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_union_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_union_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e5e9cb977f3b609176ea105f905383c4181a898 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_union_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_use_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_use_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54d765b9bbaaef699077eeab915a55ec789824aa Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_use_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_use_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_use_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e63e2fd54b16d44b627b532d3c2582a0f5e51b7 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/tool_use_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/url_image_source_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/url_image_source_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1d059d0ac184561759d40c82539ae5e9c68b8b0 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/url_image_source_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/url_pdf_source_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/url_pdf_source_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15749ec90888f6b47ef19a0b4fd52397f92a7620 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/url_pdf_source_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/usage.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/usage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f98937526a26d5aff98ccbd1a6e0749ffc3ceae3 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/usage.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/user_location_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/user_location_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..496d5ec839999205ff8540d13ed4436234c8f8d7 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/user_location_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..752f720c4d554383b98efae7c9a1e2a4a98262e9 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5296a865a591587ef992b570b0a6cb35db7a9867 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_20250910_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_20250910_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b681020fe36dc812c3226b0369056cb50ff6623f Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_20250910_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_20260209_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_20260209_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9247beab18b66374a392d9df116ef1031825730f Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_20260209_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_20260309_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_20260309_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..161aeb28c9d27b774578c16dd741535b1be96364 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_20260309_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_result_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_result_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f5d3e1fc9bcff945bcf5abc0458069a65ba39e0 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_result_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_result_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_result_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..794403ca54630bed38b8c8ef4872b3c3f556e5b1 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_result_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_result_error_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_result_error_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..672a12d5d68aeeaff7f2896a5810d6e0cbd0ff0c Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_result_error_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_result_error_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_result_error_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c6be101a76825b8ff52c3bc18eef7bd6fa7bd8b Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_result_error_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_result_error_code.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_result_error_code.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bda902c6b7caa0ab9a958cb85015a2cd6fcb7f4c Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_fetch_tool_result_error_code.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_result_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_result_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37ea73dadd679b62d4aa37827ffccf340615ffcf Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_result_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_result_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_result_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e75e9cef4d2201b2068a0f98d17fcef5fe90ff94 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_result_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_20250305_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_20250305_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36509a4ba88a948df6280e260b6d54e1b123d89b Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_20250305_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_20260209_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_20260209_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f567c934f1e8f0f807fc3d187450a1719a1f74e8 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_20260209_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_request_error_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_request_error_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90a6059252d9f0abda880f724d79a24706514617 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_request_error_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_result_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_result_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a05d6bc7dae8ce57b8e02ab58f2348c87ea7aa4b Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_result_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_result_block_content.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_result_block_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57e4c4d4169fb23ad694df4b66edc5907f1f225f Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_result_block_content.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_result_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_result_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b03f25cf46c8491856e43295ab0383164a3b4b20 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_result_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_result_block_param_content_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_result_block_param_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aea0000908248d119b8bb9664507d61becf5030d Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_result_block_param_content_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_result_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_result_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e6be8d14c7e0ddf642a9b3044b9b04b21bf7390 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_result_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_result_error_code.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_result_error_code.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66eda3be42772564866a733e08fe7cb18d3ee022 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/__pycache__/web_search_tool_result_error_code.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/bash_code_execution_output_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/bash_code_execution_output_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..ec8dc25d6fd1650260b742ad25dee6694f16b6fd --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/bash_code_execution_output_block_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BashCodeExecutionOutputBlockParam"] + + +class BashCodeExecutionOutputBlockParam(TypedDict, total=False): + file_id: Required[str] + + type: Required[Literal["bash_code_execution_output"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/bash_code_execution_result_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/bash_code_execution_result_block.py new file mode 100644 index 0000000000000000000000000000000000000000..bbc5c5bff54f23ff9cd3465650af77e939dd78d9 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/bash_code_execution_result_block.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List +from typing_extensions import Literal + +from .._models import BaseModel +from .bash_code_execution_output_block import BashCodeExecutionOutputBlock + +__all__ = ["BashCodeExecutionResultBlock"] + + +class BashCodeExecutionResultBlock(BaseModel): + content: List[BashCodeExecutionOutputBlock] + + return_code: int + + stderr: str + + stdout: str + + type: Literal["bash_code_execution_result"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/bash_code_execution_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/bash_code_execution_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..f09bdc4a54881ed839ba57e13f6632721512f153 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/bash_code_execution_result_block_param.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Literal, Required, TypedDict + +from .bash_code_execution_output_block_param import BashCodeExecutionOutputBlockParam + +__all__ = ["BashCodeExecutionResultBlockParam"] + + +class BashCodeExecutionResultBlockParam(TypedDict, total=False): + content: Required[Iterable[BashCodeExecutionOutputBlockParam]] + + return_code: Required[int] + + stderr: Required[str] + + stdout: Required[str] + + type: Required[Literal["bash_code_execution_result"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/bash_code_execution_tool_result_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/bash_code_execution_tool_result_block.py new file mode 100644 index 0000000000000000000000000000000000000000..eb928cdf6d4b0469de63af66c63dec38427fe85f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/bash_code_execution_tool_result_block.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Literal, TypeAlias + +from .._models import BaseModel +from .bash_code_execution_result_block import BashCodeExecutionResultBlock +from .bash_code_execution_tool_result_error import BashCodeExecutionToolResultError + +__all__ = ["BashCodeExecutionToolResultBlock", "Content"] + +Content: TypeAlias = Union[BashCodeExecutionToolResultError, BashCodeExecutionResultBlock] + + +class BashCodeExecutionToolResultBlock(BaseModel): + content: Content + + tool_use_id: str + + type: Literal["bash_code_execution_tool_result"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/__init__.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ba047936c23d335c23405940bb911d178c40a3f2 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/__init__.py @@ -0,0 +1,575 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .beta_skill import BetaSkill as BetaSkill +from .beta_usage import BetaUsage as BetaUsage +from .beta_message import BetaMessage as BetaMessage +from .deleted_file import DeletedFile as DeletedFile +from .beta_packages import BetaPackages as BetaPackages +from .file_metadata import FileMetadata as FileMetadata +from .beta_container import BetaContainer as BetaContainer +from .beta_file_scope import BetaFileScope as BetaFileScope +from .beta_model_info import BetaModelInfo as BetaModelInfo +from .beta_text_block import BetaTextBlock as BetaTextBlock +from .beta_text_delta import BetaTextDelta as BetaTextDelta +from .beta_tool_param import BetaToolParam as BetaToolParam +from .beta_environment import BetaEnvironment as BetaEnvironment +from .beta_stop_reason import BetaStopReason as BetaStopReason +from .file_list_params import FileListParams as FileListParams +from .agent_list_params import AgentListParams as AgentListParams +from .beta_cloud_config import BetaCloudConfig as BetaCloudConfig +from .beta_skill_params import BetaSkillParams as BetaSkillParams +from .beta_user_profile import BetaUserProfile as BetaUserProfile +from .model_list_params import ModelListParams as ModelListParams +from .skill_list_params import SkillListParams as SkillListParams +from .vault_list_params import VaultListParams as VaultListParams +from .beta_content_block import BetaContentBlock as BetaContentBlock +from .beta_direct_caller import BetaDirectCaller as BetaDirectCaller +from .beta_message_param import BetaMessageParam as BetaMessageParam +from .beta_text_citation import BetaTextCitation as BetaTextCitation +from .file_upload_params import FileUploadParams as FileUploadParams +from .agent_create_params import AgentCreateParams as AgentCreateParams +from .agent_update_params import AgentUpdateParams as AgentUpdateParams +from .beta_cache_creation import BetaCacheCreation as BetaCacheCreation +from .beta_document_block import BetaDocumentBlock as BetaDocumentBlock +from .beta_metadata_param import BetaMetadataParam as BetaMetadataParam +from .beta_thinking_block import BetaThinkingBlock as BetaThinkingBlock +from .beta_thinking_delta import BetaThinkingDelta as BetaThinkingDelta +from .beta_thinking_types import BetaThinkingTypes as BetaThinkingTypes +from .beta_tool_use_block import BetaToolUseBlock as BetaToolUseBlock +from .session_list_params import SessionListParams as SessionListParams +from .skill_create_params import SkillCreateParams as SkillCreateParams +from .skill_list_response import SkillListResponse as SkillListResponse +from .vault_create_params import VaultCreateParams as VaultCreateParams +from .vault_update_params import VaultUpdateParams as VaultUpdateParams +from .beta_citation_config import BetaCitationConfig as BetaCitationConfig +from .beta_citations_delta import BetaCitationsDelta as BetaCitationsDelta +from .beta_limited_network import BetaLimitedNetwork as BetaLimitedNetwork +from .beta_packages_params import BetaPackagesParams as BetaPackagesParams +from .beta_signature_delta import BetaSignatureDelta as BetaSignatureDelta +from .beta_web_fetch_block import BetaWebFetchBlock as BetaWebFetchBlock +from .unwrap_webhook_event import UnwrapWebhookEvent as UnwrapWebhookEvent +from .agent_retrieve_params import AgentRetrieveParams as AgentRetrieveParams +from .beta_compaction_block import BetaCompactionBlock as BetaCompactionBlock +from .beta_container_params import BetaContainerParams as BetaContainerParams +from .beta_input_json_delta import BetaInputJSONDelta as BetaInputJSONDelta +from .beta_iterations_usage import BetaIterationsUsage as BetaIterationsUsage +from .beta_text_block_param import BetaTextBlockParam as BetaTextBlockParam +from .beta_tool_union_param import BetaToolUnionParam as BetaToolUnionParam +from .message_create_params import MessageCreateParams as MessageCreateParams +from .session_create_params import SessionCreateParams as SessionCreateParams +from .session_update_params import SessionUpdateParams as SessionUpdateParams +from .skill_create_response import SkillCreateResponse as SkillCreateResponse +from .skill_delete_response import SkillDeleteResponse as SkillDeleteResponse +from .beta_base64_pdf_source import BetaBase64PDFSource as BetaBase64PDFSource +from .beta_effort_capability import BetaEffortCapability as BetaEffortCapability +from .beta_image_block_param import BetaImageBlockParam as BetaImageBlockParam +from .beta_mcp_toolset_param import BetaMCPToolsetParam as BetaMCPToolsetParam +from .beta_plain_text_source import BetaPlainTextSource as BetaPlainTextSource +from .beta_server_tool_usage import BetaServerToolUsage as BetaServerToolUsage +from .beta_tool_choice_param import BetaToolChoiceParam as BetaToolChoiceParam +from .beta_capability_support import BetaCapabilitySupport as BetaCapabilitySupport +from .beta_mcp_tool_use_block import BetaMCPToolUseBlock as BetaMCPToolUseBlock +from .beta_model_capabilities import BetaModelCapabilities as BetaModelCapabilities +from .beta_server_tool_caller import BetaServerToolCaller as BetaServerToolCaller +from .beta_webhook_event_data import BetaWebhookEventData as BetaWebhookEventData +from .environment_list_params import EnvironmentListParams as EnvironmentListParams +from .skill_retrieve_response import SkillRetrieveResponse as SkillRetrieveResponse +from .beta_cloud_config_params import BetaCloudConfigParams as BetaCloudConfigParams +from .beta_content_block_param import BetaContentBlockParam as BetaContentBlockParam +from .beta_direct_caller_param import BetaDirectCallerParam as BetaDirectCallerParam +from .beta_message_delta_usage import BetaMessageDeltaUsage as BetaMessageDeltaUsage +from .beta_output_config_param import BetaOutputConfigParam as BetaOutputConfigParam +from .beta_text_citation_param import BetaTextCitationParam as BetaTextCitationParam +from .beta_thinking_capability import BetaThinkingCapability as BetaThinkingCapability +from .beta_user_location_param import BetaUserLocationParam as BetaUserLocationParam +from .memory_store_list_params import MemoryStoreListParams as MemoryStoreListParams +from .user_profile_list_params import UserProfileListParams as UserProfileListParams +from .beta_advisor_result_block import BetaAdvisorResultBlock as BetaAdvisorResultBlock +from .beta_managed_agents_agent import BetaManagedAgentsAgent as BetaManagedAgentsAgent +from .beta_managed_agents_model import BetaManagedAgentsModel as BetaManagedAgentsModel +from .beta_managed_agents_vault import BetaManagedAgentsVault as BetaManagedAgentsVault +from .beta_message_tokens_count import BetaMessageTokensCount as BetaMessageTokensCount +from .beta_refusal_stop_details import BetaRefusalStopDetails as BetaRefusalStopDetails +from .beta_thinking_block_param import BetaThinkingBlockParam as BetaThinkingBlockParam +from .beta_thinking_turns_param import BetaThinkingTurnsParam as BetaThinkingTurnsParam +from .beta_tool_reference_block import BetaToolReferenceBlock as BetaToolReferenceBlock +from .beta_tool_use_block_param import BetaToolUseBlockParam as BetaToolUseBlockParam +from .beta_tool_uses_keep_param import BetaToolUsesKeepParam as BetaToolUsesKeepParam +from .beta_unrestricted_network import BetaUnrestrictedNetwork as BetaUnrestrictedNetwork +from .beta_url_pdf_source_param import BetaURLPDFSourceParam as BetaURLPDFSourceParam +from .environment_create_params import EnvironmentCreateParams as EnvironmentCreateParams +from .environment_update_params import EnvironmentUpdateParams as EnvironmentUpdateParams +from .beta_mcp_tool_config_param import BetaMCPToolConfigParam as BetaMCPToolConfigParam +from .beta_mcp_tool_result_block import BetaMCPToolResultBlock as BetaMCPToolResultBlock +from .beta_server_tool_use_block import BetaServerToolUseBlock as BetaServerToolUseBlock +from .beta_thinking_config_param import BetaThinkingConfigParam as BetaThinkingConfigParam +from .beta_tool_choice_any_param import BetaToolChoiceAnyParam as BetaToolChoiceAnyParam +from .beta_web_fetch_block_param import BetaWebFetchBlockParam as BetaWebFetchBlockParam +from .memory_store_create_params import MemoryStoreCreateParams as MemoryStoreCreateParams +from .memory_store_update_params import MemoryStoreUpdateParams as MemoryStoreUpdateParams +from .user_profile_create_params import UserProfileCreateParams as UserProfileCreateParams +from .user_profile_update_params import UserProfileUpdateParams as UserProfileUpdateParams +from .beta_base64_pdf_block_param import BetaBase64PDFBlockParam as BetaBase64PDFBlockParam +from .beta_citation_char_location import BetaCitationCharLocation as BetaCitationCharLocation +from .beta_citation_page_location import BetaCitationPageLocation as BetaCitationPageLocation +from .beta_citations_config_param import BetaCitationsConfigParam as BetaCitationsConfigParam +from .beta_compaction_block_param import BetaCompactionBlockParam as BetaCompactionBlockParam +from .beta_container_upload_block import BetaContainerUploadBlock as BetaContainerUploadBlock +from .beta_limited_network_params import BetaLimitedNetworkParams as BetaLimitedNetworkParams +from .beta_managed_agents_session import BetaManagedAgentsSession as BetaManagedAgentsSession +from .beta_raw_message_stop_event import BetaRawMessageStopEvent as BetaRawMessageStopEvent +from .beta_tool_choice_auto_param import BetaToolChoiceAutoParam as BetaToolChoiceAutoParam +from .beta_tool_choice_none_param import BetaToolChoiceNoneParam as BetaToolChoiceNoneParam +from .beta_tool_choice_tool_param import BetaToolChoiceToolParam as BetaToolChoiceToolParam +from .beta_url_image_source_param import BetaURLImageSourceParam as BetaURLImageSourceParam +from .message_count_tokens_params import MessageCountTokensParams as MessageCountTokensParams +from .beta_base64_pdf_source_param import BetaBase64PDFSourceParam as BetaBase64PDFSourceParam +from .beta_file_image_source_param import BetaFileImageSourceParam as BetaFileImageSourceParam +from .beta_message_iteration_usage import BetaMessageIterationUsage as BetaMessageIterationUsage +from .beta_plain_text_source_param import BetaPlainTextSourceParam as BetaPlainTextSourceParam +from .beta_raw_content_block_delta import BetaRawContentBlockDelta as BetaRawContentBlockDelta +from .beta_raw_message_delta_event import BetaRawMessageDeltaEvent as BetaRawMessageDeltaEvent +from .beta_raw_message_start_event import BetaRawMessageStartEvent as BetaRawMessageStartEvent +from .beta_redacted_thinking_block import BetaRedactedThinkingBlock as BetaRedactedThinkingBlock +from .beta_token_task_budget_param import BetaTokenTaskBudgetParam as BetaTokenTaskBudgetParam +from .beta_tool_result_block_param import BetaToolResultBlockParam as BetaToolResultBlockParam +from .beta_tool_uses_trigger_param import BetaToolUsesTriggerParam as BetaToolUsesTriggerParam +from .beta_web_search_result_block import BetaWebSearchResultBlock as BetaWebSearchResultBlock +from .beta_all_thinking_turns_param import BetaAllThinkingTurnsParam as BetaAllThinkingTurnsParam +from .beta_json_output_format_param import BetaJSONOutputFormatParam as BetaJSONOutputFormatParam +from .beta_mcp_tool_use_block_param import BetaMCPToolUseBlockParam as BetaMCPToolUseBlockParam +from .beta_raw_message_stream_event import BetaRawMessageStreamEvent as BetaRawMessageStreamEvent +from .beta_server_tool_caller_param import BetaServerToolCallerParam as BetaServerToolCallerParam +from .beta_tool_bash_20241022_param import BetaToolBash20241022Param as BetaToolBash20241022Param +from .beta_tool_bash_20250124_param import BetaToolBash20250124Param as BetaToolBash20250124Param +from .beta_user_profile_trust_grant import BetaUserProfileTrustGrant as BetaUserProfileTrustGrant +from .beta_advisor_tool_result_block import BetaAdvisorToolResultBlock as BetaAdvisorToolResultBlock +from .beta_advisor_tool_result_error import BetaAdvisorToolResultError as BetaAdvisorToolResultError +from .beta_base64_image_source_param import BetaBase64ImageSourceParam as BetaBase64ImageSourceParam +from .beta_managed_agents_multiagent import BetaManagedAgentsMultiagent as BetaManagedAgentsMultiagent +from .beta_search_result_block_param import BetaSearchResultBlockParam as BetaSearchResultBlockParam +from .beta_advisor_result_block_param import BetaAdvisorResultBlockParam as BetaAdvisorResultBlockParam +from .beta_compaction_iteration_usage import BetaCompactionIterationUsage as BetaCompactionIterationUsage +from .beta_content_block_source_param import BetaContentBlockSourceParam as BetaContentBlockSourceParam +from .beta_file_document_source_param import BetaFileDocumentSourceParam as BetaFileDocumentSourceParam +from .beta_input_tokens_trigger_param import BetaInputTokensTriggerParam as BetaInputTokensTriggerParam +from .beta_managed_agents_custom_tool import BetaManagedAgentsCustomTool as BetaManagedAgentsCustomTool +from .beta_managed_agents_mcp_toolset import BetaManagedAgentsMCPToolset as BetaManagedAgentsMCPToolset +from .beta_managed_agents_model_param import BetaManagedAgentsModelParam as BetaManagedAgentsModelParam +from .beta_memory_tool_20250818_param import BetaMemoryTool20250818Param as BetaMemoryTool20250818Param +from .beta_tool_reference_block_param import BetaToolReferenceBlockParam as BetaToolReferenceBlockParam +from .beta_unrestricted_network_param import BetaUnrestrictedNetworkParam as BetaUnrestrictedNetworkParam +from .beta_advisor_tool_20260301_param import BetaAdvisorTool20260301Param as BetaAdvisorTool20260301Param +from .beta_code_execution_output_block import BetaCodeExecutionOutputBlock as BetaCodeExecutionOutputBlock +from .beta_code_execution_result_block import BetaCodeExecutionResultBlock as BetaCodeExecutionResultBlock +from .beta_compact_20260112_edit_param import BetaCompact20260112EditParam as BetaCompact20260112EditParam +from .beta_context_management_response import BetaContextManagementResponse as BetaContextManagementResponse +from .beta_environment_delete_response import BetaEnvironmentDeleteResponse as BetaEnvironmentDeleteResponse +from .beta_managed_agents_agent_params import BetaManagedAgentsAgentParams as BetaManagedAgentsAgentParams +from .beta_managed_agents_custom_skill import BetaManagedAgentsCustomSkill as BetaManagedAgentsCustomSkill +from .beta_managed_agents_memory_store import BetaManagedAgentsMemoryStore as BetaManagedAgentsMemoryStore +from .beta_managed_agents_model_config import BetaManagedAgentsModelConfig as BetaManagedAgentsModelConfig +from .beta_managed_agents_skill_params import BetaManagedAgentsSkillParams as BetaManagedAgentsSkillParams +from .beta_server_tool_caller_20260120 import BetaServerToolCaller20260120 as BetaServerToolCaller20260120 +from .beta_server_tool_use_block_param import BetaServerToolUseBlockParam as BetaServerToolUseBlockParam +from .beta_user_profile_enrollment_url import BetaUserProfileEnrollmentURL as BetaUserProfileEnrollmentURL +from .beta_web_fetch_tool_result_block import BetaWebFetchToolResultBlock as BetaWebFetchToolResultBlock +from .beta_citation_char_location_param import BetaCitationCharLocationParam as BetaCitationCharLocationParam +from .beta_citation_page_location_param import BetaCitationPageLocationParam as BetaCitationPageLocationParam +from .beta_container_upload_block_param import BetaContainerUploadBlockParam as BetaContainerUploadBlockParam +from .beta_managed_agents_deleted_vault import BetaManagedAgentsDeletedVault as BetaManagedAgentsDeletedVault +from .beta_managed_agents_session_agent import BetaManagedAgentsSessionAgent as BetaManagedAgentsSessionAgent +from .beta_managed_agents_session_stats import BetaManagedAgentsSessionStats as BetaManagedAgentsSessionStats +from .beta_managed_agents_session_usage import BetaManagedAgentsSessionUsage as BetaManagedAgentsSessionUsage +from .beta_memory_tool_20250818_command import BetaMemoryTool20250818Command as BetaMemoryTool20250818Command +from .beta_raw_content_block_stop_event import BetaRawContentBlockStopEvent as BetaRawContentBlockStopEvent +from .beta_request_document_block_param import BetaRequestDocumentBlockParam as BetaRequestDocumentBlockParam +from .beta_web_search_tool_result_block import BetaWebSearchToolResultBlock as BetaWebSearchToolResultBlock +from .beta_web_search_tool_result_error import BetaWebSearchToolResultError as BetaWebSearchToolResultError +from .beta_advisor_redacted_result_block import BetaAdvisorRedactedResultBlock as BetaAdvisorRedactedResultBlock +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam as BetaCacheControlEphemeralParam +from .beta_context_management_capability import BetaContextManagementCapability as BetaContextManagementCapability +from .beta_mcp_tool_default_config_param import BetaMCPToolDefaultConfigParam as BetaMCPToolDefaultConfigParam +from .beta_raw_content_block_delta_event import BetaRawContentBlockDeltaEvent as BetaRawContentBlockDeltaEvent +from .beta_raw_content_block_start_event import BetaRawContentBlockStartEvent as BetaRawContentBlockStartEvent +from .beta_redacted_thinking_block_param import BetaRedactedThinkingBlockParam as BetaRedactedThinkingBlockParam +from .beta_thinking_config_enabled_param import BetaThinkingConfigEnabledParam as BetaThinkingConfigEnabledParam +from .beta_tool_search_tool_result_block import BetaToolSearchToolResultBlock as BetaToolSearchToolResultBlock +from .beta_tool_search_tool_result_error import BetaToolSearchToolResultError as BetaToolSearchToolResultError +from .beta_web_fetch_tool_20250910_param import BetaWebFetchTool20250910Param as BetaWebFetchTool20250910Param +from .beta_web_fetch_tool_20260209_param import BetaWebFetchTool20260209Param as BetaWebFetchTool20260209Param +from .beta_web_fetch_tool_20260309_param import BetaWebFetchTool20260309Param as BetaWebFetchTool20260309Param +from .beta_web_search_result_block_param import BetaWebSearchResultBlockParam as BetaWebSearchResultBlockParam +from .beta_compaction_content_block_delta import BetaCompactionContentBlockDelta as BetaCompactionContentBlockDelta +from .beta_managed_agents_agent_reference import BetaManagedAgentsAgentReference as BetaManagedAgentsAgentReference +from .beta_managed_agents_anthropic_skill import BetaManagedAgentsAnthropicSkill as BetaManagedAgentsAnthropicSkill +from .beta_managed_agents_branch_checkout import BetaManagedAgentsBranchCheckout as BetaManagedAgentsBranchCheckout +from .beta_managed_agents_commit_checkout import BetaManagedAgentsCommitCheckout as BetaManagedAgentsCommitCheckout +from .beta_managed_agents_deleted_session import BetaManagedAgentsDeletedSession as BetaManagedAgentsDeletedSession +from .beta_managed_agents_mcp_tool_config import BetaManagedAgentsMCPToolConfig as BetaManagedAgentsMCPToolConfig +from .beta_thinking_config_adaptive_param import BetaThinkingConfigAdaptiveParam as BetaThinkingConfigAdaptiveParam +from .beta_thinking_config_disabled_param import BetaThinkingConfigDisabledParam as BetaThinkingConfigDisabledParam +from .beta_web_search_tool_20250305_param import BetaWebSearchTool20250305Param as BetaWebSearchTool20250305Param +from .beta_web_search_tool_20260209_param import BetaWebSearchTool20260209Param as BetaWebSearchTool20260209Param +from .beta_advisor_message_iteration_usage import BetaAdvisorMessageIterationUsage as BetaAdvisorMessageIterationUsage +from .beta_advisor_tool_result_block_param import BetaAdvisorToolResultBlockParam as BetaAdvisorToolResultBlockParam +from .beta_advisor_tool_result_error_param import BetaAdvisorToolResultErrorParam as BetaAdvisorToolResultErrorParam +from .beta_citation_content_block_location import BetaCitationContentBlockLocation as BetaCitationContentBlockLocation +from .beta_citation_search_result_location import BetaCitationSearchResultLocation as BetaCitationSearchResultLocation +from .beta_context_management_config_param import BetaContextManagementConfigParam as BetaContextManagementConfigParam +from .beta_tool_text_editor_20241022_param import BetaToolTextEditor20241022Param as BetaToolTextEditor20241022Param +from .beta_tool_text_editor_20250124_param import BetaToolTextEditor20250124Param as BetaToolTextEditor20250124Param +from .beta_tool_text_editor_20250429_param import BetaToolTextEditor20250429Param as BetaToolTextEditor20250429Param +from .beta_tool_text_editor_20250728_param import BetaToolTextEditor20250728Param as BetaToolTextEditor20250728Param +from .beta_bash_code_execution_output_block import BetaBashCodeExecutionOutputBlock as BetaBashCodeExecutionOutputBlock +from .beta_bash_code_execution_result_block import BetaBashCodeExecutionResultBlock as BetaBashCodeExecutionResultBlock +from .beta_code_execution_tool_result_block import BetaCodeExecutionToolResultBlock as BetaCodeExecutionToolResultBlock +from .beta_code_execution_tool_result_error import BetaCodeExecutionToolResultError as BetaCodeExecutionToolResultError +from .beta_managed_agents_agent_tool_config import BetaManagedAgentsAgentToolConfig as BetaManagedAgentsAgentToolConfig +from .beta_managed_agents_always_ask_policy import BetaManagedAgentsAlwaysAskPolicy as BetaManagedAgentsAlwaysAskPolicy +from .beta_managed_agents_multiagent_params import ( + BetaManagedAgentsMultiagentParams as BetaManagedAgentsMultiagentParams, +) +from .beta_tool_computer_use_20241022_param import BetaToolComputerUse20241022Param as BetaToolComputerUse20241022Param +from .beta_tool_computer_use_20250124_param import BetaToolComputerUse20250124Param as BetaToolComputerUse20250124Param +from .beta_tool_computer_use_20251124_param import BetaToolComputerUse20251124Param as BetaToolComputerUse20251124Param +from .beta_web_fetch_tool_result_error_code import BetaWebFetchToolResultErrorCode as BetaWebFetchToolResultErrorCode +from .beta_webhook_session_idled_event_data import BetaWebhookSessionIdledEventData as BetaWebhookSessionIdledEventData +from .beta_webhook_vault_created_event_data import BetaWebhookVaultCreatedEventData as BetaWebhookVaultCreatedEventData +from .beta_webhook_vault_deleted_event_data import BetaWebhookVaultDeletedEventData as BetaWebhookVaultDeletedEventData +from .beta_code_execution_output_block_param import ( + BetaCodeExecutionOutputBlockParam as BetaCodeExecutionOutputBlockParam, +) +from .beta_code_execution_result_block_param import ( + BetaCodeExecutionResultBlockParam as BetaCodeExecutionResultBlockParam, +) +from .beta_input_tokens_clear_at_least_param import BetaInputTokensClearAtLeastParam as BetaInputTokensClearAtLeastParam +from .beta_managed_agents_custom_tool_params import ( + BetaManagedAgentsCustomToolParams as BetaManagedAgentsCustomToolParams, +) +from .beta_managed_agents_mcp_toolset_params import ( + BetaManagedAgentsMCPToolsetParams as BetaManagedAgentsMCPToolsetParams, +) +from .beta_memory_tool_20250818_view_command import ( + BetaMemoryTool20250818ViewCommand as BetaMemoryTool20250818ViewCommand, +) +from .beta_server_tool_caller_20260120_param import ( + BetaServerToolCaller20260120Param as BetaServerToolCaller20260120Param, +) +from .beta_web_fetch_tool_result_block_param import BetaWebFetchToolResultBlockParam as BetaWebFetchToolResultBlockParam +from .beta_web_fetch_tool_result_error_block import BetaWebFetchToolResultErrorBlock as BetaWebFetchToolResultErrorBlock +from .beta_web_search_tool_result_error_code import BetaWebSearchToolResultErrorCode as BetaWebSearchToolResultErrorCode +from .beta_webhook_vault_archived_event_data import ( + BetaWebhookVaultArchivedEventData as BetaWebhookVaultArchivedEventData, +) +from .beta_clear_thinking_20251015_edit_param import ( + BetaClearThinking20251015EditParam as BetaClearThinking20251015EditParam, +) +from .beta_code_execution_tool_20250522_param import ( + BetaCodeExecutionTool20250522Param as BetaCodeExecutionTool20250522Param, +) +from .beta_code_execution_tool_20250825_param import ( + BetaCodeExecutionTool20250825Param as BetaCodeExecutionTool20250825Param, +) +from .beta_code_execution_tool_20260120_param import ( + BetaCodeExecutionTool20260120Param as BetaCodeExecutionTool20260120Param, +) +from .beta_content_block_source_content_param import ( + BetaContentBlockSourceContentParam as BetaContentBlockSourceContentParam, +) +from .beta_managed_agents_always_allow_policy import ( + BetaManagedAgentsAlwaysAllowPolicy as BetaManagedAgentsAlwaysAllowPolicy, +) +from .beta_managed_agents_custom_skill_params import ( + BetaManagedAgentsCustomSkillParams as BetaManagedAgentsCustomSkillParams, +) +from .beta_managed_agents_model_config_params import ( + BetaManagedAgentsModelConfigParams as BetaManagedAgentsModelConfigParams, +) +from .beta_web_search_tool_result_block_param import ( + BetaWebSearchToolResultBlockParam as BetaWebSearchToolResultBlockParam, +) +from .beta_webhook_session_created_event_data import ( + BetaWebhookSessionCreatedEventData as BetaWebhookSessionCreatedEventData, +) +from .beta_webhook_session_deleted_event_data import ( + BetaWebhookSessionDeletedEventData as BetaWebhookSessionDeletedEventData, +) +from .beta_webhook_session_pending_event_data import ( + BetaWebhookSessionPendingEventData as BetaWebhookSessionPendingEventData, +) +from .beta_webhook_session_running_event_data import ( + BetaWebhookSessionRunningEventData as BetaWebhookSessionRunningEventData, +) +from .beta_advisor_redacted_result_block_param import ( + BetaAdvisorRedactedResultBlockParam as BetaAdvisorRedactedResultBlockParam, +) +from .beta_clear_tool_uses_20250919_edit_param import ( + BetaClearToolUses20250919EditParam as BetaClearToolUses20250919EditParam, +) +from .beta_managed_agents_cache_creation_usage import ( + BetaManagedAgentsCacheCreationUsage as BetaManagedAgentsCacheCreationUsage, +) +from .beta_managed_agents_deleted_memory_store import ( + BetaManagedAgentsDeletedMemoryStore as BetaManagedAgentsDeletedMemoryStore, +) +from .beta_managed_agents_file_resource_params import ( + BetaManagedAgentsFileResourceParams as BetaManagedAgentsFileResourceParams, +) +from .beta_memory_tool_20250818_create_command import ( + BetaMemoryTool20250818CreateCommand as BetaMemoryTool20250818CreateCommand, +) +from .beta_memory_tool_20250818_delete_command import ( + BetaMemoryTool20250818DeleteCommand as BetaMemoryTool20250818DeleteCommand, +) +from .beta_memory_tool_20250818_insert_command import ( + BetaMemoryTool20250818InsertCommand as BetaMemoryTool20250818InsertCommand, +) +from .beta_memory_tool_20250818_rename_command import ( + BetaMemoryTool20250818RenameCommand as BetaMemoryTool20250818RenameCommand, +) +from .beta_request_mcp_tool_result_block_param import ( + BetaRequestMCPToolResultBlockParam as BetaRequestMCPToolResultBlockParam, +) +from .beta_tool_search_tool_result_block_param import ( + BetaToolSearchToolResultBlockParam as BetaToolSearchToolResultBlockParam, +) +from .beta_tool_search_tool_result_error_param import ( + BetaToolSearchToolResultErrorParam as BetaToolSearchToolResultErrorParam, +) +from .beta_web_search_tool_request_error_param import ( + BetaWebSearchToolRequestErrorParam as BetaWebSearchToolRequestErrorParam, +) +from .beta_webhook_session_archived_event_data import ( + BetaWebhookSessionArchivedEventData as BetaWebhookSessionArchivedEventData, +) +from .beta_citations_web_search_result_location import ( + BetaCitationsWebSearchResultLocation as BetaCitationsWebSearchResultLocation, +) +from .beta_managed_agents_agent_toolset20260401 import ( + BetaManagedAgentsAgentToolset20260401 as BetaManagedAgentsAgentToolset20260401, +) +from .beta_managed_agents_branch_checkout_param import ( + BetaManagedAgentsBranchCheckoutParam as BetaManagedAgentsBranchCheckoutParam, +) +from .beta_managed_agents_commit_checkout_param import ( + BetaManagedAgentsCommitCheckoutParam as BetaManagedAgentsCommitCheckoutParam, +) +from .beta_managed_agents_url_mcp_server_params import ( + BetaManagedAgentsURLMCPServerParams as BetaManagedAgentsURLMCPServerParams, +) +from .beta_tool_search_tool_bm25_20251119_param import ( + BetaToolSearchToolBm25_20251119Param as BetaToolSearchToolBm25_20251119Param, +) +from .beta_tool_search_tool_search_result_block import ( + BetaToolSearchToolSearchResultBlock as BetaToolSearchToolSearchResultBlock, +) +from .beta_web_search_tool_result_block_content import ( + BetaWebSearchToolResultBlockContent as BetaWebSearchToolResultBlockContent, +) +from .beta_bash_code_execution_tool_result_block import ( + BetaBashCodeExecutionToolResultBlock as BetaBashCodeExecutionToolResultBlock, +) +from .beta_bash_code_execution_tool_result_error import ( + BetaBashCodeExecutionToolResultError as BetaBashCodeExecutionToolResultError, +) +from .beta_citation_content_block_location_param import ( + BetaCitationContentBlockLocationParam as BetaCitationContentBlockLocationParam, +) +from .beta_citation_search_result_location_param import ( + BetaCitationSearchResultLocationParam as BetaCitationSearchResultLocationParam, +) +from .beta_clear_thinking_20251015_edit_response import ( + BetaClearThinking20251015EditResponse as BetaClearThinking20251015EditResponse, +) +from .beta_code_execution_tool_result_error_code import ( + BetaCodeExecutionToolResultErrorCode as BetaCodeExecutionToolResultErrorCode, +) +from .beta_encrypted_code_execution_result_block import ( + BetaEncryptedCodeExecutionResultBlock as BetaEncryptedCodeExecutionResultBlock, +) +from .beta_managed_agents_anthropic_skill_params import ( + BetaManagedAgentsAnthropicSkillParams as BetaManagedAgentsAnthropicSkillParams, +) +from .beta_managed_agents_mcp_tool_config_params import ( + BetaManagedAgentsMCPToolConfigParams as BetaManagedAgentsMCPToolConfigParams, +) +from .beta_managed_agents_multiagent_self_params import ( + BetaManagedAgentsMultiagentSelfParams as BetaManagedAgentsMultiagentSelfParams, +) +from .beta_tool_search_tool_regex_20251119_param import ( + BetaToolSearchToolRegex20251119Param as BetaToolSearchToolRegex20251119Param, +) +from .beta_bash_code_execution_output_block_param import ( + BetaBashCodeExecutionOutputBlockParam as BetaBashCodeExecutionOutputBlockParam, +) +from .beta_bash_code_execution_result_block_param import ( + BetaBashCodeExecutionResultBlockParam as BetaBashCodeExecutionResultBlockParam, +) +from .beta_clear_tool_uses_20250919_edit_response import ( + BetaClearToolUses20250919EditResponse as BetaClearToolUses20250919EditResponse, +) +from .beta_code_execution_tool_result_block_param import ( + BetaCodeExecutionToolResultBlockParam as BetaCodeExecutionToolResultBlockParam, +) +from .beta_code_execution_tool_result_error_param import ( + BetaCodeExecutionToolResultErrorParam as BetaCodeExecutionToolResultErrorParam, +) +from .beta_managed_agents_always_ask_policy_param import ( + BetaManagedAgentsAlwaysAskPolicyParam as BetaManagedAgentsAlwaysAskPolicyParam, +) +from .beta_managed_agents_agent_tool_config_params import ( + BetaManagedAgentsAgentToolConfigParams as BetaManagedAgentsAgentToolConfigParams, +) +from .beta_managed_agents_custom_tool_input_schema import ( + BetaManagedAgentsCustomToolInputSchema as BetaManagedAgentsCustomToolInputSchema, +) +from .beta_request_mcp_server_url_definition_param import ( + BetaRequestMCPServerURLDefinitionParam as BetaRequestMCPServerURLDefinitionParam, +) +from .beta_web_fetch_tool_result_error_block_param import ( + BetaWebFetchToolResultErrorBlockParam as BetaWebFetchToolResultErrorBlockParam, +) +from .beta_webhook_session_status_idled_event_data import ( + BetaWebhookSessionStatusIdledEventData as BetaWebhookSessionStatusIdledEventData, +) +from .beta_webhook_session_thread_idled_event_data import ( + BetaWebhookSessionThreadIdledEventData as BetaWebhookSessionThreadIdledEventData, +) +from .beta_code_execution_tool_result_block_content import ( + BetaCodeExecutionToolResultBlockContent as BetaCodeExecutionToolResultBlockContent, +) +from .beta_count_tokens_context_management_response import ( + BetaCountTokensContextManagementResponse as BetaCountTokensContextManagementResponse, +) +from .beta_managed_agents_always_allow_policy_param import ( + BetaManagedAgentsAlwaysAllowPolicyParam as BetaManagedAgentsAlwaysAllowPolicyParam, +) +from .beta_managed_agents_mcp_server_url_definition import ( + BetaManagedAgentsMCPServerURLDefinition as BetaManagedAgentsMCPServerURLDefinition, +) +from .beta_memory_tool_20250818_str_replace_command import ( + BetaMemoryTool20250818StrReplaceCommand as BetaMemoryTool20250818StrReplaceCommand, +) +from .beta_citation_web_search_result_location_param import ( + BetaCitationWebSearchResultLocationParam as BetaCitationWebSearchResultLocationParam, +) +from .beta_managed_agents_mcp_toolset_default_config import ( + BetaManagedAgentsMCPToolsetDefaultConfig as BetaManagedAgentsMCPToolsetDefaultConfig, +) +from .beta_webhook_session_thread_created_event_data import ( + BetaWebhookSessionThreadCreatedEventData as BetaWebhookSessionThreadCreatedEventData, +) +from .beta_managed_agents_memory_store_resource_param import ( + BetaManagedAgentsMemoryStoreResourceParam as BetaManagedAgentsMemoryStoreResourceParam, +) +from .beta_managed_agents_outcome_evaluation_resource import ( + BetaManagedAgentsOutcomeEvaluationResource as BetaManagedAgentsOutcomeEvaluationResource, +) +from .beta_tool_search_tool_search_result_block_param import ( + BetaToolSearchToolSearchResultBlockParam as BetaToolSearchToolSearchResultBlockParam, +) +from .beta_webhook_session_requires_action_event_data import ( + BetaWebhookSessionRequiresActionEventData as BetaWebhookSessionRequiresActionEventData, +) +from .beta_bash_code_execution_tool_result_block_param import ( + BetaBashCodeExecutionToolResultBlockParam as BetaBashCodeExecutionToolResultBlockParam, +) +from .beta_bash_code_execution_tool_result_error_param import ( + BetaBashCodeExecutionToolResultErrorParam as BetaBashCodeExecutionToolResultErrorParam, +) +from .beta_encrypted_code_execution_result_block_param import ( + BetaEncryptedCodeExecutionResultBlockParam as BetaEncryptedCodeExecutionResultBlockParam, +) +from .beta_managed_agents_agent_toolset20260401_params import ( + BetaManagedAgentsAgentToolset20260401Params as BetaManagedAgentsAgentToolset20260401Params, +) +from .beta_managed_agents_agent_toolset_default_config import ( + BetaManagedAgentsAgentToolsetDefaultConfig as BetaManagedAgentsAgentToolsetDefaultConfig, +) +from .beta_request_mcp_server_tool_configuration_param import ( + BetaRequestMCPServerToolConfigurationParam as BetaRequestMCPServerToolConfigurationParam, +) +from .beta_webhook_vault_credential_created_event_data import ( + BetaWebhookVaultCredentialCreatedEventData as BetaWebhookVaultCredentialCreatedEventData, +) +from .beta_webhook_vault_credential_deleted_event_data import ( + BetaWebhookVaultCredentialDeletedEventData as BetaWebhookVaultCredentialDeletedEventData, +) +from .beta_text_editor_code_execution_tool_result_block import ( + BetaTextEditorCodeExecutionToolResultBlock as BetaTextEditorCodeExecutionToolResultBlock, +) +from .beta_text_editor_code_execution_tool_result_error import ( + BetaTextEditorCodeExecutionToolResultError as BetaTextEditorCodeExecutionToolResultError, +) +from .beta_text_editor_code_execution_view_result_block import ( + BetaTextEditorCodeExecutionViewResultBlock as BetaTextEditorCodeExecutionViewResultBlock, +) +from .beta_webhook_session_status_terminated_event_data import ( + BetaWebhookSessionStatusTerminatedEventData as BetaWebhookSessionStatusTerminatedEventData, +) +from .beta_webhook_session_thread_terminated_event_data import ( + BetaWebhookSessionThreadTerminatedEventData as BetaWebhookSessionThreadTerminatedEventData, +) +from .beta_webhook_vault_credential_archived_event_data import ( + BetaWebhookVaultCredentialArchivedEventData as BetaWebhookVaultCredentialArchivedEventData, +) +from .beta_managed_agents_custom_tool_input_schema_param import ( + BetaManagedAgentsCustomToolInputSchemaParam as BetaManagedAgentsCustomToolInputSchemaParam, +) +from .beta_managed_agents_multiagent_roster_entry_params import ( + BetaManagedAgentsMultiagentRosterEntryParams as BetaManagedAgentsMultiagentRosterEntryParams, +) +from .beta_managed_agents_session_multiagent_coordinator import ( + BetaManagedAgentsSessionMultiagentCoordinator as BetaManagedAgentsSessionMultiagentCoordinator, +) +from .beta_webhook_session_status_rescheduled_event_data import ( + BetaWebhookSessionStatusRescheduledEventData as BetaWebhookSessionStatusRescheduledEventData, +) +from .beta_webhook_session_status_run_started_event_data import ( + BetaWebhookSessionStatusRunStartedEventData as BetaWebhookSessionStatusRunStartedEventData, +) +from .beta_text_editor_code_execution_create_result_block import ( + BetaTextEditorCodeExecutionCreateResultBlock as BetaTextEditorCodeExecutionCreateResultBlock, +) +from .beta_managed_agents_github_repository_resource_params import ( + BetaManagedAgentsGitHubRepositoryResourceParams as BetaManagedAgentsGitHubRepositoryResourceParams, +) +from .beta_managed_agents_mcp_toolset_default_config_params import ( + BetaManagedAgentsMCPToolsetDefaultConfigParams as BetaManagedAgentsMCPToolsetDefaultConfigParams, +) +from .beta_web_search_tool_result_block_param_content_param import ( + BetaWebSearchToolResultBlockParamContentParam as BetaWebSearchToolResultBlockParamContentParam, +) +from .beta_managed_agents_agent_toolset_default_config_params import ( + BetaManagedAgentsAgentToolsetDefaultConfigParams as BetaManagedAgentsAgentToolsetDefaultConfigParams, +) +from .beta_text_editor_code_execution_tool_result_block_param import ( + BetaTextEditorCodeExecutionToolResultBlockParam as BetaTextEditorCodeExecutionToolResultBlockParam, +) +from .beta_text_editor_code_execution_tool_result_error_param import ( + BetaTextEditorCodeExecutionToolResultErrorParam as BetaTextEditorCodeExecutionToolResultErrorParam, +) +from .beta_text_editor_code_execution_view_result_block_param import ( + BetaTextEditorCodeExecutionViewResultBlockParam as BetaTextEditorCodeExecutionViewResultBlockParam, +) +from .beta_webhook_vault_credential_refresh_failed_event_data import ( + BetaWebhookVaultCredentialRefreshFailedEventData as BetaWebhookVaultCredentialRefreshFailedEventData, +) +from .beta_text_editor_code_execution_str_replace_result_block import ( + BetaTextEditorCodeExecutionStrReplaceResultBlock as BetaTextEditorCodeExecutionStrReplaceResultBlock, +) +from .beta_webhook_session_outcome_evaluation_ended_event_data import ( + BetaWebhookSessionOutcomeEvaluationEndedEventData as BetaWebhookSessionOutcomeEvaluationEndedEventData, +) +from .beta_code_execution_tool_result_block_param_content_param import ( + BetaCodeExecutionToolResultBlockParamContentParam as BetaCodeExecutionToolResultBlockParamContentParam, +) +from .beta_text_editor_code_execution_create_result_block_param import ( + BetaTextEditorCodeExecutionCreateResultBlockParam as BetaTextEditorCodeExecutionCreateResultBlockParam, +) +from .beta_text_editor_code_execution_str_replace_result_block_param import ( + BetaTextEditorCodeExecutionStrReplaceResultBlockParam as BetaTextEditorCodeExecutionStrReplaceResultBlockParam, +) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agent_create_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agent_create_params.py new file mode 100644 index 0000000000000000000000000000000000000000..622a3d691ab93b2553349e5581c744d140be22d7 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agent_create_params.py @@ -0,0 +1,76 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Union, Iterable, Optional +from typing_extensions import Required, Annotated, TypeAlias, TypedDict + +from ..._utils import PropertyInfo +from ..anthropic_beta_param import AnthropicBetaParam +from .beta_managed_agents_model_param import BetaManagedAgentsModelParam +from .beta_managed_agents_skill_params import BetaManagedAgentsSkillParams +from .beta_managed_agents_multiagent_params import BetaManagedAgentsMultiagentParams +from .beta_managed_agents_custom_tool_params import BetaManagedAgentsCustomToolParams +from .beta_managed_agents_mcp_toolset_params import BetaManagedAgentsMCPToolsetParams +from .beta_managed_agents_model_config_params import BetaManagedAgentsModelConfigParams +from .beta_managed_agents_url_mcp_server_params import BetaManagedAgentsURLMCPServerParams +from .beta_managed_agents_agent_toolset20260401_params import BetaManagedAgentsAgentToolset20260401Params + +__all__ = ["AgentCreateParams", "Model", "Tool"] + + +class AgentCreateParams(TypedDict, total=False): + model: Required[Model] + """Model identifier. + + Accepts the + [model string](https://platform.claude.com/docs/en/about-claude/models/overview#latest-models-comparison), + e.g. `claude-opus-4-6`, or a `model_config` object for additional configuration + control + """ + + name: Required[str] + """Human-readable name for the agent. 1-256 characters.""" + + description: Optional[str] + """Description of what the agent does. Up to 2048 characters.""" + + mcp_servers: Iterable[BetaManagedAgentsURLMCPServerParams] + """MCP servers this agent connects to. + + Maximum 20. Names must be unique within the array. + """ + + metadata: Dict[str, str] + """Arbitrary key-value metadata. + + Maximum 16 pairs, keys up to 64 chars, values up to 512 chars. + """ + + multiagent: Optional[BetaManagedAgentsMultiagentParams] + """ + A coordinator topology: the session's primary thread orchestrates work by + spawning session threads, each running an agent drawn from the `agents` roster. + """ + + skills: Iterable[BetaManagedAgentsSkillParams] + """Skills available to the agent. Maximum 20.""" + + system: Optional[str] + """System prompt for the agent. Up to 100,000 characters.""" + + tools: Iterable[Tool] + """Tool configurations available to the agent. + + Maximum of 128 tools across all toolsets allowed. + """ + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" + + +Model: TypeAlias = Union[BetaManagedAgentsModelParam, BetaManagedAgentsModelConfigParams] + +Tool: TypeAlias = Union[ + BetaManagedAgentsAgentToolset20260401Params, BetaManagedAgentsMCPToolsetParams, BetaManagedAgentsCustomToolParams +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agent_list_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agent_list_params.py new file mode 100644 index 0000000000000000000000000000000000000000..b29541757fae02d788b4389561961740bcda4d29 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agent_list_params.py @@ -0,0 +1,32 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union +from datetime import datetime +from typing_extensions import Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..anthropic_beta_param import AnthropicBetaParam + +__all__ = ["AgentListParams"] + + +class AgentListParams(TypedDict, total=False): + created_at_gte: Annotated[Union[str, datetime], PropertyInfo(alias="created_at[gte]", format="iso8601")] + """Return agents created at or after this time (inclusive).""" + + created_at_lte: Annotated[Union[str, datetime], PropertyInfo(alias="created_at[lte]", format="iso8601")] + """Return agents created at or before this time (inclusive).""" + + include_archived: bool + """Include archived agents in results. Defaults to false.""" + + limit: int + """Maximum results per page. Default 20, maximum 100.""" + + page: str + """Opaque pagination cursor from a previous response.""" + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agent_retrieve_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agent_retrieve_params.py new file mode 100644 index 0000000000000000000000000000000000000000..037de9686e58f4989cdfe0fb4e8c29411b93aa19 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agent_retrieve_params.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List +from typing_extensions import Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..anthropic_beta_param import AnthropicBetaParam + +__all__ = ["AgentRetrieveParams"] + + +class AgentRetrieveParams(TypedDict, total=False): + version: int + """Agent version. + + Omit for the most recent version. Must be at least 1 if specified. + """ + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agent_update_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agent_update_params.py new file mode 100644 index 0000000000000000000000000000000000000000..b1b4e2aa1d01050525fa5cff895099af8a9501dc --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agent_update_params.py @@ -0,0 +1,97 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Union, Iterable, Optional +from typing_extensions import Required, Annotated, TypeAlias, TypedDict + +from ..._utils import PropertyInfo +from ..anthropic_beta_param import AnthropicBetaParam +from .beta_managed_agents_model_param import BetaManagedAgentsModelParam +from .beta_managed_agents_skill_params import BetaManagedAgentsSkillParams +from .beta_managed_agents_multiagent_params import BetaManagedAgentsMultiagentParams +from .beta_managed_agents_custom_tool_params import BetaManagedAgentsCustomToolParams +from .beta_managed_agents_mcp_toolset_params import BetaManagedAgentsMCPToolsetParams +from .beta_managed_agents_model_config_params import BetaManagedAgentsModelConfigParams +from .beta_managed_agents_url_mcp_server_params import BetaManagedAgentsURLMCPServerParams +from .beta_managed_agents_agent_toolset20260401_params import BetaManagedAgentsAgentToolset20260401Params + +__all__ = ["AgentUpdateParams", "Model", "Tool"] + + +class AgentUpdateParams(TypedDict, total=False): + version: Required[int] + """The agent's current version, used to prevent concurrent overwrites. + + Obtain this value from a create or retrieve response. The request fails if this + does not match the server's current version. + """ + + description: Optional[str] + """Description. + + Up to 2048 characters. Omit to preserve; send empty string or null to clear. + """ + + mcp_servers: Optional[Iterable[BetaManagedAgentsURLMCPServerParams]] + """MCP servers. + + Full replacement. Omit to preserve; send empty array or null to clear. Names + must be unique. Maximum 20. + """ + + metadata: Optional[Dict[str, Optional[str]]] + """Metadata patch. + + Set a key to a string to upsert it, or to null to delete it. Omit the field to + preserve. The stored bag is limited to 16 keys (up to 64 chars each) with values + up to 512 chars. + """ + + model: Model + """Model identifier. + + Accepts the + [model string](https://platform.claude.com/docs/en/about-claude/models/overview#latest-models-comparison), + e.g. `claude-opus-4-6`, or a `model_config` object for additional configuration + control. Omit to preserve. Cannot be cleared. + """ + + multiagent: Optional[BetaManagedAgentsMultiagentParams] + """ + A coordinator topology: the session's primary thread orchestrates work by + spawning session threads, each running an agent drawn from the `agents` roster. + """ + + name: str + """Human-readable name. 1-256 characters. Omit to preserve. Cannot be cleared.""" + + skills: Optional[Iterable[BetaManagedAgentsSkillParams]] + """Skills. + + Full replacement. Omit to preserve; send empty array or null to clear. + Maximum 20. + """ + + system: Optional[str] + """System prompt. + + Up to 100,000 characters. Omit to preserve; send empty string or null to clear. + """ + + tools: Optional[Iterable[Tool]] + """Tool configurations available to the agent. + + Full replacement. Omit to preserve; send empty array or null to clear. Maximum + of 128 tools across all toolsets allowed. + """ + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" + + +Model: TypeAlias = Union[BetaManagedAgentsModelParam, BetaManagedAgentsModelConfigParams] + +Tool: TypeAlias = Union[ + BetaManagedAgentsAgentToolset20260401Params, BetaManagedAgentsMCPToolsetParams, BetaManagedAgentsCustomToolParams +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agents/__init__.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agents/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..184a387f743bd0c90ac1bf2b49aa8e2ea9ec461c --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agents/__init__.py @@ -0,0 +1,5 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .version_list_params import VersionListParams as VersionListParams diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agents/__pycache__/__init__.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agents/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6125cb1bcae9d1c1fa95afc9ac4fbccf4fe7d75d Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agents/__pycache__/__init__.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agents/__pycache__/version_list_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agents/__pycache__/version_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f686cc2bc324ae1a91fda7f4572bdbe9e8654e9 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agents/__pycache__/version_list_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agents/version_list_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agents/version_list_params.py new file mode 100644 index 0000000000000000000000000000000000000000..29fc95421a767c91de2e5404ad1fea645be768a1 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/agents/version_list_params.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List +from typing_extensions import Annotated, TypedDict + +from ...._utils import PropertyInfo +from ...anthropic_beta_param import AnthropicBetaParam + +__all__ = ["VersionListParams"] + + +class VersionListParams(TypedDict, total=False): + limit: int + """Maximum results per page. Default 20, maximum 100.""" + + page: str + """Opaque pagination cursor.""" + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_redacted_result_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_redacted_result_block.py new file mode 100644 index 0000000000000000000000000000000000000000..62696c4ba546d6c03069622ddcdbb7513d552176 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_redacted_result_block.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaAdvisorRedactedResultBlock"] + + +class BetaAdvisorRedactedResultBlock(BaseModel): + encrypted_content: str + """Opaque blob containing the advisor's output. + + Round-trip verbatim; do not inspect or modify. + """ + + type: Literal["advisor_redacted_result"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_redacted_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_redacted_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..0c1cfcada253063bd2c5ffb14d0b016ef0445300 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_redacted_result_block_param.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaAdvisorRedactedResultBlockParam"] + + +class BetaAdvisorRedactedResultBlockParam(TypedDict, total=False): + encrypted_content: Required[str] + """Opaque blob produced by a prior response; must be round-tripped verbatim.""" + + type: Required[Literal["advisor_redacted_result"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_result_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_result_block.py new file mode 100644 index 0000000000000000000000000000000000000000..9f702ec30c35afa833b34a6b8d19a7d48ebd2cf1 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_result_block.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaAdvisorResultBlock"] + + +class BetaAdvisorResultBlock(BaseModel): + text: str + + type: Literal["advisor_result"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..4500eec910c2143e967b945a0e97b5317a1511f3 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_result_block_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaAdvisorResultBlockParam"] + + +class BetaAdvisorResultBlockParam(TypedDict, total=False): + text: Required[str] + + type: Required[Literal["advisor_result"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_tool_result_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_tool_result_block.py new file mode 100644 index 0000000000000000000000000000000000000000..196d476634773bb62ac588cc8adf8e25d3b415d9 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_tool_result_block.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Literal, TypeAlias + +from ..._models import BaseModel +from .beta_advisor_result_block import BetaAdvisorResultBlock +from .beta_advisor_tool_result_error import BetaAdvisorToolResultError +from .beta_advisor_redacted_result_block import BetaAdvisorRedactedResultBlock + +__all__ = ["BetaAdvisorToolResultBlock", "Content"] + +Content: TypeAlias = Union[BetaAdvisorToolResultError, BetaAdvisorResultBlock, BetaAdvisorRedactedResultBlock] + + +class BetaAdvisorToolResultBlock(BaseModel): + content: Content + + tool_use_id: str + + type: Literal["advisor_tool_result"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_tool_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_tool_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..a5b702b243428bcf34905c46734130202168e78e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_tool_result_block_param.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .beta_advisor_result_block_param import BetaAdvisorResultBlockParam +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam +from .beta_advisor_tool_result_error_param import BetaAdvisorToolResultErrorParam +from .beta_advisor_redacted_result_block_param import BetaAdvisorRedactedResultBlockParam + +__all__ = ["BetaAdvisorToolResultBlockParam", "Content"] + +Content: TypeAlias = Union[ + BetaAdvisorToolResultErrorParam, BetaAdvisorResultBlockParam, BetaAdvisorRedactedResultBlockParam +] + + +class BetaAdvisorToolResultBlockParam(TypedDict, total=False): + content: Required[Content] + + tool_use_id: Required[str] + + type: Required[Literal["advisor_tool_result"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_tool_result_error.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_tool_result_error.py new file mode 100644 index 0000000000000000000000000000000000000000..d317615fe0b54be70194c64436994180d9512baf --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_tool_result_error.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaAdvisorToolResultError"] + + +class BetaAdvisorToolResultError(BaseModel): + error_code: Literal[ + "max_uses_exceeded", + "prompt_too_long", + "too_many_requests", + "overloaded", + "unavailable", + "execution_time_exceeded", + ] + + type: Literal["advisor_tool_result_error"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_tool_result_error_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_tool_result_error_param.py new file mode 100644 index 0000000000000000000000000000000000000000..e64f87b3bdeee1e25f21988e39d70658e5dc42c1 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_advisor_tool_result_error_param.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaAdvisorToolResultErrorParam"] + + +class BetaAdvisorToolResultErrorParam(TypedDict, total=False): + error_code: Required[ + Literal[ + "max_uses_exceeded", + "prompt_too_long", + "too_many_requests", + "overloaded", + "unavailable", + "execution_time_exceeded", + ] + ] + + type: Required[Literal["advisor_tool_result_error"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_all_thinking_turns_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_all_thinking_turns_param.py new file mode 100644 index 0000000000000000000000000000000000000000..aae4eddc8ae04520f3f0aa7f66697d947457b29d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_all_thinking_turns_param.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaAllThinkingTurnsParam"] + + +class BetaAllThinkingTurnsParam(TypedDict, total=False): + type: Required[Literal["all"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_base64_image_source_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_base64_image_source_param.py new file mode 100644 index 0000000000000000000000000000000000000000..8f13ce3861526156334d8be19167f07366670225 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_base64_image_source_param.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, Required, Annotated, TypedDict + +from ..._types import Base64FileInput +from ..._utils import PropertyInfo +from ..._models import set_pydantic_config + +__all__ = ["BetaBase64ImageSourceParam"] + + +class BetaBase64ImageSourceParam(TypedDict, total=False): + data: Required[Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")]] + + media_type: Required[Literal["image/jpeg", "image/png", "image/gif", "image/webp"]] + + type: Required[Literal["base64"]] + + +set_pydantic_config(BetaBase64ImageSourceParam, {"arbitrary_types_allowed": True}) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_base64_pdf_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_base64_pdf_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..1f6425ac11d04c6b1f346d6527ca73d0fc02a4b9 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_base64_pdf_block_param.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .beta_request_document_block_param import BetaRequestDocumentBlockParam + +BetaBase64PDFBlockParam = BetaRequestDocumentBlockParam diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_base64_pdf_source.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_base64_pdf_source.py new file mode 100644 index 0000000000000000000000000000000000000000..28cf5c565e6b415f99b8fc49eddd843cb2a71cc3 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_base64_pdf_source.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaBase64PDFSource"] + + +class BetaBase64PDFSource(BaseModel): + data: str + + media_type: Literal["application/pdf"] + + type: Literal["base64"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_base64_pdf_source_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_base64_pdf_source_param.py new file mode 100644 index 0000000000000000000000000000000000000000..1137c9575bb00f38c205971c308fe859626ead8f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_base64_pdf_source_param.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, Required, Annotated, TypedDict + +from ..._types import Base64FileInput +from ..._utils import PropertyInfo +from ..._models import set_pydantic_config + +__all__ = ["BetaBase64PDFSourceParam"] + + +class BetaBase64PDFSourceParam(TypedDict, total=False): + data: Required[Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")]] + + media_type: Required[Literal["application/pdf"]] + + type: Required[Literal["base64"]] + + +set_pydantic_config(BetaBase64PDFSourceParam, {"arbitrary_types_allowed": True}) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_output_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_output_block.py new file mode 100644 index 0000000000000000000000000000000000000000..958b91eab18c73480428b699671c89be0a7cdb76 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_output_block.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaBashCodeExecutionOutputBlock"] + + +class BetaBashCodeExecutionOutputBlock(BaseModel): + file_id: str + + type: Literal["bash_code_execution_output"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_output_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_output_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..2d4fc5401a5506e0177a0d428f1a02ef800f667a --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_output_block_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaBashCodeExecutionOutputBlockParam"] + + +class BetaBashCodeExecutionOutputBlockParam(TypedDict, total=False): + file_id: Required[str] + + type: Required[Literal["bash_code_execution_output"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_result_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_result_block.py new file mode 100644 index 0000000000000000000000000000000000000000..f92174714e6ab8e973bd9655815fae9b8154e51c --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_result_block.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_bash_code_execution_output_block import BetaBashCodeExecutionOutputBlock + +__all__ = ["BetaBashCodeExecutionResultBlock"] + + +class BetaBashCodeExecutionResultBlock(BaseModel): + content: List[BetaBashCodeExecutionOutputBlock] + + return_code: int + + stderr: str + + stdout: str + + type: Literal["bash_code_execution_result"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..af21582425557f2a070e7a482c9ee65d0ad4e18d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_result_block_param.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Literal, Required, TypedDict + +from .beta_bash_code_execution_output_block_param import BetaBashCodeExecutionOutputBlockParam + +__all__ = ["BetaBashCodeExecutionResultBlockParam"] + + +class BetaBashCodeExecutionResultBlockParam(TypedDict, total=False): + content: Required[Iterable[BetaBashCodeExecutionOutputBlockParam]] + + return_code: Required[int] + + stderr: Required[str] + + stdout: Required[str] + + type: Required[Literal["bash_code_execution_result"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_tool_result_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_tool_result_block.py new file mode 100644 index 0000000000000000000000000000000000000000..c117cadd7fecc35089fda91623abba459c767d52 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_tool_result_block.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Literal, TypeAlias + +from ..._models import BaseModel +from .beta_bash_code_execution_result_block import BetaBashCodeExecutionResultBlock +from .beta_bash_code_execution_tool_result_error import BetaBashCodeExecutionToolResultError + +__all__ = ["BetaBashCodeExecutionToolResultBlock", "Content"] + +Content: TypeAlias = Union[BetaBashCodeExecutionToolResultError, BetaBashCodeExecutionResultBlock] + + +class BetaBashCodeExecutionToolResultBlock(BaseModel): + content: Content + + tool_use_id: str + + type: Literal["bash_code_execution_tool_result"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_tool_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_tool_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..dc22c5461ff0e984606f29242150b4f371c870eb --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_tool_result_block_param.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam +from .beta_bash_code_execution_result_block_param import BetaBashCodeExecutionResultBlockParam +from .beta_bash_code_execution_tool_result_error_param import BetaBashCodeExecutionToolResultErrorParam + +__all__ = ["BetaBashCodeExecutionToolResultBlockParam", "Content"] + +Content: TypeAlias = Union[BetaBashCodeExecutionToolResultErrorParam, BetaBashCodeExecutionResultBlockParam] + + +class BetaBashCodeExecutionToolResultBlockParam(TypedDict, total=False): + content: Required[Content] + + tool_use_id: Required[str] + + type: Required[Literal["bash_code_execution_tool_result"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_tool_result_error.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_tool_result_error.py new file mode 100644 index 0000000000000000000000000000000000000000..3a0c3a2530149bffb1d866377c843b5f7a40f8a1 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_tool_result_error.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaBashCodeExecutionToolResultError"] + + +class BetaBashCodeExecutionToolResultError(BaseModel): + error_code: Literal[ + "invalid_tool_input", "unavailable", "too_many_requests", "execution_time_exceeded", "output_file_too_large" + ] + + type: Literal["bash_code_execution_tool_result_error"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_tool_result_error_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_tool_result_error_param.py new file mode 100644 index 0000000000000000000000000000000000000000..33569d34419aee48419d59709a387bc9728ede11 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_bash_code_execution_tool_result_error_param.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaBashCodeExecutionToolResultErrorParam"] + + +class BetaBashCodeExecutionToolResultErrorParam(TypedDict, total=False): + error_code: Required[ + Literal[ + "invalid_tool_input", "unavailable", "too_many_requests", "execution_time_exceeded", "output_file_too_large" + ] + ] + + type: Required[Literal["bash_code_execution_tool_result_error"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_cache_control_ephemeral_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_cache_control_ephemeral_param.py new file mode 100644 index 0000000000000000000000000000000000000000..221a9f76cbd4ab7176016694aa3e0488068a0790 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_cache_control_ephemeral_param.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaCacheControlEphemeralParam"] + + +class BetaCacheControlEphemeralParam(TypedDict, total=False): + type: Required[Literal["ephemeral"]] + + ttl: Literal["5m", "1h"] + """The time-to-live for the cache control breakpoint. + + This may be one the following values: + + - `5m`: 5 minutes + - `1h`: 1 hour + + Defaults to `5m`. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_cache_creation.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_cache_creation.py new file mode 100644 index 0000000000000000000000000000000000000000..366fc8e1533dc6b94666ea0102a1ea3b7dee958f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_cache_creation.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["BetaCacheCreation"] + + +class BetaCacheCreation(BaseModel): + ephemeral_1h_input_tokens: int + """The number of input tokens used to create the 1 hour cache entry.""" + + ephemeral_5m_input_tokens: int + """The number of input tokens used to create the 5 minute cache entry.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_capability_support.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_capability_support.py new file mode 100644 index 0000000000000000000000000000000000000000..ed45c3536f5d38136bc0461f92e5c77b352b3922 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_capability_support.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["BetaCapabilitySupport"] + + +class BetaCapabilitySupport(BaseModel): + """Indicates whether a capability is supported.""" + + supported: bool + """Whether this capability is supported by the model.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citation_char_location.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citation_char_location.py new file mode 100644 index 0000000000000000000000000000000000000000..8efb8527a44b09f4e38f622bb370d669ae63ab51 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citation_char_location.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaCitationCharLocation"] + + +class BetaCitationCharLocation(BaseModel): + cited_text: str + + document_index: int + + document_title: Optional[str] = None + + end_char_index: int + + file_id: Optional[str] = None + + start_char_index: int + + type: Literal["char_location"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citation_config.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citation_config.py new file mode 100644 index 0000000000000000000000000000000000000000..8e949bd05ddfaa17412f6d8965fb1d98da20dc30 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citation_config.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["BetaCitationConfig"] + + +class BetaCitationConfig(BaseModel): + enabled: bool diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citation_content_block_location_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citation_content_block_location_param.py new file mode 100644 index 0000000000000000000000000000000000000000..226aeb3d68798968e1e666b2de49456377c5e290 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citation_content_block_location_param.py @@ -0,0 +1,37 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaCitationContentBlockLocationParam"] + + +class BetaCitationContentBlockLocationParam(TypedDict, total=False): + cited_text: Required[str] + """The full text of the cited block range, concatenated. + + Always equals the contents of `content[start_block_index:end_block_index]` + joined together. The text block is the minimal citable unit; this field is never + a substring of a single block. Not counted toward output tokens, and not counted + toward input tokens when sent back in subsequent turns. + """ + + document_index: Required[int] + + document_title: Required[Optional[str]] + + end_block_index: Required[int] + """ + Exclusive 0-based end index of the cited block range in the source's `content` + array. + + Always greater than `start_block_index`; a single-block citation has + `end_block_index = start_block_index + 1`. + """ + + start_block_index: Required[int] + """0-based index of the first cited block in the source's `content` array.""" + + type: Required[Literal["content_block_location"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citation_page_location_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citation_page_location_param.py new file mode 100644 index 0000000000000000000000000000000000000000..60e5b1c209a66b8e01419a505d3754b89a409ff2 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citation_page_location_param.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaCitationPageLocationParam"] + + +class BetaCitationPageLocationParam(TypedDict, total=False): + cited_text: Required[str] + + document_index: Required[int] + + document_title: Required[Optional[str]] + + end_page_number: Required[int] + + start_page_number: Required[int] + + type: Required[Literal["page_location"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citation_search_result_location.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citation_search_result_location.py new file mode 100644 index 0000000000000000000000000000000000000000..8bc45aa45ac1b4f9fc5b1bf2ac310e96b51119c4 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citation_search_result_location.py @@ -0,0 +1,47 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaCitationSearchResultLocation"] + + +class BetaCitationSearchResultLocation(BaseModel): + cited_text: str + """The full text of the cited block range, concatenated. + + Always equals the contents of `content[start_block_index:end_block_index]` + joined together. The text block is the minimal citable unit; this field is never + a substring of a single block. Not counted toward output tokens, and not counted + toward input tokens when sent back in subsequent turns. + """ + + end_block_index: int + """ + Exclusive 0-based end index of the cited block range in the source's `content` + array. + + Always greater than `start_block_index`; a single-block citation has + `end_block_index = start_block_index + 1`. + """ + + search_result_index: int + """ + 0-based index of the cited search result among all `search_result` content + blocks in the request, in the order they appear across messages and tool + results. + + Counted separately from `document_index`; server-side web search results are not + included in this count. + """ + + source: str + + start_block_index: int + """0-based index of the first cited block in the source's `content` array.""" + + title: Optional[str] = None + + type: Literal["search_result_location"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citation_search_result_location_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citation_search_result_location_param.py new file mode 100644 index 0000000000000000000000000000000000000000..0d6cc665bd22bf97bb20051fba9626bb774535f3 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citation_search_result_location_param.py @@ -0,0 +1,47 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaCitationSearchResultLocationParam"] + + +class BetaCitationSearchResultLocationParam(TypedDict, total=False): + cited_text: Required[str] + """The full text of the cited block range, concatenated. + + Always equals the contents of `content[start_block_index:end_block_index]` + joined together. The text block is the minimal citable unit; this field is never + a substring of a single block. Not counted toward output tokens, and not counted + toward input tokens when sent back in subsequent turns. + """ + + end_block_index: Required[int] + """ + Exclusive 0-based end index of the cited block range in the source's `content` + array. + + Always greater than `start_block_index`; a single-block citation has + `end_block_index = start_block_index + 1`. + """ + + search_result_index: Required[int] + """ + 0-based index of the cited search result among all `search_result` content + blocks in the request, in the order they appear across messages and tool + results. + + Counted separately from `document_index`; server-side web search results are not + included in this count. + """ + + source: Required[str] + + start_block_index: Required[int] + """0-based index of the first cited block in the source's `content` array.""" + + title: Required[Optional[str]] + + type: Required[Literal["search_result_location"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citation_web_search_result_location_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citation_web_search_result_location_param.py new file mode 100644 index 0000000000000000000000000000000000000000..90625af1b7614a87e9ab398817f5d2074fd32869 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citation_web_search_result_location_param.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaCitationWebSearchResultLocationParam"] + + +class BetaCitationWebSearchResultLocationParam(TypedDict, total=False): + cited_text: Required[str] + + encrypted_index: Required[str] + + title: Required[Optional[str]] + + type: Required[Literal["web_search_result_location"]] + + url: Required[str] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citations_config_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citations_config_param.py new file mode 100644 index 0000000000000000000000000000000000000000..409cfde70f8410bd3eca2ed76685fa503e47f7f4 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citations_config_param.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["BetaCitationsConfigParam"] + + +class BetaCitationsConfigParam(TypedDict, total=False): + enabled: bool diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citations_web_search_result_location.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citations_web_search_result_location.py new file mode 100644 index 0000000000000000000000000000000000000000..111ffe7c02b381aaa8c872422b72d4f520d1b5f1 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_citations_web_search_result_location.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaCitationsWebSearchResultLocation"] + + +class BetaCitationsWebSearchResultLocation(BaseModel): + cited_text: str + + encrypted_index: str + + title: Optional[str] = None + + type: Literal["web_search_result_location"] + + url: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_clear_thinking_20251015_edit_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_clear_thinking_20251015_edit_param.py new file mode 100644 index 0000000000000000000000000000000000000000..a711c723d36ac553a0cdd4487ec7b2914ffc57a6 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_clear_thinking_20251015_edit_param.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .beta_thinking_turns_param import BetaThinkingTurnsParam +from .beta_all_thinking_turns_param import BetaAllThinkingTurnsParam + +__all__ = ["BetaClearThinking20251015EditParam", "Keep"] + +Keep: TypeAlias = Union[BetaThinkingTurnsParam, BetaAllThinkingTurnsParam, Literal["all"]] + + +class BetaClearThinking20251015EditParam(TypedDict, total=False): + type: Required[Literal["clear_thinking_20251015"]] + + keep: Keep + """Number of most recent assistant turns to keep thinking blocks for. + + Older turns will have their thinking blocks removed. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_clear_thinking_20251015_edit_response.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_clear_thinking_20251015_edit_response.py new file mode 100644 index 0000000000000000000000000000000000000000..08d174b55085f7c446940ead563ac6e72a2f898d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_clear_thinking_20251015_edit_response.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaClearThinking20251015EditResponse"] + + +class BetaClearThinking20251015EditResponse(BaseModel): + cleared_input_tokens: int + """Number of input tokens cleared by this edit.""" + + cleared_thinking_turns: int + """Number of thinking turns that were cleared.""" + + type: Literal["clear_thinking_20251015"] + """The type of context management edit applied.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_clear_tool_uses_20250919_edit_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_clear_tool_uses_20250919_edit_param.py new file mode 100644 index 0000000000000000000000000000000000000000..64b901f67f17ef692d1b646d852f0752d9636042 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_clear_tool_uses_20250919_edit_param.py @@ -0,0 +1,38 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from ..._types import SequenceNotStr +from .beta_tool_uses_keep_param import BetaToolUsesKeepParam +from .beta_tool_uses_trigger_param import BetaToolUsesTriggerParam +from .beta_input_tokens_trigger_param import BetaInputTokensTriggerParam +from .beta_input_tokens_clear_at_least_param import BetaInputTokensClearAtLeastParam + +__all__ = ["BetaClearToolUses20250919EditParam", "Trigger"] + +Trigger: TypeAlias = Union[BetaInputTokensTriggerParam, BetaToolUsesTriggerParam] + + +class BetaClearToolUses20250919EditParam(TypedDict, total=False): + type: Required[Literal["clear_tool_uses_20250919"]] + + clear_at_least: Optional[BetaInputTokensClearAtLeastParam] + """Minimum number of tokens that must be cleared when triggered. + + Context will only be modified if at least this many tokens can be removed. + """ + + clear_tool_inputs: Union[bool, SequenceNotStr[str], None] + """Whether to clear all tool inputs (bool) or specific tool inputs to clear (list)""" + + exclude_tools: Optional[SequenceNotStr[str]] + """Tool names whose uses are preserved from clearing""" + + keep: BetaToolUsesKeepParam + """Number of tool uses to retain in the conversation""" + + trigger: Trigger + """Condition that triggers the context management strategy""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_clear_tool_uses_20250919_edit_response.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_clear_tool_uses_20250919_edit_response.py new file mode 100644 index 0000000000000000000000000000000000000000..42a7dfae8289993ad2e58c5612023fd338af5c8c --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_clear_tool_uses_20250919_edit_response.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaClearToolUses20250919EditResponse"] + + +class BetaClearToolUses20250919EditResponse(BaseModel): + cleared_input_tokens: int + """Number of input tokens cleared by this edit.""" + + cleared_tool_uses: int + """Number of tool uses that were cleared.""" + + type: Literal["clear_tool_uses_20250919"] + """The type of context management edit applied.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_cloud_config.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_cloud_config.py new file mode 100644 index 0000000000000000000000000000000000000000..beaa6a03845cc53f31fdc5c2a0f7f1a40990c199 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_cloud_config.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Literal, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .beta_packages import BetaPackages +from .beta_limited_network import BetaLimitedNetwork +from .beta_unrestricted_network import BetaUnrestrictedNetwork + +__all__ = ["BetaCloudConfig", "Networking"] + +Networking: TypeAlias = Annotated[ + Union[BetaUnrestrictedNetwork, BetaLimitedNetwork], PropertyInfo(discriminator="type") +] + + +class BetaCloudConfig(BaseModel): + """`cloud` environment configuration.""" + + networking: Networking + """Network configuration policy.""" + + packages: BetaPackages + """Package manager configuration.""" + + type: Literal["cloud"] + """Environment type""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_cloud_config_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_cloud_config_params.py new file mode 100644 index 0000000000000000000000000000000000000000..40cd40785448ad9a8ae702a15e6ea591e0a18879 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_cloud_config_params.py @@ -0,0 +1,36 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .beta_packages_params import BetaPackagesParams +from .beta_limited_network_params import BetaLimitedNetworkParams +from .beta_unrestricted_network_param import BetaUnrestrictedNetworkParam + +__all__ = ["BetaCloudConfigParams", "Networking"] + +Networking: TypeAlias = Union[BetaUnrestrictedNetworkParam, BetaLimitedNetworkParams] + + +class BetaCloudConfigParams(TypedDict, total=False): + """Request params for `cloud` environment configuration. + + Fields default to null; on update, omitted fields preserve the + existing value. + """ + + type: Required[Literal["cloud"]] + """Environment type""" + + networking: Optional[Networking] + """Network configuration policy. Omit on update to preserve the existing value.""" + + packages: Optional[BetaPackagesParams] + """Specify packages (and optionally their versions) available in this environment. + + When versioning, use the version semantics relevant for the package manager, + e.g. for `pip` use `package==1.0.0`. You are responsible for validating the + package and version exist. Unversioned installs the latest. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_output_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_output_block.py new file mode 100644 index 0000000000000000000000000000000000000000..6f02c3ee566559c95cc625461597f5f1198878ec --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_output_block.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaCodeExecutionOutputBlock"] + + +class BetaCodeExecutionOutputBlock(BaseModel): + file_id: str + + type: Literal["code_execution_output"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_output_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_output_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..35a6293c1e6f7229983e85fdf7fa95025fddde37 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_output_block_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaCodeExecutionOutputBlockParam"] + + +class BetaCodeExecutionOutputBlockParam(TypedDict, total=False): + file_id: Required[str] + + type: Required[Literal["code_execution_output"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_result_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_result_block.py new file mode 100644 index 0000000000000000000000000000000000000000..be7a60b239024b1cbdd6740f125a7b0ec31d4b0c --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_result_block.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_code_execution_output_block import BetaCodeExecutionOutputBlock + +__all__ = ["BetaCodeExecutionResultBlock"] + + +class BetaCodeExecutionResultBlock(BaseModel): + content: List[BetaCodeExecutionOutputBlock] + + return_code: int + + stderr: str + + stdout: str + + type: Literal["code_execution_result"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_20250522_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_20250522_param.py new file mode 100644 index 0000000000000000000000000000000000000000..1683a2572390a85d1b6550c7f5420d81727c50fd --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_20250522_param.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaCodeExecutionTool20250522Param"] + + +class BetaCodeExecutionTool20250522Param(TypedDict, total=False): + name: Required[Literal["code_execution"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["code_execution_20250522"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_20250825_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_20250825_param.py new file mode 100644 index 0000000000000000000000000000000000000000..053c44236bc71dc9145d9f35ea6647bb8ba48691 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_20250825_param.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaCodeExecutionTool20250825Param"] + + +class BetaCodeExecutionTool20250825Param(TypedDict, total=False): + name: Required[Literal["code_execution"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["code_execution_20250825"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_20260120_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_20260120_param.py new file mode 100644 index 0000000000000000000000000000000000000000..8d96b1fc9718e2beb60f9f0a4cc4d808b92fea9b --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_20260120_param.py @@ -0,0 +1,38 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaCodeExecutionTool20260120Param"] + + +class BetaCodeExecutionTool20260120Param(TypedDict, total=False): + """ + Code execution tool with REPL state persistence (daemon mode + gVisor checkpoint). + """ + + name: Required[Literal["code_execution"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["code_execution_20260120"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_result_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_result_block.py new file mode 100644 index 0000000000000000000000000000000000000000..141bbc094d1753e0e4038b3080237e488fa6019c --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_result_block.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_code_execution_tool_result_block_content import BetaCodeExecutionToolResultBlockContent + +__all__ = ["BetaCodeExecutionToolResultBlock"] + + +class BetaCodeExecutionToolResultBlock(BaseModel): + content: BetaCodeExecutionToolResultBlockContent + """Code execution result with encrypted stdout for PFC + web_search results.""" + + tool_use_id: str + + type: Literal["code_execution_tool_result"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_result_block_content.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_result_block_content.py new file mode 100644 index 0000000000000000000000000000000000000000..2977a051ccf34508cc4c7ac257c0ff202c01c6bf --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_result_block_content.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import TypeAlias + +from .beta_code_execution_result_block import BetaCodeExecutionResultBlock +from .beta_code_execution_tool_result_error import BetaCodeExecutionToolResultError +from .beta_encrypted_code_execution_result_block import BetaEncryptedCodeExecutionResultBlock + +__all__ = ["BetaCodeExecutionToolResultBlockContent"] + +BetaCodeExecutionToolResultBlockContent: TypeAlias = Union[ + BetaCodeExecutionToolResultError, BetaCodeExecutionResultBlock, BetaEncryptedCodeExecutionResultBlock +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..fdb6a09c1deb473b7888cbeac1fb83f8b4e70e21 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_result_block_param.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam +from .beta_code_execution_tool_result_block_param_content_param import BetaCodeExecutionToolResultBlockParamContentParam + +__all__ = ["BetaCodeExecutionToolResultBlockParam"] + + +class BetaCodeExecutionToolResultBlockParam(TypedDict, total=False): + content: Required[BetaCodeExecutionToolResultBlockParamContentParam] + """Code execution result with encrypted stdout for PFC + web_search results.""" + + tool_use_id: Required[str] + + type: Required[Literal["code_execution_tool_result"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_result_block_param_content_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_result_block_param_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..172969044c941f150818f700f4dddb7780d8bd67 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_result_block_param_content_param.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .beta_code_execution_result_block_param import BetaCodeExecutionResultBlockParam +from .beta_code_execution_tool_result_error_param import BetaCodeExecutionToolResultErrorParam +from .beta_encrypted_code_execution_result_block_param import BetaEncryptedCodeExecutionResultBlockParam + +__all__ = ["BetaCodeExecutionToolResultBlockParamContentParam"] + +BetaCodeExecutionToolResultBlockParamContentParam: TypeAlias = Union[ + BetaCodeExecutionToolResultErrorParam, BetaCodeExecutionResultBlockParam, BetaEncryptedCodeExecutionResultBlockParam +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_result_error_code.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_result_error_code.py new file mode 100644 index 0000000000000000000000000000000000000000..f56326b4383d5bf8fb72cac84d62d3507a119cd9 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_result_error_code.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["BetaCodeExecutionToolResultErrorCode"] + +BetaCodeExecutionToolResultErrorCode: TypeAlias = Literal[ + "invalid_tool_input", "unavailable", "too_many_requests", "execution_time_exceeded" +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_result_error_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_result_error_param.py new file mode 100644 index 0000000000000000000000000000000000000000..cb57a434f67fdcc887219b92ca30f6040f296673 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_code_execution_tool_result_error_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +from .beta_code_execution_tool_result_error_code import BetaCodeExecutionToolResultErrorCode + +__all__ = ["BetaCodeExecutionToolResultErrorParam"] + + +class BetaCodeExecutionToolResultErrorParam(TypedDict, total=False): + error_code: Required[BetaCodeExecutionToolResultErrorCode] + + type: Required[Literal["code_execution_tool_result_error"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_compaction_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_compaction_block.py new file mode 100644 index 0000000000000000000000000000000000000000..53da79fa931634f75f09895d9e7bd98b9c86a416 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_compaction_block.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaCompactionBlock"] + + +class BetaCompactionBlock(BaseModel): + """A compaction block returned when autocompact is triggered. + + When content is None, it indicates the compaction failed to produce a valid + summary (e.g., malformed output from the model). Clients may round-trip + compaction blocks with null content; the server treats them as no-ops. + """ + + content: Optional[str] = None + """Summary of compacted content, or null if compaction failed""" + + encrypted_content: Optional[str] = None + """Opaque metadata from prior compaction, to be round-tripped verbatim""" + + type: Literal["compaction"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_compaction_content_block_delta.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_compaction_content_block_delta.py new file mode 100644 index 0000000000000000000000000000000000000000..84887de9236c4425236a6250fecd01d3416234ed --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_compaction_content_block_delta.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaCompactionContentBlockDelta"] + + +class BetaCompactionContentBlockDelta(BaseModel): + content: Optional[str] = None + + encrypted_content: Optional[str] = None + """Opaque metadata from prior compaction, to be round-tripped verbatim""" + + type: Literal["compaction_delta"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_container.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_container.py new file mode 100644 index 0000000000000000000000000000000000000000..47116abf761af3a72ba67f63564980f47d750b72 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_container.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from datetime import datetime + +from ..._models import BaseModel +from .beta_skill import BetaSkill + +__all__ = ["BetaContainer"] + + +class BetaContainer(BaseModel): + """ + Information about the container used in the request (for the code execution tool) + """ + + id: str + """Identifier for the container used in this request""" + + expires_at: datetime + """The time at which the container will expire.""" + + skills: Optional[List[BetaSkill]] = None + """Skills loaded in the container""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_container_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_container_params.py new file mode 100644 index 0000000000000000000000000000000000000000..58c40dd16ccfa8b72800c94eb2dabfbf76ced4c4 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_container_params.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable, Optional +from typing_extensions import TypedDict + +from .beta_skill_params import BetaSkillParams + +__all__ = ["BetaContainerParams"] + + +class BetaContainerParams(TypedDict, total=False): + """Container parameters with skills to be loaded.""" + + id: Optional[str] + """Container id""" + + skills: Optional[Iterable[BetaSkillParams]] + """List of skills to load in the container""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_container_upload_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_container_upload_block.py new file mode 100644 index 0000000000000000000000000000000000000000..fe2aa2221d3be6938fa1b734e775c5d335a01bf3 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_container_upload_block.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaContainerUploadBlock"] + + +class BetaContainerUploadBlock(BaseModel): + """Response model for a file uploaded to the container.""" + + file_id: str + + type: Literal["container_upload"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_container_upload_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_container_upload_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..b857e11afc9a77a14a7627a1bc9a646dfe5408e2 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_container_upload_block_param.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaContainerUploadBlockParam"] + + +class BetaContainerUploadBlockParam(TypedDict, total=False): + """ + A content block that represents a file to be uploaded to the container + Files uploaded via this block will be available in the container's input directory. + """ + + file_id: Required[str] + + type: Required[Literal["container_upload"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_content_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_content_block.py new file mode 100644 index 0000000000000000000000000000000000000000..5b6b627e8802f7622ba9cdcdcbaa2b0ec2d9890f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_content_block.py @@ -0,0 +1,46 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from ..._utils import PropertyInfo +from .beta_text_block import BetaTextBlock +from .beta_thinking_block import BetaThinkingBlock +from .beta_tool_use_block import BetaToolUseBlock +from .beta_compaction_block import BetaCompactionBlock +from .beta_mcp_tool_use_block import BetaMCPToolUseBlock +from .beta_mcp_tool_result_block import BetaMCPToolResultBlock +from .beta_server_tool_use_block import BetaServerToolUseBlock +from .beta_container_upload_block import BetaContainerUploadBlock +from .beta_redacted_thinking_block import BetaRedactedThinkingBlock +from .beta_advisor_tool_result_block import BetaAdvisorToolResultBlock +from .beta_web_fetch_tool_result_block import BetaWebFetchToolResultBlock +from .beta_web_search_tool_result_block import BetaWebSearchToolResultBlock +from .beta_tool_search_tool_result_block import BetaToolSearchToolResultBlock +from .beta_code_execution_tool_result_block import BetaCodeExecutionToolResultBlock +from .beta_bash_code_execution_tool_result_block import BetaBashCodeExecutionToolResultBlock +from .beta_text_editor_code_execution_tool_result_block import BetaTextEditorCodeExecutionToolResultBlock + +__all__ = ["BetaContentBlock"] + +BetaContentBlock: TypeAlias = Annotated[ + Union[ + BetaTextBlock, + BetaThinkingBlock, + BetaRedactedThinkingBlock, + BetaToolUseBlock, + BetaServerToolUseBlock, + BetaWebSearchToolResultBlock, + BetaWebFetchToolResultBlock, + BetaAdvisorToolResultBlock, + BetaCodeExecutionToolResultBlock, + BetaBashCodeExecutionToolResultBlock, + BetaTextEditorCodeExecutionToolResultBlock, + BetaToolSearchToolResultBlock, + BetaMCPToolUseBlock, + BetaMCPToolResultBlock, + BetaContainerUploadBlock, + BetaCompactionBlock, + ], + PropertyInfo(discriminator="type"), +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_content_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_content_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..9b3f982c84ba995b73f2ddf99ea53d9bfd925a24 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_content_block_param.py @@ -0,0 +1,54 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .beta_content_block import BetaContentBlock +from .beta_text_block_param import BetaTextBlockParam +from .beta_image_block_param import BetaImageBlockParam +from .beta_thinking_block_param import BetaThinkingBlockParam +from .beta_tool_use_block_param import BetaToolUseBlockParam +from .beta_compaction_block_param import BetaCompactionBlockParam +from .beta_tool_result_block_param import BetaToolResultBlockParam +from .beta_mcp_tool_use_block_param import BetaMCPToolUseBlockParam +from .beta_search_result_block_param import BetaSearchResultBlockParam +from .beta_server_tool_use_block_param import BetaServerToolUseBlockParam +from .beta_container_upload_block_param import BetaContainerUploadBlockParam +from .beta_request_document_block_param import BetaRequestDocumentBlockParam +from .beta_redacted_thinking_block_param import BetaRedactedThinkingBlockParam +from .beta_advisor_tool_result_block_param import BetaAdvisorToolResultBlockParam +from .beta_web_fetch_tool_result_block_param import BetaWebFetchToolResultBlockParam +from .beta_web_search_tool_result_block_param import BetaWebSearchToolResultBlockParam +from .beta_request_mcp_tool_result_block_param import BetaRequestMCPToolResultBlockParam +from .beta_tool_search_tool_result_block_param import BetaToolSearchToolResultBlockParam +from .beta_code_execution_tool_result_block_param import BetaCodeExecutionToolResultBlockParam +from .beta_bash_code_execution_tool_result_block_param import BetaBashCodeExecutionToolResultBlockParam +from .beta_text_editor_code_execution_tool_result_block_param import BetaTextEditorCodeExecutionToolResultBlockParam + +__all__ = ["BetaContentBlockParam"] + +BetaContentBlockParam: TypeAlias = Union[ + BetaTextBlockParam, + BetaImageBlockParam, + BetaRequestDocumentBlockParam, + BetaSearchResultBlockParam, + BetaThinkingBlockParam, + BetaRedactedThinkingBlockParam, + BetaToolUseBlockParam, + BetaToolResultBlockParam, + BetaServerToolUseBlockParam, + BetaWebSearchToolResultBlockParam, + BetaWebFetchToolResultBlockParam, + BetaAdvisorToolResultBlockParam, + BetaCodeExecutionToolResultBlockParam, + BetaBashCodeExecutionToolResultBlockParam, + BetaTextEditorCodeExecutionToolResultBlockParam, + BetaToolSearchToolResultBlockParam, + BetaMCPToolUseBlockParam, + BetaRequestMCPToolResultBlockParam, + BetaContainerUploadBlockParam, + BetaCompactionBlockParam, + BetaContentBlock, +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_content_block_source_content_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_content_block_source_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..bc13b146c725b77cf1a2c802d9f88a23680b88da --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_content_block_source_content_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .beta_text_block_param import BetaTextBlockParam +from .beta_image_block_param import BetaImageBlockParam + +__all__ = ["BetaContentBlockSourceContentParam"] + +BetaContentBlockSourceContentParam: TypeAlias = Union[BetaTextBlockParam, BetaImageBlockParam] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_content_block_source_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_content_block_source_param.py new file mode 100644 index 0000000000000000000000000000000000000000..512cf0db93250d7536f37b09e5d8cde3ced47d58 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_content_block_source_param.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import Literal, Required, TypedDict + +from .beta_content_block_source_content_param import BetaContentBlockSourceContentParam + +__all__ = ["BetaContentBlockSourceParam"] + + +class BetaContentBlockSourceParam(TypedDict, total=False): + content: Required[Union[str, Iterable[BetaContentBlockSourceContentParam]]] + + type: Required[Literal["content"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_context_management_capability.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_context_management_capability.py new file mode 100644 index 0000000000000000000000000000000000000000..07ae8fc4be82322390fa17e4a9ea03b023834ae6 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_context_management_capability.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ..._models import BaseModel +from .beta_capability_support import BetaCapabilitySupport + +__all__ = ["BetaContextManagementCapability"] + + +class BetaContextManagementCapability(BaseModel): + """Context management capability details.""" + + clear_thinking_20251015: Optional[BetaCapabilitySupport] = None + """Indicates whether a capability is supported.""" + + clear_tool_uses_20250919: Optional[BetaCapabilitySupport] = None + """Indicates whether a capability is supported.""" + + compact_20260112: Optional[BetaCapabilitySupport] = None + """Indicates whether a capability is supported.""" + + supported: bool + """Whether this capability is supported by the model.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_context_management_config_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_context_management_config_param.py new file mode 100644 index 0000000000000000000000000000000000000000..dec6895539a89ac545ae6a0e41de08a914a53938 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_context_management_config_param.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import TypeAlias, TypedDict + +from .beta_compact_20260112_edit_param import BetaCompact20260112EditParam +from .beta_clear_thinking_20251015_edit_param import BetaClearThinking20251015EditParam +from .beta_clear_tool_uses_20250919_edit_param import BetaClearToolUses20250919EditParam + +__all__ = ["BetaContextManagementConfigParam", "Edit"] + +Edit: TypeAlias = Union[ + BetaClearToolUses20250919EditParam, BetaClearThinking20251015EditParam, BetaCompact20260112EditParam +] + + +class BetaContextManagementConfigParam(TypedDict, total=False): + edits: Iterable[Edit] + """List of context management edits to apply""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_context_management_response.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_context_management_response.py new file mode 100644 index 0000000000000000000000000000000000000000..278c437d86a6d78642314c23d8732b15b2b30162 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_context_management_response.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union +from typing_extensions import Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .beta_clear_thinking_20251015_edit_response import BetaClearThinking20251015EditResponse +from .beta_clear_tool_uses_20250919_edit_response import BetaClearToolUses20250919EditResponse + +__all__ = ["BetaContextManagementResponse", "AppliedEdit"] + +AppliedEdit: TypeAlias = Annotated[ + Union[BetaClearToolUses20250919EditResponse, BetaClearThinking20251015EditResponse], + PropertyInfo(discriminator="type"), +] + + +class BetaContextManagementResponse(BaseModel): + applied_edits: List[AppliedEdit] + """List of context management edits that were applied.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_count_tokens_context_management_response.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_count_tokens_context_management_response.py new file mode 100644 index 0000000000000000000000000000000000000000..15dd44fca3443b06b34c4fe893d83d12828cba31 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_count_tokens_context_management_response.py @@ -0,0 +1,10 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["BetaCountTokensContextManagementResponse"] + + +class BetaCountTokensContextManagementResponse(BaseModel): + original_input_tokens: int + """The original token count before context management was applied""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_direct_caller.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_direct_caller.py new file mode 100644 index 0000000000000000000000000000000000000000..6e7474d144a9172e6017c13f71e01db7d66cc5f9 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_direct_caller.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaDirectCaller"] + + +class BetaDirectCaller(BaseModel): + """Tool invocation directly from the model.""" + + type: Literal["direct"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_document_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_document_block.py new file mode 100644 index 0000000000000000000000000000000000000000..5ed2800e1641f359f67c66d9a10b7e85eb7c61c0 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_document_block.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .beta_citation_config import BetaCitationConfig +from .beta_base64_pdf_source import BetaBase64PDFSource +from .beta_plain_text_source import BetaPlainTextSource + +__all__ = ["BetaDocumentBlock", "Source"] + +Source: TypeAlias = Annotated[Union[BetaBase64PDFSource, BetaPlainTextSource], PropertyInfo(discriminator="type")] + + +class BetaDocumentBlock(BaseModel): + citations: Optional[BetaCitationConfig] = None + """Citation configuration for the document""" + + source: Source + + title: Optional[str] = None + """The title of the document""" + + type: Literal["document"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_effort_capability.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_effort_capability.py new file mode 100644 index 0000000000000000000000000000000000000000..6f33062d3f3be011c76dba18e7b924e7673446bc --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_effort_capability.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ..._models import BaseModel +from .beta_capability_support import BetaCapabilitySupport + +__all__ = ["BetaEffortCapability"] + + +class BetaEffortCapability(BaseModel): + """Effort (reasoning_effort) capability details.""" + + high: BetaCapabilitySupport + """Whether the model supports high effort level.""" + + low: BetaCapabilitySupport + """Whether the model supports low effort level.""" + + max: BetaCapabilitySupport + """Whether the model supports max effort level.""" + + medium: BetaCapabilitySupport + """Whether the model supports medium effort level.""" + + supported: bool + """Whether this capability is supported by the model.""" + + xhigh: Optional[BetaCapabilitySupport] = None + """Indicates whether a capability is supported.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_encrypted_code_execution_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_encrypted_code_execution_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..e9dc37d6c46dc2cc709b5c42de465703951158e1 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_encrypted_code_execution_result_block_param.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Literal, Required, TypedDict + +from .beta_code_execution_output_block_param import BetaCodeExecutionOutputBlockParam + +__all__ = ["BetaEncryptedCodeExecutionResultBlockParam"] + + +class BetaEncryptedCodeExecutionResultBlockParam(TypedDict, total=False): + """Code execution result with encrypted stdout for PFC + web_search results.""" + + content: Required[Iterable[BetaCodeExecutionOutputBlockParam]] + + encrypted_stdout: Required[str] + + return_code: Required[int] + + stderr: Required[str] + + type: Required[Literal["encrypted_code_execution_result"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_environment.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_environment.py new file mode 100644 index 0000000000000000000000000000000000000000..6474b05cb22da548d18bf1d079e74c2510ff0069 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_environment.py @@ -0,0 +1,40 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_cloud_config import BetaCloudConfig + +__all__ = ["BetaEnvironment"] + + +class BetaEnvironment(BaseModel): + """Unified Environment resource for both cloud and self-hosted environments.""" + + id: str + """Environment identifier (e.g., 'env\\__...')""" + + archived_at: Optional[str] = None + """RFC 3339 timestamp when environment was archived, or null if not archived""" + + config: BetaCloudConfig + """`cloud` environment configuration.""" + + created_at: str + """RFC 3339 timestamp when environment was created""" + + description: str + """User-provided description for the environment""" + + metadata: Dict[str, str] + """User-provided metadata key-value pairs""" + + name: str + """Human-readable name for the environment""" + + type: Literal["environment"] + """The type of object (always 'environment')""" + + updated_at: str + """RFC 3339 timestamp when environment was last updated""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_environment_delete_response.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_environment_delete_response.py new file mode 100644 index 0000000000000000000000000000000000000000..ebc9e22128256611c59203d20778bd28028559ba --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_environment_delete_response.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaEnvironmentDeleteResponse"] + + +class BetaEnvironmentDeleteResponse(BaseModel): + """Response after deleting an environment.""" + + id: str + """Environment identifier""" + + type: Literal["environment_deleted"] + """The type of response""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_file_document_source_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_file_document_source_param.py new file mode 100644 index 0000000000000000000000000000000000000000..9654093ccbdb907ef509ba976366e6a35b8dab5b --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_file_document_source_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaFileDocumentSourceParam"] + + +class BetaFileDocumentSourceParam(TypedDict, total=False): + file_id: Required[str] + + type: Required[Literal["file"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_file_scope.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_file_scope.py new file mode 100644 index 0000000000000000000000000000000000000000..f9292334107ac1b6a7feca4558b78cbbb3537d6a --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_file_scope.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaFileScope"] + + +class BetaFileScope(BaseModel): + id: str + """The ID of the scoping resource (e.g., the session ID).""" + + type: Literal["session"] + """The type of scope (e.g., `"session"`).""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_image_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_image_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..f197c829cd46feb910e39c1d77de758fde916b44 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_image_block_param.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .beta_url_image_source_param import BetaURLImageSourceParam +from .beta_file_image_source_param import BetaFileImageSourceParam +from .beta_base64_image_source_param import BetaBase64ImageSourceParam +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaImageBlockParam", "Source"] + +Source: TypeAlias = Union[BetaBase64ImageSourceParam, BetaURLImageSourceParam, BetaFileImageSourceParam] + + +class BetaImageBlockParam(TypedDict, total=False): + source: Required[Source] + + type: Required[Literal["image"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_input_json_delta.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_input_json_delta.py new file mode 100644 index 0000000000000000000000000000000000000000..a5f9cbeaec78d7e7650f8f7a8690fa90b9fbf293 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_input_json_delta.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaInputJSONDelta"] + + +class BetaInputJSONDelta(BaseModel): + partial_json: str + + type: Literal["input_json_delta"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_input_tokens_clear_at_least_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_input_tokens_clear_at_least_param.py new file mode 100644 index 0000000000000000000000000000000000000000..e3a137bd23648719766e3a32ec9c87ed2c156fce --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_input_tokens_clear_at_least_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaInputTokensClearAtLeastParam"] + + +class BetaInputTokensClearAtLeastParam(TypedDict, total=False): + type: Required[Literal["input_tokens"]] + + value: Required[int] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_input_tokens_trigger_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_input_tokens_trigger_param.py new file mode 100644 index 0000000000000000000000000000000000000000..1d5f15c6131f6a444b8e5260303899ed5d26bd27 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_input_tokens_trigger_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaInputTokensTriggerParam"] + + +class BetaInputTokensTriggerParam(TypedDict, total=False): + type: Required[Literal["input_tokens"]] + + value: Required[int] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_iterations_usage.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_iterations_usage.py new file mode 100644 index 0000000000000000000000000000000000000000..424c1f492790cb8a762a5025af91b513eed22fa6 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_iterations_usage.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union +from typing_extensions import Annotated, TypeAlias + +from ..._utils import PropertyInfo +from .beta_message_iteration_usage import BetaMessageIterationUsage +from .beta_compaction_iteration_usage import BetaCompactionIterationUsage +from .beta_advisor_message_iteration_usage import BetaAdvisorMessageIterationUsage + +__all__ = ["BetaIterationsUsage", "BetaIterationsUsageItem"] + +BetaIterationsUsageItem: TypeAlias = Annotated[ + Union[BetaMessageIterationUsage, BetaCompactionIterationUsage, BetaAdvisorMessageIterationUsage], + PropertyInfo(discriminator="type"), +] + +BetaIterationsUsage: TypeAlias = List[BetaIterationsUsageItem] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_json_output_format_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_json_output_format_param.py new file mode 100644 index 0000000000000000000000000000000000000000..48f9fb0b1f3079982eabc612b3fdf634ed3c1724 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_json_output_format_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaJSONOutputFormatParam"] + + +class BetaJSONOutputFormatParam(TypedDict, total=False): + schema: Required[Dict[str, object]] + """The JSON schema of the format""" + + type: Required[Literal["json_schema"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_limited_network.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_limited_network.py new file mode 100644 index 0000000000000000000000000000000000000000..f933445e993dc87d94fdcd76999cbd6f3a60d4d8 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_limited_network.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaLimitedNetwork"] + + +class BetaLimitedNetwork(BaseModel): + """Limited network access.""" + + allow_mcp_servers: bool + """ + Permits outbound access to MCP server endpoints configured on the agent, beyond + those listed in the `allowed_hosts` array. + """ + + allow_package_managers: bool + """ + Permits outbound access to public package registries (PyPI, npm, etc.) beyond + those listed in the `allowed_hosts` array. + """ + + allowed_hosts: List[str] + """Specifies domains the container can reach.""" + + type: Literal["limited"] + """Network policy type""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_limited_network_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_limited_network_params.py new file mode 100644 index 0000000000000000000000000000000000000000..8ef074da945e16c65f99cad754338a4fc933c5c9 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_limited_network_params.py @@ -0,0 +1,36 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +from ..._types import SequenceNotStr + +__all__ = ["BetaLimitedNetworkParams"] + + +class BetaLimitedNetworkParams(TypedDict, total=False): + """Limited network request params. + + Fields default to null; on update, omitted fields preserve the + existing value. + """ + + type: Required[Literal["limited"]] + """Network policy type""" + + allow_mcp_servers: Optional[bool] + """ + Permits outbound access to MCP server endpoints configured on the agent, beyond + those listed in the `allowed_hosts` array. Defaults to `false`. + """ + + allow_package_managers: Optional[bool] + """ + Permits outbound access to public package registries (PyPI, npm, etc.) beyond + those listed in the `allowed_hosts` array. Defaults to `false`. + """ + + allowed_hosts: Optional[SequenceNotStr[str]] + """Specifies domains the container can reach.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_agent.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..7d77211a23e7c3dce35ad3a454c500c182d3cf3e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_agent.py @@ -0,0 +1,70 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, List, Union, Optional +from datetime import datetime +from typing_extensions import Literal, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .beta_managed_agents_multiagent import BetaManagedAgentsMultiagent +from .beta_managed_agents_custom_tool import BetaManagedAgentsCustomTool +from .beta_managed_agents_mcp_toolset import BetaManagedAgentsMCPToolset +from .beta_managed_agents_custom_skill import BetaManagedAgentsCustomSkill +from .beta_managed_agents_model_config import BetaManagedAgentsModelConfig +from .beta_managed_agents_anthropic_skill import BetaManagedAgentsAnthropicSkill +from .beta_managed_agents_agent_toolset20260401 import BetaManagedAgentsAgentToolset20260401 +from .beta_managed_agents_mcp_server_url_definition import BetaManagedAgentsMCPServerURLDefinition + +__all__ = ["BetaManagedAgentsAgent", "Skill", "Tool"] + +Skill: TypeAlias = Annotated[ + Union[BetaManagedAgentsAnthropicSkill, BetaManagedAgentsCustomSkill], PropertyInfo(discriminator="type") +] + +Tool: TypeAlias = Annotated[ + Union[BetaManagedAgentsAgentToolset20260401, BetaManagedAgentsMCPToolset, BetaManagedAgentsCustomTool], + PropertyInfo(discriminator="type"), +] + + +class BetaManagedAgentsAgent(BaseModel): + """A Managed Agents `agent`.""" + + id: str + + archived_at: Optional[datetime] = None + """A timestamp in RFC 3339 format""" + + created_at: datetime + """A timestamp in RFC 3339 format""" + + description: Optional[str] = None + + mcp_servers: List[BetaManagedAgentsMCPServerURLDefinition] + + metadata: Dict[str, str] + + model: BetaManagedAgentsModelConfig + """Model identifier and configuration.""" + + multiagent: Optional[BetaManagedAgentsMultiagent] = None + """Resolved coordinator topology with a concrete agent roster.""" + + name: str + + skills: List[Skill] + + system: Optional[str] = None + + tools: List[Tool] + + type: Literal["agent"] + + updated_at: datetime + """A timestamp in RFC 3339 format""" + + version: int + """The agent's current version. + + Starts at 1 and increments when the agent is modified. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_agent_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_agent_params.py new file mode 100644 index 0000000000000000000000000000000000000000..364db605283832dd16bd3a7f6273b2ac905ef50b --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_agent_params.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaManagedAgentsAgentParams"] + + +class BetaManagedAgentsAgentParams(TypedDict, total=False): + """Specification for an Agent. + + Provide a specific `version` or use the short-form `agent="agent_id"` for the most recent version + """ + + id: Required[str] + """The `agent` ID.""" + + type: Required[Literal["agent"]] + + version: int + """The specific `agent` version to use. + + Omit to use the latest version. Must be at least 1 if specified. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_agent_tool_config.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_agent_tool_config.py new file mode 100644 index 0000000000000000000000000000000000000000..07ea0532a0f942eba0a3d27b4d136671259dca0c --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_agent_tool_config.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Literal, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .beta_managed_agents_always_ask_policy import BetaManagedAgentsAlwaysAskPolicy +from .beta_managed_agents_always_allow_policy import BetaManagedAgentsAlwaysAllowPolicy + +__all__ = ["BetaManagedAgentsAgentToolConfig", "PermissionPolicy"] + +PermissionPolicy: TypeAlias = Annotated[ + Union[BetaManagedAgentsAlwaysAllowPolicy, BetaManagedAgentsAlwaysAskPolicy], PropertyInfo(discriminator="type") +] + + +class BetaManagedAgentsAgentToolConfig(BaseModel): + """Configuration for a specific agent tool.""" + + enabled: bool + + name: Literal["bash", "edit", "read", "write", "glob", "grep", "web_fetch", "web_search"] + """Built-in agent tool identifier.""" + + permission_policy: PermissionPolicy + """Permission policy for tool execution.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_agent_tool_config_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_agent_tool_config_params.py new file mode 100644 index 0000000000000000000000000000000000000000..6348319267203d6c76cc9612834740ba4df1351f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_agent_tool_config_params.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .beta_managed_agents_always_ask_policy_param import BetaManagedAgentsAlwaysAskPolicyParam +from .beta_managed_agents_always_allow_policy_param import BetaManagedAgentsAlwaysAllowPolicyParam + +__all__ = ["BetaManagedAgentsAgentToolConfigParams", "PermissionPolicy"] + +PermissionPolicy: TypeAlias = Union[BetaManagedAgentsAlwaysAllowPolicyParam, BetaManagedAgentsAlwaysAskPolicyParam] + + +class BetaManagedAgentsAgentToolConfigParams(TypedDict, total=False): + """Configuration override for a specific tool within a toolset.""" + + name: Required[Literal["bash", "edit", "read", "write", "glob", "grep", "web_fetch", "web_search"]] + """Built-in agent tool identifier.""" + + enabled: Optional[bool] + """Whether this tool is enabled and available to Claude. + + Overrides the default_config setting. + """ + + permission_policy: Optional[PermissionPolicy] + """Permission policy for tool execution.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_agent_toolset20260401.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_agent_toolset20260401.py new file mode 100644 index 0000000000000000000000000000000000000000..fb1b0166edd6ecdf7ffdbf3688b2bc0cfc428537 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_agent_toolset20260401.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_managed_agents_agent_tool_config import BetaManagedAgentsAgentToolConfig +from .beta_managed_agents_agent_toolset_default_config import BetaManagedAgentsAgentToolsetDefaultConfig + +__all__ = ["BetaManagedAgentsAgentToolset20260401"] + + +class BetaManagedAgentsAgentToolset20260401(BaseModel): + configs: List[BetaManagedAgentsAgentToolConfig] + + default_config: BetaManagedAgentsAgentToolsetDefaultConfig + """Resolved default configuration for agent tools.""" + + type: Literal["agent_toolset_20260401"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_agent_toolset20260401_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_agent_toolset20260401_params.py new file mode 100644 index 0000000000000000000000000000000000000000..5de1c4b42c6fe71e96d20f21e56ed6db1aca0e43 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_agent_toolset20260401_params.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable, Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_managed_agents_agent_tool_config_params import BetaManagedAgentsAgentToolConfigParams +from .beta_managed_agents_agent_toolset_default_config_params import BetaManagedAgentsAgentToolsetDefaultConfigParams + +__all__ = ["BetaManagedAgentsAgentToolset20260401Params"] + + +class BetaManagedAgentsAgentToolset20260401Params(TypedDict, total=False): + """Configuration for built-in agent tools. + + Use this to enable or disable groups of tools available to the agent. + """ + + type: Required[Literal["agent_toolset_20260401"]] + + configs: Iterable[BetaManagedAgentsAgentToolConfigParams] + """Per-tool configuration overrides.""" + + default_config: Optional[BetaManagedAgentsAgentToolsetDefaultConfigParams] + """Default configuration for all tools in a toolset.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_agent_toolset_default_config_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_agent_toolset_default_config_params.py new file mode 100644 index 0000000000000000000000000000000000000000..bdaf1853724e5203f9b848df59552ed426c8db59 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_agent_toolset_default_config_params.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Optional +from typing_extensions import TypeAlias, TypedDict + +from .beta_managed_agents_always_ask_policy_param import BetaManagedAgentsAlwaysAskPolicyParam +from .beta_managed_agents_always_allow_policy_param import BetaManagedAgentsAlwaysAllowPolicyParam + +__all__ = ["BetaManagedAgentsAgentToolsetDefaultConfigParams", "PermissionPolicy"] + +PermissionPolicy: TypeAlias = Union[BetaManagedAgentsAlwaysAllowPolicyParam, BetaManagedAgentsAlwaysAskPolicyParam] + + +class BetaManagedAgentsAgentToolsetDefaultConfigParams(TypedDict, total=False): + """Default configuration for all tools in a toolset.""" + + enabled: Optional[bool] + """Whether tools are enabled and available to Claude by default. + + Defaults to true if not specified. + """ + + permission_policy: Optional[PermissionPolicy] + """Permission policy for tool execution.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_always_allow_policy.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_always_allow_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..a103ad29f3cb81d9f626c8506e253a03edc70e1e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_always_allow_policy.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaManagedAgentsAlwaysAllowPolicy"] + + +class BetaManagedAgentsAlwaysAllowPolicy(BaseModel): + """Tool calls are automatically approved without user confirmation.""" + + type: Literal["always_allow"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_always_allow_policy_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_always_allow_policy_param.py new file mode 100644 index 0000000000000000000000000000000000000000..3a7c23dd062da2e6d1efb8884a84a7776750e865 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_always_allow_policy_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaManagedAgentsAlwaysAllowPolicyParam"] + + +class BetaManagedAgentsAlwaysAllowPolicyParam(TypedDict, total=False): + """Tool calls are automatically approved without user confirmation.""" + + type: Required[Literal["always_allow"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_always_ask_policy.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_always_ask_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..2d83eb23e30edc700ef57d89c73e09958a5486e9 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_always_ask_policy.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaManagedAgentsAlwaysAskPolicy"] + + +class BetaManagedAgentsAlwaysAskPolicy(BaseModel): + """Tool calls require user confirmation before execution.""" + + type: Literal["always_ask"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_always_ask_policy_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_always_ask_policy_param.py new file mode 100644 index 0000000000000000000000000000000000000000..82c91b411ee2bca36f196beb4732f742ad3c4699 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_always_ask_policy_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaManagedAgentsAlwaysAskPolicyParam"] + + +class BetaManagedAgentsAlwaysAskPolicyParam(TypedDict, total=False): + """Tool calls require user confirmation before execution.""" + + type: Required[Literal["always_ask"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_anthropic_skill.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_anthropic_skill.py new file mode 100644 index 0000000000000000000000000000000000000000..acb97fdaf1e5228cfe361149a8c7e2627656e3c6 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_anthropic_skill.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaManagedAgentsAnthropicSkill"] + + +class BetaManagedAgentsAnthropicSkill(BaseModel): + """A resolved Anthropic-managed skill.""" + + skill_id: str + + type: Literal["anthropic"] + + version: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_anthropic_skill_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_anthropic_skill_params.py new file mode 100644 index 0000000000000000000000000000000000000000..c235b99ed1f78c8713608a471b559c1d4d3d0bdf --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_anthropic_skill_params.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaManagedAgentsAnthropicSkillParams"] + + +class BetaManagedAgentsAnthropicSkillParams(TypedDict, total=False): + """An Anthropic-managed skill.""" + + skill_id: Required[str] + """Identifier of the Anthropic skill (e.g., "xlsx").""" + + type: Required[Literal["anthropic"]] + + version: Optional[str] + """Version to pin. Defaults to latest if omitted.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_branch_checkout.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_branch_checkout.py new file mode 100644 index 0000000000000000000000000000000000000000..520b3eb7c1f8db1dd5ddb09cfbab597073d4e0ce --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_branch_checkout.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaManagedAgentsBranchCheckout"] + + +class BetaManagedAgentsBranchCheckout(BaseModel): + name: str + """Branch name to check out.""" + + type: Literal["branch"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_branch_checkout_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_branch_checkout_param.py new file mode 100644 index 0000000000000000000000000000000000000000..312aaca3936e9741932f896f3f49ab664717709d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_branch_checkout_param.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaManagedAgentsBranchCheckoutParam"] + + +class BetaManagedAgentsBranchCheckoutParam(TypedDict, total=False): + name: Required[str] + """Branch name to check out.""" + + type: Required[Literal["branch"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_cache_creation_usage.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_cache_creation_usage.py new file mode 100644 index 0000000000000000000000000000000000000000..c91e2fd3ed48a02dee072ed62edde44631e32df9 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_cache_creation_usage.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ..._models import BaseModel + +__all__ = ["BetaManagedAgentsCacheCreationUsage"] + + +class BetaManagedAgentsCacheCreationUsage(BaseModel): + """Prompt-cache creation token usage broken down by cache lifetime.""" + + ephemeral_1h_input_tokens: Optional[int] = None + """Tokens used to create 1-hour ephemeral cache entries.""" + + ephemeral_5m_input_tokens: Optional[int] = None + """Tokens used to create 5-minute ephemeral cache entries.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_commit_checkout.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_commit_checkout.py new file mode 100644 index 0000000000000000000000000000000000000000..203cf2029d0ffacdf98846c711b97ce26d246441 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_commit_checkout.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaManagedAgentsCommitCheckout"] + + +class BetaManagedAgentsCommitCheckout(BaseModel): + sha: str + """Full commit SHA to check out.""" + + type: Literal["commit"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_commit_checkout_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_commit_checkout_param.py new file mode 100644 index 0000000000000000000000000000000000000000..a14a715928e49b058b900c7931ed60238d174abc --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_commit_checkout_param.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaManagedAgentsCommitCheckoutParam"] + + +class BetaManagedAgentsCommitCheckoutParam(TypedDict, total=False): + sha: Required[str] + """Full commit SHA to check out.""" + + type: Required[Literal["commit"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_custom_skill.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_custom_skill.py new file mode 100644 index 0000000000000000000000000000000000000000..932fc1a9c2abe2baa3caf46897672104a523bc41 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_custom_skill.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaManagedAgentsCustomSkill"] + + +class BetaManagedAgentsCustomSkill(BaseModel): + """A resolved user-created custom skill.""" + + skill_id: str + + type: Literal["custom"] + + version: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_custom_skill_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_custom_skill_params.py new file mode 100644 index 0000000000000000000000000000000000000000..101426c4610b9f65a368a6fd7603d29986b3a271 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_custom_skill_params.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaManagedAgentsCustomSkillParams"] + + +class BetaManagedAgentsCustomSkillParams(TypedDict, total=False): + """A user-created custom skill.""" + + skill_id: Required[str] + """Tagged ID of the custom skill (e.g., "skill_01XJ5...").""" + + type: Required[Literal["custom"]] + + version: Optional[str] + """Version to pin. Defaults to latest if omitted.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_custom_tool.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_custom_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..efb9c3cdb63dc51cb6d3aa72c487918d303b296f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_custom_tool.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_managed_agents_custom_tool_input_schema import BetaManagedAgentsCustomToolInputSchema + +__all__ = ["BetaManagedAgentsCustomTool"] + + +class BetaManagedAgentsCustomTool(BaseModel): + """A custom tool as returned in API responses.""" + + description: str + + input_schema: BetaManagedAgentsCustomToolInputSchema + """JSON Schema for custom tool input parameters.""" + + name: str + + type: Literal["custom"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_custom_tool_input_schema.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_custom_tool_input_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..abf18f7860c65b1323b30ed6329b7b5508be9679 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_custom_tool_input_schema.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, List, Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaManagedAgentsCustomToolInputSchema"] + + +class BetaManagedAgentsCustomToolInputSchema(BaseModel): + """JSON Schema for custom tool input parameters.""" + + properties: Optional[Dict[str, object]] = None + """JSON Schema properties defining the tool's input parameters.""" + + required: Optional[List[str]] = None + """List of required property names.""" + + type: Optional[Literal["object"]] = None + """Must be 'object' for tool input schemas.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_custom_tool_input_schema_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_custom_tool_input_schema_param.py new file mode 100644 index 0000000000000000000000000000000000000000..0df0e187054456848abc67ba446055fc9a46969f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_custom_tool_input_schema_param.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional +from typing_extensions import Literal, TypedDict + +from ..._types import SequenceNotStr + +__all__ = ["BetaManagedAgentsCustomToolInputSchemaParam"] + + +class BetaManagedAgentsCustomToolInputSchemaParam(TypedDict, total=False): + """JSON Schema for custom tool input parameters.""" + + properties: Optional[Dict[str, object]] + """JSON Schema properties defining the tool's input parameters.""" + + required: SequenceNotStr[str] + """List of required property names.""" + + type: Literal["object"] + """Must be 'object' for tool input schemas.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_custom_tool_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_custom_tool_params.py new file mode 100644 index 0000000000000000000000000000000000000000..42a3c2de85959172743ff2fefe3f8a8d6e2f761e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_custom_tool_params.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +from .beta_managed_agents_custom_tool_input_schema_param import BetaManagedAgentsCustomToolInputSchemaParam + +__all__ = ["BetaManagedAgentsCustomToolParams"] + + +class BetaManagedAgentsCustomToolParams(TypedDict, total=False): + """A custom tool that is executed by the API client rather than the agent. + + When the agent calls this tool, an `agent.custom_tool_use` event is emitted and the session goes idle, waiting for the client to provide the result via a `user.custom_tool_result` event. + """ + + description: Required[str] + """ + Description of what the tool does, shown to the agent to help it decide when to + use the tool. 1-1024 characters. + """ + + input_schema: Required[BetaManagedAgentsCustomToolInputSchemaParam] + """JSON Schema for custom tool input parameters.""" + + name: Required[str] + """Unique name for the tool. + + 1-128 characters; letters, digits, underscores, and hyphens. + """ + + type: Required[Literal["custom"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_deleted_session.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_deleted_session.py new file mode 100644 index 0000000000000000000000000000000000000000..bd79d8231b45fddd08bf9c55b1531d283d5ec9d6 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_deleted_session.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaManagedAgentsDeletedSession"] + + +class BetaManagedAgentsDeletedSession(BaseModel): + """Confirmation that a `session` has been permanently deleted.""" + + id: str + + type: Literal["session_deleted"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_deleted_vault.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_deleted_vault.py new file mode 100644 index 0000000000000000000000000000000000000000..da760f6968ff848f859a6521386b961992a49cb5 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_deleted_vault.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaManagedAgentsDeletedVault"] + + +class BetaManagedAgentsDeletedVault(BaseModel): + """Confirmation of a deleted vault.""" + + id: str + """Unique identifier of the deleted vault.""" + + type: Literal["vault_deleted"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_file_resource_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_file_resource_params.py new file mode 100644 index 0000000000000000000000000000000000000000..7b444b53ac9c9f2b0c0201bdd41246bc6deed6bb --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_file_resource_params.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaManagedAgentsFileResourceParams"] + + +class BetaManagedAgentsFileResourceParams(TypedDict, total=False): + """Mount a file uploaded via the Files API into the session.""" + + file_id: Required[str] + """ID of a previously uploaded file.""" + + type: Required[Literal["file"]] + + mount_path: Optional[str] + """Mount path in the container. Defaults to `/mnt/session/uploads/`.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_github_repository_resource_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_github_repository_resource_params.py new file mode 100644 index 0000000000000000000000000000000000000000..8cbd865989cb84d8bed9159d7f3efa49f58dc0a1 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_github_repository_resource_params.py @@ -0,0 +1,31 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .beta_managed_agents_branch_checkout_param import BetaManagedAgentsBranchCheckoutParam +from .beta_managed_agents_commit_checkout_param import BetaManagedAgentsCommitCheckoutParam + +__all__ = ["BetaManagedAgentsGitHubRepositoryResourceParams", "Checkout"] + +Checkout: TypeAlias = Union[BetaManagedAgentsBranchCheckoutParam, BetaManagedAgentsCommitCheckoutParam] + + +class BetaManagedAgentsGitHubRepositoryResourceParams(TypedDict, total=False): + """Mount a GitHub repository into the session's container.""" + + authorization_token: Required[str] + """GitHub authorization token used to clone the repository.""" + + type: Required[Literal["github_repository"]] + + url: Required[str] + """Github URL of the repository""" + + checkout: Optional[Checkout] + """Branch or commit to check out. Defaults to the repository's default branch.""" + + mount_path: Optional[str] + """Mount path in the container. Defaults to `/workspace/`.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_mcp_server_url_definition.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_mcp_server_url_definition.py new file mode 100644 index 0000000000000000000000000000000000000000..35c6e48343c0e33f758935a482a075b6fef7597f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_mcp_server_url_definition.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaManagedAgentsMCPServerURLDefinition"] + + +class BetaManagedAgentsMCPServerURLDefinition(BaseModel): + """URL-based MCP server connection as returned in API responses.""" + + name: str + + type: Literal["url"] + + url: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_mcp_tool_config_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_mcp_tool_config_params.py new file mode 100644 index 0000000000000000000000000000000000000000..899d81c3f4ed206ef2d63133d5bc3acb998ef29f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_mcp_tool_config_params.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Optional +from typing_extensions import Required, TypeAlias, TypedDict + +from .beta_managed_agents_always_ask_policy_param import BetaManagedAgentsAlwaysAskPolicyParam +from .beta_managed_agents_always_allow_policy_param import BetaManagedAgentsAlwaysAllowPolicyParam + +__all__ = ["BetaManagedAgentsMCPToolConfigParams", "PermissionPolicy"] + +PermissionPolicy: TypeAlias = Union[BetaManagedAgentsAlwaysAllowPolicyParam, BetaManagedAgentsAlwaysAskPolicyParam] + + +class BetaManagedAgentsMCPToolConfigParams(TypedDict, total=False): + """Configuration override for a specific MCP tool.""" + + name: Required[str] + """Name of the MCP tool to configure. 1-128 characters.""" + + enabled: Optional[bool] + """Whether this tool is enabled. Overrides the `default_config` setting.""" + + permission_policy: Optional[PermissionPolicy] + """Permission policy for tool execution.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_mcp_toolset.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_mcp_toolset.py new file mode 100644 index 0000000000000000000000000000000000000000..bbd56ef400e327b9999dddae6e623949afa295bb --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_mcp_toolset.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_managed_agents_mcp_tool_config import BetaManagedAgentsMCPToolConfig +from .beta_managed_agents_mcp_toolset_default_config import BetaManagedAgentsMCPToolsetDefaultConfig + +__all__ = ["BetaManagedAgentsMCPToolset"] + + +class BetaManagedAgentsMCPToolset(BaseModel): + configs: List[BetaManagedAgentsMCPToolConfig] + + default_config: BetaManagedAgentsMCPToolsetDefaultConfig + """Resolved default configuration for all tools from an MCP server.""" + + mcp_server_name: str + + type: Literal["mcp_toolset"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_mcp_toolset_default_config.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_mcp_toolset_default_config.py new file mode 100644 index 0000000000000000000000000000000000000000..8ea696071dc164b641431f1357173fb6912658d2 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_mcp_toolset_default_config.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .beta_managed_agents_always_ask_policy import BetaManagedAgentsAlwaysAskPolicy +from .beta_managed_agents_always_allow_policy import BetaManagedAgentsAlwaysAllowPolicy + +__all__ = ["BetaManagedAgentsMCPToolsetDefaultConfig", "PermissionPolicy"] + +PermissionPolicy: TypeAlias = Annotated[ + Union[BetaManagedAgentsAlwaysAllowPolicy, BetaManagedAgentsAlwaysAskPolicy], PropertyInfo(discriminator="type") +] + + +class BetaManagedAgentsMCPToolsetDefaultConfig(BaseModel): + """Resolved default configuration for all tools from an MCP server.""" + + enabled: bool + + permission_policy: PermissionPolicy + """Permission policy for tool execution.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_mcp_toolset_default_config_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_mcp_toolset_default_config_params.py new file mode 100644 index 0000000000000000000000000000000000000000..f29f2958b6e20fd7bc8c49f5406d5031d07c776c --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_mcp_toolset_default_config_params.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Optional +from typing_extensions import TypeAlias, TypedDict + +from .beta_managed_agents_always_ask_policy_param import BetaManagedAgentsAlwaysAskPolicyParam +from .beta_managed_agents_always_allow_policy_param import BetaManagedAgentsAlwaysAllowPolicyParam + +__all__ = ["BetaManagedAgentsMCPToolsetDefaultConfigParams", "PermissionPolicy"] + +PermissionPolicy: TypeAlias = Union[BetaManagedAgentsAlwaysAllowPolicyParam, BetaManagedAgentsAlwaysAskPolicyParam] + + +class BetaManagedAgentsMCPToolsetDefaultConfigParams(TypedDict, total=False): + """Default configuration for all tools from an MCP server.""" + + enabled: Optional[bool] + """Whether tools are enabled by default. Defaults to true if not specified.""" + + permission_policy: Optional[PermissionPolicy] + """Permission policy for tool execution.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_memory_store.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_memory_store.py new file mode 100644 index 0000000000000000000000000000000000000000..323a5f78ff0fcde2a8618e6449e4d6737e834fb8 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_memory_store.py @@ -0,0 +1,55 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional +from datetime import datetime +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaManagedAgentsMemoryStore"] + + +class BetaManagedAgentsMemoryStore(BaseModel): + """A `memory_store`: a named container for agent memories, scoped to a workspace. + + Attach a store to a session via `resources[]` to mount it as a directory the agent can read and write. + """ + + id: str + """Unique identifier for the memory store (a `memstore_...` tagged ID). + + Use this when attaching the store to a session, or in the `{memory_store_id}` + path parameter of subsequent calls. + """ + + created_at: datetime + """A timestamp in RFC 3339 format""" + + name: str + """Human-readable name for the store. + + 1–255 characters. The store's mount-path slug under `/mnt/memory/` is derived + from this name. + """ + + type: Literal["memory_store"] + + updated_at: datetime + """A timestamp in RFC 3339 format""" + + archived_at: Optional[datetime] = None + """A timestamp in RFC 3339 format""" + + description: Optional[str] = None + """Free-text description of what the store contains, up to 1024 characters. + + Included in the agent's system prompt when the store is attached, so word it to + be useful to the agent. Empty string when unset. + """ + + metadata: Optional[Dict[str, str]] = None + """ + Arbitrary key-value tags for your own bookkeeping (such as the end user a store + belongs to). Up to 16 pairs; keys 1–64 characters; values up to 512 characters. + Returned on retrieve/list but not filterable. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_memory_store_resource_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_memory_store_resource_param.py new file mode 100644 index 0000000000000000000000000000000000000000..31170e63f5ffa01d0c3419c8a97f5a7d27e82af5 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_memory_store_resource_param.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaManagedAgentsMemoryStoreResourceParam"] + + +class BetaManagedAgentsMemoryStoreResourceParam(TypedDict, total=False): + """Parameters for attaching a memory store to an agent session.""" + + memory_store_id: Required[str] + """The memory store ID (memstore\\__...). + + Must belong to the caller's organization and workspace. + """ + + type: Required[Literal["memory_store"]] + + access: Optional[Literal["read_write", "read_only"]] + """Access mode for an attached memory store.""" + + instructions: Optional[str] + """Per-attachment guidance for the agent on how to use this store. + + Rendered into the memory section of the system prompt. Max 4096 chars. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_model.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_model.py new file mode 100644 index 0000000000000000000000000000000000000000..66aa606a9361bed44f63523b8ea58692f1bbd587 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_model.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Literal, TypeAlias + +__all__ = ["BetaManagedAgentsModel"] + +BetaManagedAgentsModel: TypeAlias = Union[ + Literal[ + "claude-opus-4-7", + "claude-opus-4-6", + "claude-sonnet-4-6", + "claude-haiku-4-5", + "claude-haiku-4-5-20251001", + "claude-opus-4-5", + "claude-opus-4-5-20251101", + "claude-sonnet-4-5", + "claude-sonnet-4-5-20250929", + ], + str, +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_model_config.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_model_config.py new file mode 100644 index 0000000000000000000000000000000000000000..d871041700f675e7c84ec691011d0d23058ae1f5 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_model_config.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_managed_agents_model import BetaManagedAgentsModel + +__all__ = ["BetaManagedAgentsModelConfig"] + + +class BetaManagedAgentsModelConfig(BaseModel): + """Model identifier and configuration.""" + + id: BetaManagedAgentsModel + """ + The model that will power your agent.\n\nSee + [models](https://docs.anthropic.com/en/docs/models-overview) for additional + details and options. + """ + + speed: Optional[Literal["standard", "fast"]] = None + """Inference speed mode. + + `fast` provides significantly faster output token generation at premium pricing. + Not all models support `fast`; invalid combinations are rejected at create time. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_model_config_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_model_config_params.py new file mode 100644 index 0000000000000000000000000000000000000000..2b5886a6d26dbf9d7113555bce4e80d75b5c0ae0 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_model_config_params.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_managed_agents_model_param import BetaManagedAgentsModelParam + +__all__ = ["BetaManagedAgentsModelConfigParams"] + + +class BetaManagedAgentsModelConfigParams(TypedDict, total=False): + """An object that defines additional configuration control over model use""" + + id: Required[BetaManagedAgentsModelParam] + """ + The model that will power your agent.\n\nSee + [models](https://docs.anthropic.com/en/docs/models-overview) for additional + details and options. + """ + + speed: Optional[Literal["standard", "fast"]] + """Inference speed mode. + + `fast` provides significantly faster output token generation at premium pricing. + Not all models support `fast`; invalid combinations are rejected at create time. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_model_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_model_param.py new file mode 100644 index 0000000000000000000000000000000000000000..c8cfaf848d7326215f411ec53a452f1aaf4b4ee7 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_model_param.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, TypeAlias + +__all__ = ["BetaManagedAgentsModelParam"] + +BetaManagedAgentsModelParam: TypeAlias = Union[ + Literal[ + "claude-opus-4-7", + "claude-opus-4-6", + "claude-sonnet-4-6", + "claude-haiku-4-5", + "claude-haiku-4-5-20251001", + "claude-opus-4-5", + "claude-opus-4-5-20251101", + "claude-sonnet-4-5", + "claude-sonnet-4-5-20250929", + ], + str, +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_multiagent.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_multiagent.py new file mode 100644 index 0000000000000000000000000000000000000000..3935442fae80d6ecfeadc3ce47a9e152bd8f17ff --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_multiagent.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_managed_agents_agent_reference import BetaManagedAgentsAgentReference + +__all__ = ["BetaManagedAgentsMultiagent"] + + +class BetaManagedAgentsMultiagent(BaseModel): + """Resolved coordinator topology with a concrete agent roster.""" + + agents: List[BetaManagedAgentsAgentReference] + """ + Agents the coordinator may spawn as session threads, each resolved to a specific + version. + """ + + type: Literal["coordinator"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_multiagent_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_multiagent_params.py new file mode 100644 index 0000000000000000000000000000000000000000..d37f2473f90779288058bbd976f4e6c7ad54b0bc --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_multiagent_params.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +from ..._types import SequenceNotStr +from .beta_managed_agents_multiagent_roster_entry_params import BetaManagedAgentsMultiagentRosterEntryParams + +__all__ = ["BetaManagedAgentsMultiagentParams"] + + +class BetaManagedAgentsMultiagentParams(TypedDict, total=False): + """ + A coordinator topology: the session's primary thread orchestrates work by spawning session threads, each running an agent drawn from the `agents` roster. + """ + + agents: Required[SequenceNotStr[BetaManagedAgentsMultiagentRosterEntryParams]] + """Agents the coordinator may spawn as session threads. + + 1–20 entries. Each entry is an agent ID string, a versioned + `{"type":"agent","id","version"}` reference, or `{"type":"self"}` to allow + recursive self-invocation. Entries must reference distinct agents (after + resolving `self` and string forms); at most one `self`. Referenced agents must + exist, must not be archived, and must not themselves have `multiagent` set + (depth limit 1). + """ + + type: Required[Literal["coordinator"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_multiagent_roster_entry_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_multiagent_roster_entry_params.py new file mode 100644 index 0000000000000000000000000000000000000000..1fa0dc98a271330d953bd079f2d474655aae957a --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_multiagent_roster_entry_params.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .beta_managed_agents_agent_params import BetaManagedAgentsAgentParams +from .beta_managed_agents_multiagent_self_params import BetaManagedAgentsMultiagentSelfParams + +__all__ = ["BetaManagedAgentsMultiagentRosterEntryParams"] + +BetaManagedAgentsMultiagentRosterEntryParams: TypeAlias = Union[ + str, BetaManagedAgentsAgentParams, BetaManagedAgentsMultiagentSelfParams +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_multiagent_self_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_multiagent_self_params.py new file mode 100644 index 0000000000000000000000000000000000000000..bb66f69a6c3fe08ab9b76e43371b8e75dd6d2a9d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_multiagent_self_params.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaManagedAgentsMultiagentSelfParams"] + + +class BetaManagedAgentsMultiagentSelfParams(TypedDict, total=False): + """Sentinel roster entry meaning "the agent that owns this configuration". + + Resolved server-side to a concrete agent reference. + """ + + type: Required[Literal["self"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_outcome_evaluation_resource.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_outcome_evaluation_resource.py new file mode 100644 index 0000000000000000000000000000000000000000..a26bfb3eca961c064bdc724b912915e80e079ed9 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_outcome_evaluation_resource.py @@ -0,0 +1,42 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from datetime import datetime +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaManagedAgentsOutcomeEvaluationResource"] + + +class BetaManagedAgentsOutcomeEvaluationResource(BaseModel): + """Evaluation state for a single outcome defined via a define_outcome event.""" + + completed_at: Optional[datetime] = None + """A timestamp in RFC 3339 format""" + + description: str + """What the agent should produce.""" + + explanation: Optional[str] = None + """Grader's verdict text from the most recent evaluation. + + For satisfied, explains why criteria are met; for needs_revision (intermediate), + what's missing; for failed, why unrecoverable. + """ + + iteration: int + """0-indexed revision cycle the outcome is currently on.""" + + outcome_id: str + """Server-generated outc\\__ ID for this outcome.""" + + result: str + """Current evaluation state. + + 'pending' before the agent begins work; 'running' while producing or revising; + 'evaluating' while the grader scores; + 'satisfied'/'max_iterations_reached'/'failed'/'interrupted' are terminal. + """ + + type: Literal["outcome_evaluation"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_session.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_session.py new file mode 100644 index 0000000000000000000000000000000000000000..e067b61a139713e1ad35f7da9cf5ec060b42f6a8 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_session.py @@ -0,0 +1,66 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, List, Optional +from datetime import datetime +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_managed_agents_session_agent import BetaManagedAgentsSessionAgent +from .beta_managed_agents_session_stats import BetaManagedAgentsSessionStats +from .beta_managed_agents_session_usage import BetaManagedAgentsSessionUsage +from .sessions.beta_managed_agents_session_resource import BetaManagedAgentsSessionResource +from .beta_managed_agents_outcome_evaluation_resource import BetaManagedAgentsOutcomeEvaluationResource + +__all__ = ["BetaManagedAgentsSession"] + + +class BetaManagedAgentsSession(BaseModel): + """A Managed Agents `session`.""" + + id: str + + agent: BetaManagedAgentsSessionAgent + """Resolved `agent` definition for a `session`. + + Snapshot of the `agent` at `session` creation time. + """ + + archived_at: Optional[datetime] = None + """A timestamp in RFC 3339 format""" + + created_at: datetime + """A timestamp in RFC 3339 format""" + + environment_id: str + + metadata: Dict[str, str] + + outcome_evaluations: List[BetaManagedAgentsOutcomeEvaluationResource] + """Per-outcome evaluation state. + + One entry per define_outcome event sent to the session. + """ + + resources: List[BetaManagedAgentsSessionResource] + + stats: BetaManagedAgentsSessionStats + """Timing statistics for a session.""" + + status: Literal["rescheduling", "running", "idle", "terminated"] + """SessionStatus enum""" + + title: Optional[str] = None + + type: Literal["session"] + + updated_at: datetime + """A timestamp in RFC 3339 format""" + + usage: BetaManagedAgentsSessionUsage + """Cumulative token usage for a session across all turns.""" + + vault_ids: List[str] + """Vault IDs attached to the session at creation. + + Empty when no vaults were supplied. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_session_agent.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_session_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..9e7e12dd526ea7990baba373aae160bdddf57876 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_session_agent.py @@ -0,0 +1,60 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .beta_managed_agents_custom_tool import BetaManagedAgentsCustomTool +from .beta_managed_agents_mcp_toolset import BetaManagedAgentsMCPToolset +from .beta_managed_agents_custom_skill import BetaManagedAgentsCustomSkill +from .beta_managed_agents_model_config import BetaManagedAgentsModelConfig +from .beta_managed_agents_anthropic_skill import BetaManagedAgentsAnthropicSkill +from .beta_managed_agents_agent_toolset20260401 import BetaManagedAgentsAgentToolset20260401 +from .beta_managed_agents_mcp_server_url_definition import BetaManagedAgentsMCPServerURLDefinition +from .beta_managed_agents_session_multiagent_coordinator import BetaManagedAgentsSessionMultiagentCoordinator + +__all__ = ["BetaManagedAgentsSessionAgent", "Skill", "Tool"] + +Skill: TypeAlias = Annotated[ + Union[BetaManagedAgentsAnthropicSkill, BetaManagedAgentsCustomSkill], PropertyInfo(discriminator="type") +] + +Tool: TypeAlias = Annotated[ + Union[BetaManagedAgentsAgentToolset20260401, BetaManagedAgentsMCPToolset, BetaManagedAgentsCustomTool], + PropertyInfo(discriminator="type"), +] + + +class BetaManagedAgentsSessionAgent(BaseModel): + """Resolved `agent` definition for a `session`. + + Snapshot of the `agent` at `session` creation time. + """ + + id: str + + description: Optional[str] = None + + mcp_servers: List[BetaManagedAgentsMCPServerURLDefinition] + + model: BetaManagedAgentsModelConfig + """Model identifier and configuration.""" + + multiagent: Optional[BetaManagedAgentsSessionMultiagentCoordinator] = None + """ + Resolved coordinator topology with full agent definitions for each roster + member. + """ + + name: str + + skills: List[Skill] + + system: Optional[str] = None + + tools: List[Tool] + + type: Literal["agent"] + + version: int diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_session_multiagent_coordinator.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_session_multiagent_coordinator.py new file mode 100644 index 0000000000000000000000000000000000000000..95182ae6c747e69895f56abaa6613dd980350403 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_session_multiagent_coordinator.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List +from typing_extensions import Literal + +from ..._models import BaseModel +from .sessions.beta_managed_agents_session_thread_agent import BetaManagedAgentsSessionThreadAgent + +__all__ = ["BetaManagedAgentsSessionMultiagentCoordinator"] + + +class BetaManagedAgentsSessionMultiagentCoordinator(BaseModel): + """ + Resolved coordinator topology with full agent definitions for each roster member. + """ + + agents: List[BetaManagedAgentsSessionThreadAgent] + """Full `agent` definitions the coordinator may spawn as session threads.""" + + type: Literal["coordinator"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_session_stats.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_session_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..df14e0e5ee0b481f7ee5d4b607372ed3b57b5dfa --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_session_stats.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ..._models import BaseModel + +__all__ = ["BetaManagedAgentsSessionStats"] + + +class BetaManagedAgentsSessionStats(BaseModel): + """Timing statistics for a session.""" + + active_seconds: Optional[float] = None + """Cumulative time in seconds the session spent in running status. + + Excludes idle time. + """ + + duration_seconds: Optional[float] = None + """Elapsed time since session creation in seconds. + + For terminated sessions, frozen at the final update. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_session_usage.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_session_usage.py new file mode 100644 index 0000000000000000000000000000000000000000..8b81d375acce88c566633f3e931867fa974e35cf --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_session_usage.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ..._models import BaseModel +from .beta_managed_agents_cache_creation_usage import BetaManagedAgentsCacheCreationUsage + +__all__ = ["BetaManagedAgentsSessionUsage"] + + +class BetaManagedAgentsSessionUsage(BaseModel): + """Cumulative token usage for a session across all turns.""" + + cache_creation: Optional[BetaManagedAgentsCacheCreationUsage] = None + """Prompt-cache creation token usage broken down by cache lifetime.""" + + cache_read_input_tokens: Optional[int] = None + """Total tokens read from prompt cache.""" + + input_tokens: Optional[int] = None + """Total input tokens consumed across all turns.""" + + output_tokens: Optional[int] = None + """Total output tokens generated across all turns.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_skill_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_skill_params.py new file mode 100644 index 0000000000000000000000000000000000000000..972393a9c6a7133db67658e9053560701535425b --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_skill_params.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .beta_managed_agents_custom_skill_params import BetaManagedAgentsCustomSkillParams +from .beta_managed_agents_anthropic_skill_params import BetaManagedAgentsAnthropicSkillParams + +__all__ = ["BetaManagedAgentsSkillParams"] + +BetaManagedAgentsSkillParams: TypeAlias = Union[ + BetaManagedAgentsAnthropicSkillParams, BetaManagedAgentsCustomSkillParams +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_url_mcp_server_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_url_mcp_server_params.py new file mode 100644 index 0000000000000000000000000000000000000000..8783b06e59f3bc259303c57d2819869c10d87248 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_managed_agents_url_mcp_server_params.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaManagedAgentsURLMCPServerParams"] + + +class BetaManagedAgentsURLMCPServerParams(TypedDict, total=False): + """URL-based MCP server connection.""" + + name: Required[str] + """Unique name for this server, referenced by mcp_toolset configurations. + + 1-255 characters. + """ + + type: Required[Literal["url"]] + + url: Required[str] + """Endpoint URL for the MCP server.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_mcp_tool_config_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_mcp_tool_config_param.py new file mode 100644 index 0000000000000000000000000000000000000000..088992a170a23948f2d1c1cbe98232f00260bdc8 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_mcp_tool_config_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["BetaMCPToolConfigParam"] + + +class BetaMCPToolConfigParam(TypedDict, total=False): + """Configuration for a specific tool in an MCP toolset.""" + + defer_loading: bool + + enabled: bool diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_mcp_tool_default_config_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_mcp_tool_default_config_param.py new file mode 100644 index 0000000000000000000000000000000000000000..865416fff5044328ba4d396ff23d0f7bcf1f1b32 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_mcp_tool_default_config_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["BetaMCPToolDefaultConfigParam"] + + +class BetaMCPToolDefaultConfigParam(TypedDict, total=False): + """Default configuration for tools in an MCP toolset.""" + + defer_loading: bool + + enabled: bool diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_mcp_tool_result_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_mcp_tool_result_block.py new file mode 100644 index 0000000000000000000000000000000000000000..3be6ffd7d42858042c58ee9ae4bb18418401d5d3 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_mcp_tool_result_block.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_text_block import BetaTextBlock + +__all__ = ["BetaMCPToolResultBlock"] + + +class BetaMCPToolResultBlock(BaseModel): + content: Union[str, List[BetaTextBlock]] + + is_error: bool + + tool_use_id: str + + type: Literal["mcp_tool_result"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_mcp_tool_use_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_mcp_tool_use_block.py new file mode 100644 index 0000000000000000000000000000000000000000..32cabdbf5fd5acf81211fdc2d062e732fe2ccbdc --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_mcp_tool_use_block.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaMCPToolUseBlock"] + + +class BetaMCPToolUseBlock(BaseModel): + id: str + + input: Dict[str, object] + + name: str + """The name of the MCP tool""" + + server_name: str + """The name of the MCP server""" + + type: Literal["mcp_tool_use"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_mcp_tool_use_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_mcp_tool_use_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..4a67a19faf04e20191c2a06f2b692d6b15449a09 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_mcp_tool_use_block_param.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaMCPToolUseBlockParam"] + + +class BetaMCPToolUseBlockParam(TypedDict, total=False): + id: Required[str] + + input: Required[Dict[str, object]] + + name: Required[str] + + server_name: Required[str] + """The name of the MCP server""" + + type: Required[Literal["mcp_tool_use"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_mcp_toolset_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_mcp_toolset_param.py new file mode 100644 index 0000000000000000000000000000000000000000..34fbf23ed5aee634244c8d3a68e6c24bc2fc1e09 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_mcp_toolset_param.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_mcp_tool_config_param import BetaMCPToolConfigParam +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam +from .beta_mcp_tool_default_config_param import BetaMCPToolDefaultConfigParam + +__all__ = ["BetaMCPToolsetParam"] + + +class BetaMCPToolsetParam(TypedDict, total=False): + """Configuration for a group of tools from an MCP server. + + Allows configuring enabled status and defer_loading for all tools + from an MCP server, with optional per-tool overrides. + """ + + mcp_server_name: Required[str] + """Name of the MCP server to configure tools for""" + + type: Required[Literal["mcp_toolset"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + configs: Optional[Dict[str, BetaMCPToolConfigParam]] + """Configuration overrides for specific tools, keyed by tool name""" + + default_config: BetaMCPToolDefaultConfigParam + """Default configuration applied to all tools from this server""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_memory_tool_20250818_command.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_memory_tool_20250818_command.py new file mode 100644 index 0000000000000000000000000000000000000000..7ce68f8e2bcaad84f4079b946330e38fc2952197 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_memory_tool_20250818_command.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from ..._utils import PropertyInfo +from .beta_memory_tool_20250818_view_command import BetaMemoryTool20250818ViewCommand +from .beta_memory_tool_20250818_create_command import BetaMemoryTool20250818CreateCommand +from .beta_memory_tool_20250818_delete_command import BetaMemoryTool20250818DeleteCommand +from .beta_memory_tool_20250818_insert_command import BetaMemoryTool20250818InsertCommand +from .beta_memory_tool_20250818_rename_command import BetaMemoryTool20250818RenameCommand +from .beta_memory_tool_20250818_str_replace_command import BetaMemoryTool20250818StrReplaceCommand + +__all__ = ["BetaMemoryTool20250818Command"] + +BetaMemoryTool20250818Command: TypeAlias = Annotated[ + Union[ + BetaMemoryTool20250818ViewCommand, + BetaMemoryTool20250818CreateCommand, + BetaMemoryTool20250818StrReplaceCommand, + BetaMemoryTool20250818InsertCommand, + BetaMemoryTool20250818DeleteCommand, + BetaMemoryTool20250818RenameCommand, + ], + PropertyInfo(discriminator="command"), +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_memory_tool_20250818_create_command.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_memory_tool_20250818_create_command.py new file mode 100644 index 0000000000000000000000000000000000000000..bd51cdd7713c2b3b8d15c892a6f9a95baea52b87 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_memory_tool_20250818_create_command.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaMemoryTool20250818CreateCommand"] + + +class BetaMemoryTool20250818CreateCommand(BaseModel): + command: Literal["create"] + """Command type identifier""" + + file_text: str + """Content to write to the file""" + + path: str + """Path where the file should be created""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_memory_tool_20250818_insert_command.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_memory_tool_20250818_insert_command.py new file mode 100644 index 0000000000000000000000000000000000000000..1970dba00b80140433a3b6a7c31c51f3d6633bab --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_memory_tool_20250818_insert_command.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaMemoryTool20250818InsertCommand"] + + +class BetaMemoryTool20250818InsertCommand(BaseModel): + command: Literal["insert"] + """Command type identifier""" + + insert_line: int + """Line number where text should be inserted""" + + insert_text: str + """Text to insert at the specified line""" + + path: str + """Path to the file where text should be inserted""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_memory_tool_20250818_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_memory_tool_20250818_param.py new file mode 100644 index 0000000000000000000000000000000000000000..f89a65682bb3224988ee75920d206e92c8579723 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_memory_tool_20250818_param.py @@ -0,0 +1,36 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Iterable, Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaMemoryTool20250818Param"] + + +class BetaMemoryTool20250818Param(TypedDict, total=False): + name: Required[Literal["memory"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["memory_20250818"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + input_examples: Iterable[Dict[str, object]] + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_memory_tool_20250818_rename_command.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_memory_tool_20250818_rename_command.py new file mode 100644 index 0000000000000000000000000000000000000000..46e27d848799045fa5fc4a000daf7e9bf1efdc89 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_memory_tool_20250818_rename_command.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaMemoryTool20250818RenameCommand"] + + +class BetaMemoryTool20250818RenameCommand(BaseModel): + command: Literal["rename"] + """Command type identifier""" + + new_path: str + """New path for the file or directory""" + + old_path: str + """Current path of the file or directory""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_memory_tool_20250818_view_command.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_memory_tool_20250818_view_command.py new file mode 100644 index 0000000000000000000000000000000000000000..8d540bca8990f56be6c3e39a82337ebb3bb58d1e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_memory_tool_20250818_view_command.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaMemoryTool20250818ViewCommand"] + + +class BetaMemoryTool20250818ViewCommand(BaseModel): + command: Literal["view"] + """Command type identifier""" + + path: str + """Path to directory or file to view""" + + view_range: Optional[List[int]] = None + """Optional line range for viewing specific lines""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_message_delta_usage.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_message_delta_usage.py new file mode 100644 index 0000000000000000000000000000000000000000..3d18dd7af1f10bb306b1c9058474192ebd5e03b0 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_message_delta_usage.py @@ -0,0 +1,37 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ..._models import BaseModel +from .beta_iterations_usage import BetaIterationsUsage +from .beta_server_tool_usage import BetaServerToolUsage + +__all__ = ["BetaMessageDeltaUsage"] + + +class BetaMessageDeltaUsage(BaseModel): + cache_creation_input_tokens: Optional[int] = None + """The cumulative number of input tokens used to create the cache entry.""" + + cache_read_input_tokens: Optional[int] = None + """The cumulative number of input tokens read from the cache.""" + + input_tokens: Optional[int] = None + """The cumulative number of input tokens which were used.""" + + iterations: Optional[BetaIterationsUsage] = None + """Per-iteration token usage breakdown. + + Each entry represents one sampling iteration, with its own input/output token + counts and cache statistics. This allows you to: + + - Determine which iterations exceeded long context thresholds (>=200k tokens) + - Calculate the true context window size from the last iteration + - Understand token accumulation across server-side tool use loops + """ + + output_tokens: int + """The cumulative number of output tokens which were used.""" + + server_tool_use: Optional[BetaServerToolUsage] = None + """The number of server tool requests.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_message_iteration_usage.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_message_iteration_usage.py new file mode 100644 index 0000000000000000000000000000000000000000..7fd09d16e623b2e8ecc0cca7f43d8606f4a46b78 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_message_iteration_usage.py @@ -0,0 +1,31 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_cache_creation import BetaCacheCreation + +__all__ = ["BetaMessageIterationUsage"] + + +class BetaMessageIterationUsage(BaseModel): + """Token usage for a sampling iteration.""" + + cache_creation: Optional[BetaCacheCreation] = None + """Breakdown of cached tokens by TTL""" + + cache_creation_input_tokens: int + """The number of input tokens used to create the cache entry.""" + + cache_read_input_tokens: int + """The number of input tokens read from the cache.""" + + input_tokens: int + """The number of input tokens which were used.""" + + output_tokens: int + """The number of output tokens which were used.""" + + type: Literal["message"] + """Usage for a sampling iteration""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_message_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_message_param.py new file mode 100644 index 0000000000000000000000000000000000000000..b41e56d34f6fd2f212350270c1fd15737df05737 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_message_param.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import Literal, Required, TypedDict + +from .beta_content_block_param import BetaContentBlockParam + +__all__ = ["BetaMessageParam"] + + +class BetaMessageParam(TypedDict, total=False): + content: Required[Union[str, Iterable[BetaContentBlockParam]]] + + role: Required[Literal["user", "assistant"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_message_tokens_count.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_message_tokens_count.py new file mode 100644 index 0000000000000000000000000000000000000000..6a27a2b3a5b3bc7d17567d58bf55ec8f0e9cb8b5 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_message_tokens_count.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ..._models import BaseModel +from .beta_count_tokens_context_management_response import BetaCountTokensContextManagementResponse + +__all__ = ["BetaMessageTokensCount"] + + +class BetaMessageTokensCount(BaseModel): + context_management: Optional[BetaCountTokensContextManagementResponse] = None + """Information about context management applied to the message.""" + + input_tokens: int + """ + The total number of tokens across the provided list of messages, system prompt, + and tools. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_metadata_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_metadata_param.py new file mode 100644 index 0000000000000000000000000000000000000000..8ccda2165c22304f089412bad2207d836fa339a0 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_metadata_param.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["BetaMetadataParam"] + + +class BetaMetadataParam(TypedDict, total=False): + user_id: Optional[str] + """An external identifier for the user who is associated with the request. + + This should be a uuid, hash value, or other opaque identifier. Anthropic may use + this id to help detect abuse. Do not include any identifying information such as + name, email address, or phone number. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_model_capabilities.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_model_capabilities.py new file mode 100644 index 0000000000000000000000000000000000000000..d489a52a22b1c56ecc387caae95781928371db7d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_model_capabilities.py @@ -0,0 +1,40 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel +from .beta_effort_capability import BetaEffortCapability +from .beta_capability_support import BetaCapabilitySupport +from .beta_thinking_capability import BetaThinkingCapability +from .beta_context_management_capability import BetaContextManagementCapability + +__all__ = ["BetaModelCapabilities"] + + +class BetaModelCapabilities(BaseModel): + """Model capability information.""" + + batch: BetaCapabilitySupport + """Whether the model supports the Batch API.""" + + citations: BetaCapabilitySupport + """Whether the model supports citation generation.""" + + code_execution: BetaCapabilitySupport + """Whether the model supports code execution tools.""" + + context_management: BetaContextManagementCapability + """Context management support and available strategies.""" + + effort: BetaEffortCapability + """Effort (reasoning_effort) support and available levels.""" + + image_input: BetaCapabilitySupport + """Whether the model accepts image content blocks.""" + + pdf_input: BetaCapabilitySupport + """Whether the model accepts PDF content blocks.""" + + structured_outputs: BetaCapabilitySupport + """Whether the model supports structured output / JSON mode / strict tool schemas.""" + + thinking: BetaThinkingCapability + """Thinking capability and supported type configurations.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_model_info.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_model_info.py new file mode 100644 index 0000000000000000000000000000000000000000..5080d314d47d15bd694d9e2d6cebefd4087c3189 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_model_info.py @@ -0,0 +1,39 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from datetime import datetime +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_model_capabilities import BetaModelCapabilities + +__all__ = ["BetaModelInfo"] + + +class BetaModelInfo(BaseModel): + id: str + """Unique model identifier.""" + + capabilities: Optional[BetaModelCapabilities] = None + """Model capability information.""" + + created_at: datetime + """RFC 3339 datetime string representing the time at which the model was released. + + May be set to an epoch value if the release date is unknown. + """ + + display_name: str + """A human-readable name for the model.""" + + max_input_tokens: Optional[int] = None + """Maximum input context window size in tokens for this model.""" + + max_tokens: Optional[int] = None + """Maximum value for the `max_tokens` parameter when using this model.""" + + type: Literal["model"] + """Object type. + + For Models, this is always `"model"`. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_output_config_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_output_config_param.py new file mode 100644 index 0000000000000000000000000000000000000000..ec926693e9efc8d6969c7f3423b736ed6e761587 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_output_config_param.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, TypedDict + +from .beta_token_task_budget_param import BetaTokenTaskBudgetParam +from .beta_json_output_format_param import BetaJSONOutputFormatParam + +__all__ = ["BetaOutputConfigParam"] + + +class BetaOutputConfigParam(TypedDict, total=False): + effort: Optional[Literal["low", "medium", "high", "xhigh", "max"]] + """All possible effort levels.""" + + format: Optional[BetaJSONOutputFormatParam] + """A schema to specify Claude's output format in responses. + + See + [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) + """ + + task_budget: Optional[BetaTokenTaskBudgetParam] + """User-configurable total token budget across contexts.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_packages.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_packages.py new file mode 100644 index 0000000000000000000000000000000000000000..b03ffad6b4625ce7def56d99c914af1de1c52f62 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_packages.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaPackages"] + + +class BetaPackages(BaseModel): + """Packages (and their versions) available in this environment.""" + + apt: List[str] + """Ubuntu/Debian packages to install""" + + cargo: List[str] + """Rust packages to install""" + + gem: List[str] + """Ruby packages to install""" + + go: List[str] + """Go packages to install""" + + npm: List[str] + """Node.js packages to install""" + + pip: List[str] + """Python packages to install""" + + type: Optional[Literal["packages"]] = None + """Package configuration type""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_packages_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_packages_params.py new file mode 100644 index 0000000000000000000000000000000000000000..646a210b108a53b76524aebcbbb88af4f440ff4a --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_packages_params.py @@ -0,0 +1,38 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, TypedDict + +from ..._types import SequenceNotStr + +__all__ = ["BetaPackagesParams"] + + +class BetaPackagesParams(TypedDict, total=False): + """Specify packages (and optionally their versions) available in this environment. + + When versioning, use the version semantics relevant for the package manager, e.g. for `pip` use `package==1.0.0`. You are responsible for validating the package and version exist. Unversioned installs the latest. + """ + + apt: Optional[SequenceNotStr[str]] + """Ubuntu/Debian packages to install""" + + cargo: Optional[SequenceNotStr[str]] + """Rust packages to install""" + + gem: Optional[SequenceNotStr[str]] + """Ruby packages to install""" + + go: Optional[SequenceNotStr[str]] + """Go packages to install""" + + npm: Optional[SequenceNotStr[str]] + """Node.js packages to install""" + + pip: Optional[SequenceNotStr[str]] + """Python packages to install""" + + type: Literal["packages"] + """Package configuration type""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_plain_text_source.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_plain_text_source.py new file mode 100644 index 0000000000000000000000000000000000000000..17c31684837b2f68629afdec8315d39380114468 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_plain_text_source.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaPlainTextSource"] + + +class BetaPlainTextSource(BaseModel): + data: str + + media_type: Literal["text/plain"] + + type: Literal["text"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_plain_text_source_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_plain_text_source_param.py new file mode 100644 index 0000000000000000000000000000000000000000..187a238644df216404d03a0df4b5c06b5dcc2faa --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_plain_text_source_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaPlainTextSourceParam"] + + +class BetaPlainTextSourceParam(TypedDict, total=False): + data: Required[str] + + media_type: Required[Literal["text/plain"]] + + type: Required[Literal["text"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_raw_content_block_delta.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_raw_content_block_delta.py new file mode 100644 index 0000000000000000000000000000000000000000..c7a0691a787e6cb5287406803e24c9543c000335 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_raw_content_block_delta.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from ..._utils import PropertyInfo +from .beta_text_delta import BetaTextDelta +from .beta_thinking_delta import BetaThinkingDelta +from .beta_citations_delta import BetaCitationsDelta +from .beta_signature_delta import BetaSignatureDelta +from .beta_input_json_delta import BetaInputJSONDelta +from .beta_compaction_content_block_delta import BetaCompactionContentBlockDelta + +__all__ = ["BetaRawContentBlockDelta"] + +BetaRawContentBlockDelta: TypeAlias = Annotated[ + Union[ + BetaTextDelta, + BetaInputJSONDelta, + BetaCitationsDelta, + BetaThinkingDelta, + BetaSignatureDelta, + BetaCompactionContentBlockDelta, + ], + PropertyInfo(discriminator="type"), +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_raw_content_block_start_event.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_raw_content_block_start_event.py new file mode 100644 index 0000000000000000000000000000000000000000..8cd048837b0109bbf1572c94f28232e2cadfc83c --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_raw_content_block_start_event.py @@ -0,0 +1,56 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Literal, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .beta_text_block import BetaTextBlock +from .beta_thinking_block import BetaThinkingBlock +from .beta_tool_use_block import BetaToolUseBlock +from .beta_compaction_block import BetaCompactionBlock +from .beta_mcp_tool_use_block import BetaMCPToolUseBlock +from .beta_mcp_tool_result_block import BetaMCPToolResultBlock +from .beta_server_tool_use_block import BetaServerToolUseBlock +from .beta_container_upload_block import BetaContainerUploadBlock +from .beta_redacted_thinking_block import BetaRedactedThinkingBlock +from .beta_advisor_tool_result_block import BetaAdvisorToolResultBlock +from .beta_web_fetch_tool_result_block import BetaWebFetchToolResultBlock +from .beta_web_search_tool_result_block import BetaWebSearchToolResultBlock +from .beta_tool_search_tool_result_block import BetaToolSearchToolResultBlock +from .beta_code_execution_tool_result_block import BetaCodeExecutionToolResultBlock +from .beta_bash_code_execution_tool_result_block import BetaBashCodeExecutionToolResultBlock +from .beta_text_editor_code_execution_tool_result_block import BetaTextEditorCodeExecutionToolResultBlock + +__all__ = ["BetaRawContentBlockStartEvent", "ContentBlock"] + +ContentBlock: TypeAlias = Annotated[ + Union[ + BetaTextBlock, + BetaThinkingBlock, + BetaRedactedThinkingBlock, + BetaToolUseBlock, + BetaServerToolUseBlock, + BetaWebSearchToolResultBlock, + BetaWebFetchToolResultBlock, + BetaAdvisorToolResultBlock, + BetaCodeExecutionToolResultBlock, + BetaBashCodeExecutionToolResultBlock, + BetaTextEditorCodeExecutionToolResultBlock, + BetaToolSearchToolResultBlock, + BetaMCPToolUseBlock, + BetaMCPToolResultBlock, + BetaContainerUploadBlock, + BetaCompactionBlock, + ], + PropertyInfo(discriminator="type"), +] + + +class BetaRawContentBlockStartEvent(BaseModel): + content_block: ContentBlock + """Response model for a file uploaded to the container.""" + + index: int + + type: Literal["content_block_start"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_raw_content_block_stop_event.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_raw_content_block_stop_event.py new file mode 100644 index 0000000000000000000000000000000000000000..d85518603302e8b958fe2dde7678f7a286ea2607 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_raw_content_block_stop_event.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaRawContentBlockStopEvent"] + + +class BetaRawContentBlockStopEvent(BaseModel): + index: int + + type: Literal["content_block_stop"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_raw_message_delta_event.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_raw_message_delta_event.py new file mode 100644 index 0000000000000000000000000000000000000000..a57b80ae6dcb44b81b1f2c41eb10e97830527217 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_raw_message_delta_event.py @@ -0,0 +1,55 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_container import BetaContainer +from .beta_stop_reason import BetaStopReason +from .beta_message_delta_usage import BetaMessageDeltaUsage +from .beta_refusal_stop_details import BetaRefusalStopDetails +from .beta_context_management_response import BetaContextManagementResponse + +__all__ = ["BetaRawMessageDeltaEvent", "Delta"] + + +class Delta(BaseModel): + container: Optional[BetaContainer] = None + """ + Information about the container used in the request (for the code execution + tool) + """ + + stop_details: Optional[BetaRefusalStopDetails] = None + """Structured information about a refusal.""" + + stop_reason: Optional[BetaStopReason] = None + + stop_sequence: Optional[str] = None + + +class BetaRawMessageDeltaEvent(BaseModel): + context_management: Optional[BetaContextManagementResponse] = None + """Information about context management strategies applied during the request""" + + delta: Delta + + type: Literal["message_delta"] + + usage: BetaMessageDeltaUsage + """Billing and rate-limit usage. + + Anthropic's API bills and rate-limits by token counts, as tokens represent the + underlying cost to our systems. + + Under the hood, the API transforms requests into a format suitable for the + model. The model's output then goes through a parsing stage before becoming an + API response. As a result, the token counts in `usage` will not match one-to-one + with the exact visible content of an API request or response. + + For example, `output_tokens` will be non-zero, even for an empty string response + from Claude. + + Total input tokens in a request is the summation of `input_tokens`, + `cache_creation_input_tokens`, and `cache_read_input_tokens`. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_raw_message_start_event.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_raw_message_start_event.py new file mode 100644 index 0000000000000000000000000000000000000000..9bb16f948bd360429d8f90e4d311a45c9dd6c639 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_raw_message_start_event.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_message import BetaMessage + +__all__ = ["BetaRawMessageStartEvent"] + + +class BetaRawMessageStartEvent(BaseModel): + message: BetaMessage + + type: Literal["message_start"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_raw_message_stream_event.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_raw_message_stream_event.py new file mode 100644 index 0000000000000000000000000000000000000000..00ffd7c16889e5c990eee1be5b5fce87f5261f39 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_raw_message_stream_event.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from ..._utils import PropertyInfo +from .beta_raw_message_stop_event import BetaRawMessageStopEvent +from .beta_raw_message_delta_event import BetaRawMessageDeltaEvent +from .beta_raw_message_start_event import BetaRawMessageStartEvent +from .beta_raw_content_block_stop_event import BetaRawContentBlockStopEvent +from .beta_raw_content_block_delta_event import BetaRawContentBlockDeltaEvent +from .beta_raw_content_block_start_event import BetaRawContentBlockStartEvent + +__all__ = ["BetaRawMessageStreamEvent"] + +BetaRawMessageStreamEvent: TypeAlias = Annotated[ + Union[ + BetaRawMessageStartEvent, + BetaRawMessageDeltaEvent, + BetaRawMessageStopEvent, + BetaRawContentBlockStartEvent, + BetaRawContentBlockDeltaEvent, + BetaRawContentBlockStopEvent, + ], + PropertyInfo(discriminator="type"), +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_redacted_thinking_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_redacted_thinking_block.py new file mode 100644 index 0000000000000000000000000000000000000000..b27bd933278804b6b233eacc1420846c2082e2f4 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_redacted_thinking_block.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaRedactedThinkingBlock"] + + +class BetaRedactedThinkingBlock(BaseModel): + data: str + + type: Literal["redacted_thinking"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_redacted_thinking_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_redacted_thinking_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..cc7d870f07d785936979061ebd2c024240d13aac --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_redacted_thinking_block_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaRedactedThinkingBlockParam"] + + +class BetaRedactedThinkingBlockParam(TypedDict, total=False): + data: Required[str] + + type: Required[Literal["redacted_thinking"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_refusal_stop_details.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_refusal_stop_details.py new file mode 100644 index 0000000000000000000000000000000000000000..d613ea8afc9ec1a42410c3cf822cceed9ebc74b9 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_refusal_stop_details.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaRefusalStopDetails"] + + +class BetaRefusalStopDetails(BaseModel): + """Structured information about a refusal.""" + + category: Optional[Literal["cyber", "bio"]] = None + """The policy category that triggered the refusal. + + `null` when the refusal doesn't map to a named category. + """ + + explanation: Optional[str] = None + """Human-readable explanation of the refusal. + + This text is not guaranteed to be stable. `null` when no explanation is + available for the category. + """ + + type: Literal["refusal"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_request_document_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_request_document_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..2b582ecb1e4f5b89dcc21931bee7500e6938c011 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_request_document_block_param.py @@ -0,0 +1,39 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .beta_url_pdf_source_param import BetaURLPDFSourceParam +from .beta_citations_config_param import BetaCitationsConfigParam +from .beta_base64_pdf_source_param import BetaBase64PDFSourceParam +from .beta_plain_text_source_param import BetaPlainTextSourceParam +from .beta_content_block_source_param import BetaContentBlockSourceParam +from .beta_file_document_source_param import BetaFileDocumentSourceParam +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaRequestDocumentBlockParam", "Source"] + +Source: TypeAlias = Union[ + BetaBase64PDFSourceParam, + BetaPlainTextSourceParam, + BetaContentBlockSourceParam, + BetaURLPDFSourceParam, + BetaFileDocumentSourceParam, +] + + +class BetaRequestDocumentBlockParam(TypedDict, total=False): + source: Required[Source] + + type: Required[Literal["document"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + citations: Optional[BetaCitationsConfigParam] + + context: Optional[str] + + title: Optional[str] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_request_mcp_server_tool_configuration_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_request_mcp_server_tool_configuration_param.py new file mode 100644 index 0000000000000000000000000000000000000000..4edd81257a6719c9e7f49075811cc50eb8324b11 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_request_mcp_server_tool_configuration_param.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +from ..._types import SequenceNotStr + +__all__ = ["BetaRequestMCPServerToolConfigurationParam"] + + +class BetaRequestMCPServerToolConfigurationParam(TypedDict, total=False): + allowed_tools: Optional[SequenceNotStr[str]] + + enabled: Optional[bool] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_request_mcp_server_url_definition_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_request_mcp_server_url_definition_param.py new file mode 100644 index 0000000000000000000000000000000000000000..d897c8575ec0b1c8fbb014bc6a37f71493cf2f83 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_request_mcp_server_url_definition_param.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_request_mcp_server_tool_configuration_param import BetaRequestMCPServerToolConfigurationParam + +__all__ = ["BetaRequestMCPServerURLDefinitionParam"] + + +class BetaRequestMCPServerURLDefinitionParam(TypedDict, total=False): + name: Required[str] + + type: Required[Literal["url"]] + + url: Required[str] + + authorization_token: Optional[str] + + tool_configuration: Optional[BetaRequestMCPServerToolConfigurationParam] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_request_mcp_tool_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_request_mcp_tool_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..c32d2c5e370ffdbc31ce64652725829df3146133 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_request_mcp_tool_result_block_param.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable, Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_text_block_param import BetaTextBlockParam +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaRequestMCPToolResultBlockParam"] + + +class BetaRequestMCPToolResultBlockParam(TypedDict, total=False): + tool_use_id: Required[str] + + type: Required[Literal["mcp_tool_result"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + content: Union[str, Iterable[BetaTextBlockParam]] + + is_error: bool diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_server_tool_caller.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_server_tool_caller.py new file mode 100644 index 0000000000000000000000000000000000000000..ecd4bdeb508a232531707e74c87c5a2a03457c45 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_server_tool_caller.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaServerToolCaller"] + + +class BetaServerToolCaller(BaseModel): + """Tool invocation generated by a server-side tool.""" + + tool_id: str + + type: Literal["code_execution_20250825"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_server_tool_caller_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_server_tool_caller_param.py new file mode 100644 index 0000000000000000000000000000000000000000..ab83443787e039cc9209337310f52a4ab5dd1de4 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_server_tool_caller_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaServerToolCallerParam"] + + +class BetaServerToolCallerParam(TypedDict, total=False): + """Tool invocation generated by a server-side tool.""" + + tool_id: Required[str] + + type: Required[Literal["code_execution_20250825"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_server_tool_usage.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_server_tool_usage.py new file mode 100644 index 0000000000000000000000000000000000000000..2c64588005d0b9c4b7b44994d10c39267ce02214 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_server_tool_usage.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["BetaServerToolUsage"] + + +class BetaServerToolUsage(BaseModel): + web_fetch_requests: int + """The number of web fetch tool requests.""" + + web_search_requests: int + """The number of web search tool requests.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_server_tool_use_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_server_tool_use_block.py new file mode 100644 index 0000000000000000000000000000000000000000..e4d14f63e612fe7b25ce3bb2d2d1bcbe228272d3 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_server_tool_use_block.py @@ -0,0 +1,38 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .beta_direct_caller import BetaDirectCaller +from .beta_server_tool_caller import BetaServerToolCaller +from .beta_server_tool_caller_20260120 import BetaServerToolCaller20260120 + +__all__ = ["BetaServerToolUseBlock", "Caller"] + +Caller: TypeAlias = Annotated[ + Union[BetaDirectCaller, BetaServerToolCaller, BetaServerToolCaller20260120], PropertyInfo(discriminator="type") +] + + +class BetaServerToolUseBlock(BaseModel): + id: str + + input: Dict[str, object] + + name: Literal[ + "advisor", + "web_search", + "web_fetch", + "code_execution", + "bash_code_execution", + "text_editor_code_execution", + "tool_search_tool_regex", + "tool_search_tool_bm25", + ] + + type: Literal["server_tool_use"] + + caller: Optional[Caller] = None + """Tool invocation directly from the model.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_skill.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_skill.py new file mode 100644 index 0000000000000000000000000000000000000000..d8952290e4afe650216c6416fdbbdcb1601b8f57 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_skill.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaSkill"] + + +class BetaSkill(BaseModel): + """A skill that was loaded in a container (response model).""" + + skill_id: str + """Skill ID""" + + type: Literal["anthropic", "custom"] + """Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined)""" + + version: str + """Skill version or 'latest' for most recent version""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_skill_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_skill_params.py new file mode 100644 index 0000000000000000000000000000000000000000..b33f7bf5d0942cb80fe39c8d5b662f1d5d88e10d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_skill_params.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaSkillParams"] + + +class BetaSkillParams(TypedDict, total=False): + """Specification for a skill to be loaded in a container (request model).""" + + skill_id: Required[str] + """Skill ID""" + + type: Required[Literal["anthropic", "custom"]] + """Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined)""" + + version: str + """Skill version or 'latest' for most recent version""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_stop_reason.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_stop_reason.py new file mode 100644 index 0000000000000000000000000000000000000000..910b2682fc5b5dad9636f5b2a1995bafe3a6bb3e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_stop_reason.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["BetaStopReason"] + +BetaStopReason: TypeAlias = Literal[ + "end_turn", + "max_tokens", + "stop_sequence", + "tool_use", + "pause_turn", + "compaction", + "refusal", + "model_context_window_exceeded", +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_block.py new file mode 100644 index 0000000000000000000000000000000000000000..f6374b4128201f6e33015512dd49fbf98d1ae68f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_block.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_text_citation import BetaTextCitation + +__all__ = ["BetaTextBlock"] + + +class BetaTextBlock(BaseModel): + citations: Optional[List[BetaTextCitation]] = None + """Citations supporting the text block. + + The type of citation returned will depend on the type of document being cited. + Citing a PDF results in `page_location`, plain text results in `char_location`, + and content document results in `content_block_location`. + """ + + text: str + + type: Literal["text"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..066f561510f106c4019e4343bb587af06ec0a42f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_block_param.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable, Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_text_citation_param import BetaTextCitationParam +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaTextBlockParam"] + + +class BetaTextBlockParam(TypedDict, total=False): + text: Required[str] + + type: Required[Literal["text"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + citations: Optional[Iterable[BetaTextCitationParam]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_citation.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_citation.py new file mode 100644 index 0000000000000000000000000000000000000000..96b98ec4295cb3c2b5a21ec57adc598fefa96317 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_citation.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from ..._utils import PropertyInfo +from .beta_citation_char_location import BetaCitationCharLocation +from .beta_citation_page_location import BetaCitationPageLocation +from .beta_citation_content_block_location import BetaCitationContentBlockLocation +from .beta_citation_search_result_location import BetaCitationSearchResultLocation +from .beta_citations_web_search_result_location import BetaCitationsWebSearchResultLocation + +__all__ = ["BetaTextCitation"] + +BetaTextCitation: TypeAlias = Annotated[ + Union[ + BetaCitationCharLocation, + BetaCitationPageLocation, + BetaCitationContentBlockLocation, + BetaCitationsWebSearchResultLocation, + BetaCitationSearchResultLocation, + ], + PropertyInfo(discriminator="type"), +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_delta.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_delta.py new file mode 100644 index 0000000000000000000000000000000000000000..b94ba5ea26b7cb407738d3c246c1fb861c7c6986 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_delta.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaTextDelta"] + + +class BetaTextDelta(BaseModel): + text: str + + type: Literal["text_delta"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_str_replace_result_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_str_replace_result_block.py new file mode 100644 index 0000000000000000000000000000000000000000..770475bfc30ee2f6dfd5cc70701e13c07c82e7aa --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_str_replace_result_block.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaTextEditorCodeExecutionStrReplaceResultBlock"] + + +class BetaTextEditorCodeExecutionStrReplaceResultBlock(BaseModel): + lines: Optional[List[str]] = None + + new_lines: Optional[int] = None + + new_start: Optional[int] = None + + old_lines: Optional[int] = None + + old_start: Optional[int] = None + + type: Literal["text_editor_code_execution_str_replace_result"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_str_replace_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_str_replace_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..a2daccc5ee7fc2967be0b280e9f91bbe9456448f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_str_replace_result_block_param.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +from ..._types import SequenceNotStr + +__all__ = ["BetaTextEditorCodeExecutionStrReplaceResultBlockParam"] + + +class BetaTextEditorCodeExecutionStrReplaceResultBlockParam(TypedDict, total=False): + type: Required[Literal["text_editor_code_execution_str_replace_result"]] + + lines: Optional[SequenceNotStr[str]] + + new_lines: Optional[int] + + new_start: Optional[int] + + old_lines: Optional[int] + + old_start: Optional[int] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_tool_result_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_tool_result_block.py new file mode 100644 index 0000000000000000000000000000000000000000..326c093b8667cec0d9637d44d894e8bdc84a7515 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_tool_result_block.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Literal, TypeAlias + +from ..._models import BaseModel +from .beta_text_editor_code_execution_tool_result_error import BetaTextEditorCodeExecutionToolResultError +from .beta_text_editor_code_execution_view_result_block import BetaTextEditorCodeExecutionViewResultBlock +from .beta_text_editor_code_execution_create_result_block import BetaTextEditorCodeExecutionCreateResultBlock +from .beta_text_editor_code_execution_str_replace_result_block import BetaTextEditorCodeExecutionStrReplaceResultBlock + +__all__ = ["BetaTextEditorCodeExecutionToolResultBlock", "Content"] + +Content: TypeAlias = Union[ + BetaTextEditorCodeExecutionToolResultError, + BetaTextEditorCodeExecutionViewResultBlock, + BetaTextEditorCodeExecutionCreateResultBlock, + BetaTextEditorCodeExecutionStrReplaceResultBlock, +] + + +class BetaTextEditorCodeExecutionToolResultBlock(BaseModel): + content: Content + + tool_use_id: str + + type: Literal["text_editor_code_execution_tool_result"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_tool_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_tool_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..c56709ca45e80e96efcf4c80ccf78c4c5db40640 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_tool_result_block_param.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam +from .beta_text_editor_code_execution_tool_result_error_param import BetaTextEditorCodeExecutionToolResultErrorParam +from .beta_text_editor_code_execution_view_result_block_param import BetaTextEditorCodeExecutionViewResultBlockParam +from .beta_text_editor_code_execution_create_result_block_param import BetaTextEditorCodeExecutionCreateResultBlockParam +from .beta_text_editor_code_execution_str_replace_result_block_param import ( + BetaTextEditorCodeExecutionStrReplaceResultBlockParam, +) + +__all__ = ["BetaTextEditorCodeExecutionToolResultBlockParam", "Content"] + +Content: TypeAlias = Union[ + BetaTextEditorCodeExecutionToolResultErrorParam, + BetaTextEditorCodeExecutionViewResultBlockParam, + BetaTextEditorCodeExecutionCreateResultBlockParam, + BetaTextEditorCodeExecutionStrReplaceResultBlockParam, +] + + +class BetaTextEditorCodeExecutionToolResultBlockParam(TypedDict, total=False): + content: Required[Content] + + tool_use_id: Required[str] + + type: Required[Literal["text_editor_code_execution_tool_result"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_tool_result_error.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_tool_result_error.py new file mode 100644 index 0000000000000000000000000000000000000000..303ff15f5be31d7adfaf9a383c8a875b26a9e64c --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_tool_result_error.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaTextEditorCodeExecutionToolResultError"] + + +class BetaTextEditorCodeExecutionToolResultError(BaseModel): + error_code: Literal[ + "invalid_tool_input", "unavailable", "too_many_requests", "execution_time_exceeded", "file_not_found" + ] + + error_message: Optional[str] = None + + type: Literal["text_editor_code_execution_tool_result_error"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_tool_result_error_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_tool_result_error_param.py new file mode 100644 index 0000000000000000000000000000000000000000..5b26ca9fa1d61a06294cd6eaf925f080d29716ba --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_tool_result_error_param.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaTextEditorCodeExecutionToolResultErrorParam"] + + +class BetaTextEditorCodeExecutionToolResultErrorParam(TypedDict, total=False): + error_code: Required[ + Literal["invalid_tool_input", "unavailable", "too_many_requests", "execution_time_exceeded", "file_not_found"] + ] + + type: Required[Literal["text_editor_code_execution_tool_result_error"]] + + error_message: Optional[str] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_view_result_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_view_result_block.py new file mode 100644 index 0000000000000000000000000000000000000000..8eb22bab2d9362155965c90449578ff383188a4d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_view_result_block.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaTextEditorCodeExecutionViewResultBlock"] + + +class BetaTextEditorCodeExecutionViewResultBlock(BaseModel): + content: str + + file_type: Literal["text", "image", "pdf"] + + num_lines: Optional[int] = None + + start_line: Optional[int] = None + + total_lines: Optional[int] = None + + type: Literal["text_editor_code_execution_view_result"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_view_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_view_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..ff8f0b798842c0caba8159bfa4a5981e5404b67e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_text_editor_code_execution_view_result_block_param.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaTextEditorCodeExecutionViewResultBlockParam"] + + +class BetaTextEditorCodeExecutionViewResultBlockParam(TypedDict, total=False): + content: Required[str] + + file_type: Required[Literal["text", "image", "pdf"]] + + type: Required[Literal["text_editor_code_execution_view_result"]] + + num_lines: Optional[int] + + start_line: Optional[int] + + total_lines: Optional[int] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd43180072449100edb620b68d8c54854c02431 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_block_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaThinkingBlockParam"] + + +class BetaThinkingBlockParam(TypedDict, total=False): + signature: Required[str] + + thinking: Required[str] + + type: Required[Literal["thinking"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_capability.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_capability.py new file mode 100644 index 0000000000000000000000000000000000000000..c1bf545bb65aa06c900866cab03561937411ada5 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_capability.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel +from .beta_thinking_types import BetaThinkingTypes + +__all__ = ["BetaThinkingCapability"] + + +class BetaThinkingCapability(BaseModel): + """Thinking capability details.""" + + supported: bool + """Whether this capability is supported by the model.""" + + types: BetaThinkingTypes + """Supported thinking type configurations.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_config_adaptive_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_config_adaptive_param.py new file mode 100644 index 0000000000000000000000000000000000000000..bd755e0536f1b53007248b812fc1c01b951bfbd4 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_config_adaptive_param.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaThinkingConfigAdaptiveParam"] + + +class BetaThinkingConfigAdaptiveParam(TypedDict, total=False): + type: Required[Literal["adaptive"]] + + display: Optional[Literal["summarized", "omitted"]] + """Controls how thinking content appears in the response. + + When set to `summarized`, thinking is returned normally. When set to `omitted`, + thinking content is redacted but a signature is returned for multi-turn + continuity. Defaults to `summarized`. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_config_disabled_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_config_disabled_param.py new file mode 100644 index 0000000000000000000000000000000000000000..e7c4a2a09c226bcc2624818c274846e29bf18ecd --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_config_disabled_param.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaThinkingConfigDisabledParam"] + + +class BetaThinkingConfigDisabledParam(TypedDict, total=False): + type: Required[Literal["disabled"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_config_enabled_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_config_enabled_param.py new file mode 100644 index 0000000000000000000000000000000000000000..6ba9397c88563467b8f8ecc15f2bbf3a998df80b --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_config_enabled_param.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaThinkingConfigEnabledParam"] + + +class BetaThinkingConfigEnabledParam(TypedDict, total=False): + budget_tokens: Required[int] + """Determines how many tokens Claude can use for its internal reasoning process. + + Larger budgets can enable more thorough analysis for complex problems, improving + response quality. + + Must be ≥1024 and less than `max_tokens`. + + See + [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) + for details. + """ + + type: Required[Literal["enabled"]] + + display: Optional[Literal["summarized", "omitted"]] + """Controls how thinking content appears in the response. + + When set to `summarized`, thinking is returned normally. When set to `omitted`, + thinking content is redacted but a signature is returned for multi-turn + continuity. Defaults to `summarized`. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_config_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_config_param.py new file mode 100644 index 0000000000000000000000000000000000000000..aaf1fa2c3ae830391cfa49b0ce27207fecfe8a1a --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_config_param.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .beta_thinking_config_enabled_param import BetaThinkingConfigEnabledParam +from .beta_thinking_config_adaptive_param import BetaThinkingConfigAdaptiveParam +from .beta_thinking_config_disabled_param import BetaThinkingConfigDisabledParam + +__all__ = ["BetaThinkingConfigParam"] + +BetaThinkingConfigParam: TypeAlias = Union[ + BetaThinkingConfigEnabledParam, BetaThinkingConfigDisabledParam, BetaThinkingConfigAdaptiveParam +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_delta.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_delta.py new file mode 100644 index 0000000000000000000000000000000000000000..790a304e068f0e112cc76147c545bf0d6db2b227 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_delta.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaThinkingDelta"] + + +class BetaThinkingDelta(BaseModel): + thinking: str + + type: Literal["thinking_delta"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_turns_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_turns_param.py new file mode 100644 index 0000000000000000000000000000000000000000..7dd5450753db8249fe27150325e9cb6566285e3e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_turns_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaThinkingTurnsParam"] + + +class BetaThinkingTurnsParam(TypedDict, total=False): + type: Required[Literal["thinking_turns"]] + + value: Required[int] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_types.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_types.py new file mode 100644 index 0000000000000000000000000000000000000000..3246681af280132a73d5dba0358a61021c5958d2 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_thinking_types.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel +from .beta_capability_support import BetaCapabilitySupport + +__all__ = ["BetaThinkingTypes"] + + +class BetaThinkingTypes(BaseModel): + """Supported thinking type configurations.""" + + adaptive: BetaCapabilitySupport + """Whether the model supports thinking with type 'adaptive' (auto).""" + + enabled: BetaCapabilitySupport + """Whether the model supports thinking with type 'enabled'.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_bash_20241022_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_bash_20241022_param.py new file mode 100644 index 0000000000000000000000000000000000000000..ef342f637c4f0a74e43ec7e94867365194cfdda2 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_bash_20241022_param.py @@ -0,0 +1,36 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Iterable, Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaToolBash20241022Param"] + + +class BetaToolBash20241022Param(TypedDict, total=False): + name: Required[Literal["bash"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["bash_20241022"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + input_examples: Iterable[Dict[str, object]] + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_bash_20250124_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_bash_20250124_param.py new file mode 100644 index 0000000000000000000000000000000000000000..6394a1cafd77ac0d8c790931184c3cb976ac4962 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_bash_20250124_param.py @@ -0,0 +1,36 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Iterable, Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaToolBash20250124Param"] + + +class BetaToolBash20250124Param(TypedDict, total=False): + name: Required[Literal["bash"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["bash_20250124"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + input_examples: Iterable[Dict[str, object]] + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_choice_any_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_choice_any_param.py new file mode 100644 index 0000000000000000000000000000000000000000..4d3513ef771106a2772788e2062c5ddd3d77fd70 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_choice_any_param.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaToolChoiceAnyParam"] + + +class BetaToolChoiceAnyParam(TypedDict, total=False): + """The model will use any available tools.""" + + type: Required[Literal["any"]] + + disable_parallel_tool_use: bool + """Whether to disable parallel tool use. + + Defaults to `false`. If set to `true`, the model will output exactly one tool + use. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_choice_auto_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_choice_auto_param.py new file mode 100644 index 0000000000000000000000000000000000000000..97a52aded60cce3e6d3eb1e0aecbcaf3d2017ac4 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_choice_auto_param.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaToolChoiceAutoParam"] + + +class BetaToolChoiceAutoParam(TypedDict, total=False): + """The model will automatically decide whether to use tools.""" + + type: Required[Literal["auto"]] + + disable_parallel_tool_use: bool + """Whether to disable parallel tool use. + + Defaults to `false`. If set to `true`, the model will output at most one tool + use. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_choice_none_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_choice_none_param.py new file mode 100644 index 0000000000000000000000000000000000000000..84612db710642eee52f4c8a1c9d17b02a72ef763 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_choice_none_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaToolChoiceNoneParam"] + + +class BetaToolChoiceNoneParam(TypedDict, total=False): + """The model will not be allowed to use tools.""" + + type: Required[Literal["none"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_choice_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_choice_param.py new file mode 100644 index 0000000000000000000000000000000000000000..ff6a51aa492a6adbbdd84b1d4ef3efba506a9fd0 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_choice_param.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .beta_tool_choice_any_param import BetaToolChoiceAnyParam +from .beta_tool_choice_auto_param import BetaToolChoiceAutoParam +from .beta_tool_choice_none_param import BetaToolChoiceNoneParam +from .beta_tool_choice_tool_param import BetaToolChoiceToolParam + +__all__ = ["BetaToolChoiceParam"] + +BetaToolChoiceParam: TypeAlias = Union[ + BetaToolChoiceAutoParam, BetaToolChoiceAnyParam, BetaToolChoiceToolParam, BetaToolChoiceNoneParam +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_choice_tool_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_choice_tool_param.py new file mode 100644 index 0000000000000000000000000000000000000000..f841958247affadabd850f36ef790322594eb51a --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_choice_tool_param.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaToolChoiceToolParam"] + + +class BetaToolChoiceToolParam(TypedDict, total=False): + """The model will use the specified tool with `tool_choice.name`.""" + + name: Required[str] + """The name of the tool to use.""" + + type: Required[Literal["tool"]] + + disable_parallel_tool_use: bool + """Whether to disable parallel tool use. + + Defaults to `false`. If set to `true`, the model will output exactly one tool + use. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_computer_use_20241022_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_computer_use_20241022_param.py new file mode 100644 index 0000000000000000000000000000000000000000..177e8dd740c63e8d29c111bf0d48481e1b9a769d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_computer_use_20241022_param.py @@ -0,0 +1,45 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Iterable, Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaToolComputerUse20241022Param"] + + +class BetaToolComputerUse20241022Param(TypedDict, total=False): + display_height_px: Required[int] + """The height of the display in pixels.""" + + display_width_px: Required[int] + """The width of the display in pixels.""" + + name: Required[Literal["computer"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["computer_20241022"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + display_number: Optional[int] + """The X11 display number (e.g. 0, 1) for the display.""" + + input_examples: Iterable[Dict[str, object]] + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_computer_use_20250124_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_computer_use_20250124_param.py new file mode 100644 index 0000000000000000000000000000000000000000..3622b5b09f9aa7b82be35d977eaef828774715fa --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_computer_use_20250124_param.py @@ -0,0 +1,45 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Iterable, Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaToolComputerUse20250124Param"] + + +class BetaToolComputerUse20250124Param(TypedDict, total=False): + display_height_px: Required[int] + """The height of the display in pixels.""" + + display_width_px: Required[int] + """The width of the display in pixels.""" + + name: Required[Literal["computer"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["computer_20250124"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + display_number: Optional[int] + """The X11 display number (e.g. 0, 1) for the display.""" + + input_examples: Iterable[Dict[str, object]] + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_computer_use_20251124_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_computer_use_20251124_param.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c8eb2937b9acb336f718c8e49e4e02687e15c0 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_computer_use_20251124_param.py @@ -0,0 +1,48 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Iterable, Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaToolComputerUse20251124Param"] + + +class BetaToolComputerUse20251124Param(TypedDict, total=False): + display_height_px: Required[int] + """The height of the display in pixels.""" + + display_width_px: Required[int] + """The width of the display in pixels.""" + + name: Required[Literal["computer"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["computer_20251124"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + display_number: Optional[int] + """The X11 display number (e.g. 0, 1) for the display.""" + + enable_zoom: bool + """Whether to enable an action to take a zoomed-in screenshot of the screen.""" + + input_examples: Iterable[Dict[str, object]] + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_param.py new file mode 100644 index 0000000000000000000000000000000000000000..e64c26d2e98aa863352372b6bb14348b29f36b40 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_param.py @@ -0,0 +1,79 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Union, Iterable, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from ..._types import SequenceNotStr +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaToolParam", "InputSchema"] + + +class InputSchemaTyped(TypedDict, total=False): + """[JSON schema](https://json-schema.org/draft/2020-12) for this tool's input. + + This defines the shape of the `input` that your tool accepts and that the model will produce. + """ + + type: Required[Literal["object"]] + + properties: Optional[Dict[str, object]] + + required: Optional[SequenceNotStr[str]] + + +InputSchema: TypeAlias = Union[InputSchemaTyped, Dict[str, object]] + + +class BetaToolParam(TypedDict, total=False): + input_schema: Required[InputSchema] + """[JSON schema](https://json-schema.org/draft/2020-12) for this tool's input. + + This defines the shape of the `input` that your tool accepts and that the model + will produce. + """ + + name: Required[str] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + description: str + """Description of what this tool does. + + Tool descriptions should be as detailed as possible. The more information that + the model has about what the tool is and how to use it, the better it will + perform. You can use natural language descriptions to reinforce important + aspects of the tool input JSON schema. + """ + + eager_input_streaming: Optional[bool] + """Enable eager input streaming for this tool. + + When true, tool input parameters will be streamed incrementally as they are + generated, and types will be inferred on-the-fly rather than buffering the full + JSON output. When false, streaming is disabled for this tool even if the + fine-grained-tool-streaming beta is active. When null (default), uses the + default behavior based on beta headers. + """ + + input_examples: Iterable[Dict[str, object]] + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" + + type: Optional[Literal["custom"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_reference_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_reference_block.py new file mode 100644 index 0000000000000000000000000000000000000000..7ae70cd9024ebf2d2b08d6b23c2d81c6c630f6dc --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_reference_block.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaToolReferenceBlock"] + + +class BetaToolReferenceBlock(BaseModel): + tool_name: str + + type: Literal["tool_reference"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_reference_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_reference_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..3f6be14ba190f54569c5b7841ec9421215e4a014 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_reference_block_param.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaToolReferenceBlockParam"] + + +class BetaToolReferenceBlockParam(TypedDict, total=False): + """Tool reference block that can be included in tool_result content.""" + + tool_name: Required[str] + + type: Required[Literal["tool_reference"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..6b213c845920ae58f324187f10d73bb31f077e2a --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_result_block_param.py @@ -0,0 +1,36 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .beta_text_block_param import BetaTextBlockParam +from .beta_image_block_param import BetaImageBlockParam +from .beta_search_result_block_param import BetaSearchResultBlockParam +from .beta_tool_reference_block_param import BetaToolReferenceBlockParam +from .beta_request_document_block_param import BetaRequestDocumentBlockParam +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaToolResultBlockParam", "Content"] + +Content: TypeAlias = Union[ + BetaTextBlockParam, + BetaImageBlockParam, + BetaSearchResultBlockParam, + BetaRequestDocumentBlockParam, + BetaToolReferenceBlockParam, +] + + +class BetaToolResultBlockParam(TypedDict, total=False): + tool_use_id: Required[str] + + type: Required[Literal["tool_result"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + content: Union[str, Iterable[Content]] + + is_error: bool diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_bm25_20251119_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_bm25_20251119_param.py new file mode 100644 index 0000000000000000000000000000000000000000..41e973a2c3666ca03fdad5f4f36afe3579f37133 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_bm25_20251119_param.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaToolSearchToolBm25_20251119Param"] + + +class BetaToolSearchToolBm25_20251119Param(TypedDict, total=False): + name: Required[Literal["tool_search_tool_bm25"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["tool_search_tool_bm25_20251119", "tool_search_tool_bm25"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_regex_20251119_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_regex_20251119_param.py new file mode 100644 index 0000000000000000000000000000000000000000..fef4bb439876bc9eeaed65528293e1f5763e6a32 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_regex_20251119_param.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaToolSearchToolRegex20251119Param"] + + +class BetaToolSearchToolRegex20251119Param(TypedDict, total=False): + name: Required[Literal["tool_search_tool_regex"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["tool_search_tool_regex_20251119", "tool_search_tool_regex"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_result_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_result_block.py new file mode 100644 index 0000000000000000000000000000000000000000..9b957163feea0bc00071d1ef7d63c821292d3eb8 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_result_block.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Literal, TypeAlias + +from ..._models import BaseModel +from .beta_tool_search_tool_result_error import BetaToolSearchToolResultError +from .beta_tool_search_tool_search_result_block import BetaToolSearchToolSearchResultBlock + +__all__ = ["BetaToolSearchToolResultBlock", "Content"] + +Content: TypeAlias = Union[BetaToolSearchToolResultError, BetaToolSearchToolSearchResultBlock] + + +class BetaToolSearchToolResultBlock(BaseModel): + content: Content + + tool_use_id: str + + type: Literal["tool_search_tool_result"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..2a74a254ba869d5d06334a627afe66840339700e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_result_block_param.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam +from .beta_tool_search_tool_result_error_param import BetaToolSearchToolResultErrorParam +from .beta_tool_search_tool_search_result_block_param import BetaToolSearchToolSearchResultBlockParam + +__all__ = ["BetaToolSearchToolResultBlockParam", "Content"] + +Content: TypeAlias = Union[BetaToolSearchToolResultErrorParam, BetaToolSearchToolSearchResultBlockParam] + + +class BetaToolSearchToolResultBlockParam(TypedDict, total=False): + content: Required[Content] + + tool_use_id: Required[str] + + type: Required[Literal["tool_search_tool_result"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_result_error.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_result_error.py new file mode 100644 index 0000000000000000000000000000000000000000..c8d9367360c8ac8162f91c24f9494aad2f894597 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_result_error.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaToolSearchToolResultError"] + + +class BetaToolSearchToolResultError(BaseModel): + error_code: Literal["invalid_tool_input", "unavailable", "too_many_requests", "execution_time_exceeded"] + + error_message: Optional[str] = None + + type: Literal["tool_search_tool_result_error"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_result_error_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_result_error_param.py new file mode 100644 index 0000000000000000000000000000000000000000..6a4a2a88ae83e71549069f2cba614093600390e1 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_result_error_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaToolSearchToolResultErrorParam"] + + +class BetaToolSearchToolResultErrorParam(TypedDict, total=False): + error_code: Required[Literal["invalid_tool_input", "unavailable", "too_many_requests", "execution_time_exceeded"]] + + type: Required[Literal["tool_search_tool_result_error"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_search_result_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_search_result_block.py new file mode 100644 index 0000000000000000000000000000000000000000..9b6265e113c201f38b20eec6453a1d69ae7c6519 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_search_result_block.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_tool_reference_block import BetaToolReferenceBlock + +__all__ = ["BetaToolSearchToolSearchResultBlock"] + + +class BetaToolSearchToolSearchResultBlock(BaseModel): + tool_references: List[BetaToolReferenceBlock] + + type: Literal["tool_search_tool_search_result"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_search_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_search_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..3185f4052ef6aa1331069b44b4de8ae26c1b7a03 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_search_tool_search_result_block_param.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Literal, Required, TypedDict + +from .beta_tool_reference_block_param import BetaToolReferenceBlockParam + +__all__ = ["BetaToolSearchToolSearchResultBlockParam"] + + +class BetaToolSearchToolSearchResultBlockParam(TypedDict, total=False): + tool_references: Required[Iterable[BetaToolReferenceBlockParam]] + + type: Required[Literal["tool_search_tool_search_result"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_text_editor_20241022_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_text_editor_20241022_param.py new file mode 100644 index 0000000000000000000000000000000000000000..577f0af5f8d1f8d2604d0e6c721c2f7f3c8ecaf5 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_text_editor_20241022_param.py @@ -0,0 +1,36 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Iterable, Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaToolTextEditor20241022Param"] + + +class BetaToolTextEditor20241022Param(TypedDict, total=False): + name: Required[Literal["str_replace_editor"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["text_editor_20241022"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + input_examples: Iterable[Dict[str, object]] + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_text_editor_20250124_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_text_editor_20250124_param.py new file mode 100644 index 0000000000000000000000000000000000000000..fd6462ad7d19d586c2a2eb733f232fb6c2febc47 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_text_editor_20250124_param.py @@ -0,0 +1,36 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Iterable, Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaToolTextEditor20250124Param"] + + +class BetaToolTextEditor20250124Param(TypedDict, total=False): + name: Required[Literal["str_replace_editor"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["text_editor_20250124"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + input_examples: Iterable[Dict[str, object]] + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_text_editor_20250728_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_text_editor_20250728_param.py new file mode 100644 index 0000000000000000000000000000000000000000..3172e0bba129178ba2493a1109f7a2502c59b099 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_text_editor_20250728_param.py @@ -0,0 +1,42 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Iterable, Optional +from typing_extensions import Literal, Required, TypedDict + +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaToolTextEditor20250728Param"] + + +class BetaToolTextEditor20250728Param(TypedDict, total=False): + name: Required[Literal["str_replace_based_edit_tool"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["text_editor_20250728"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + input_examples: Iterable[Dict[str, object]] + + max_characters: Optional[int] + """Maximum number of characters to display when viewing a file. + + If not specified, defaults to displaying the full file. + """ + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_union_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_union_param.py new file mode 100644 index 0000000000000000000000000000000000000000..1899c7da8eefe976b6f1124e86e0cc2148aed549 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_union_param.py @@ -0,0 +1,58 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .beta_tool_param import BetaToolParam +from .beta_mcp_toolset_param import BetaMCPToolsetParam +from .beta_tool_bash_20241022_param import BetaToolBash20241022Param +from .beta_tool_bash_20250124_param import BetaToolBash20250124Param +from .beta_memory_tool_20250818_param import BetaMemoryTool20250818Param +from .beta_advisor_tool_20260301_param import BetaAdvisorTool20260301Param +from .beta_web_fetch_tool_20250910_param import BetaWebFetchTool20250910Param +from .beta_web_fetch_tool_20260209_param import BetaWebFetchTool20260209Param +from .beta_web_fetch_tool_20260309_param import BetaWebFetchTool20260309Param +from .beta_web_search_tool_20250305_param import BetaWebSearchTool20250305Param +from .beta_web_search_tool_20260209_param import BetaWebSearchTool20260209Param +from .beta_tool_text_editor_20241022_param import BetaToolTextEditor20241022Param +from .beta_tool_text_editor_20250124_param import BetaToolTextEditor20250124Param +from .beta_tool_text_editor_20250429_param import BetaToolTextEditor20250429Param +from .beta_tool_text_editor_20250728_param import BetaToolTextEditor20250728Param +from .beta_tool_computer_use_20241022_param import BetaToolComputerUse20241022Param +from .beta_tool_computer_use_20250124_param import BetaToolComputerUse20250124Param +from .beta_tool_computer_use_20251124_param import BetaToolComputerUse20251124Param +from .beta_code_execution_tool_20250522_param import BetaCodeExecutionTool20250522Param +from .beta_code_execution_tool_20250825_param import BetaCodeExecutionTool20250825Param +from .beta_code_execution_tool_20260120_param import BetaCodeExecutionTool20260120Param +from .beta_tool_search_tool_bm25_20251119_param import BetaToolSearchToolBm25_20251119Param +from .beta_tool_search_tool_regex_20251119_param import BetaToolSearchToolRegex20251119Param + +__all__ = ["BetaToolUnionParam"] + +BetaToolUnionParam: TypeAlias = Union[ + BetaToolParam, + BetaToolBash20241022Param, + BetaToolBash20250124Param, + BetaCodeExecutionTool20250522Param, + BetaCodeExecutionTool20250825Param, + BetaCodeExecutionTool20260120Param, + BetaToolComputerUse20241022Param, + BetaMemoryTool20250818Param, + BetaToolComputerUse20250124Param, + BetaToolTextEditor20241022Param, + BetaToolComputerUse20251124Param, + BetaToolTextEditor20250124Param, + BetaToolTextEditor20250429Param, + BetaToolTextEditor20250728Param, + BetaWebSearchTool20250305Param, + BetaWebFetchTool20250910Param, + BetaWebSearchTool20260209Param, + BetaWebFetchTool20260209Param, + BetaWebFetchTool20260309Param, + BetaAdvisorTool20260301Param, + BetaToolSearchToolBm25_20251119Param, + BetaToolSearchToolRegex20251119Param, + BetaMCPToolsetParam, +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_use_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_use_block.py new file mode 100644 index 0000000000000000000000000000000000000000..b53d8f4f805ff8c2e883244d4985c35fc6890002 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_use_block.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .beta_direct_caller import BetaDirectCaller +from .beta_server_tool_caller import BetaServerToolCaller +from .beta_server_tool_caller_20260120 import BetaServerToolCaller20260120 + +__all__ = ["BetaToolUseBlock", "Caller"] + +Caller: TypeAlias = Annotated[ + Union[BetaDirectCaller, BetaServerToolCaller, BetaServerToolCaller20260120], PropertyInfo(discriminator="type") +] + + +class BetaToolUseBlock(BaseModel): + id: str + + input: Dict[str, object] + + name: str + + type: Literal["tool_use"] + + caller: Optional[Caller] = None + """Tool invocation directly from the model.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_use_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_use_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..c28e25e0768f0b4a47a80590bf44a7301ebcb91b --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_use_block_param.py @@ -0,0 +1,31 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Union, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .beta_direct_caller_param import BetaDirectCallerParam +from .beta_server_tool_caller_param import BetaServerToolCallerParam +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam +from .beta_server_tool_caller_20260120_param import BetaServerToolCaller20260120Param + +__all__ = ["BetaToolUseBlockParam", "Caller"] + +Caller: TypeAlias = Union[BetaDirectCallerParam, BetaServerToolCallerParam, BetaServerToolCaller20260120Param] + + +class BetaToolUseBlockParam(TypedDict, total=False): + id: Required[str] + + input: Required[Dict[str, object]] + + name: Required[str] + + type: Required[Literal["tool_use"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + caller: Caller + """Tool invocation directly from the model.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_uses_keep_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_uses_keep_param.py new file mode 100644 index 0000000000000000000000000000000000000000..3c67ea67f6b9be0fbd97a0b689b0e64705034118 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_uses_keep_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaToolUsesKeepParam"] + + +class BetaToolUsesKeepParam(TypedDict, total=False): + type: Required[Literal["tool_uses"]] + + value: Required[int] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_uses_trigger_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_uses_trigger_param.py new file mode 100644 index 0000000000000000000000000000000000000000..15eafd4560554db1aa3b6a62c11c1ed2ef4dd76f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_tool_uses_trigger_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaToolUsesTriggerParam"] + + +class BetaToolUsesTriggerParam(TypedDict, total=False): + type: Required[Literal["tool_uses"]] + + value: Required[int] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_unrestricted_network.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_unrestricted_network.py new file mode 100644 index 0000000000000000000000000000000000000000..2c2fabee3ad77d5e71be528f33ba272328f85aa2 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_unrestricted_network.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaUnrestrictedNetwork"] + + +class BetaUnrestrictedNetwork(BaseModel): + """Unrestricted network access.""" + + type: Literal["unrestricted"] + """Network policy type""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_unrestricted_network_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_unrestricted_network_param.py new file mode 100644 index 0000000000000000000000000000000000000000..20cd710935b9153b39470e739afab51a23f80771 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_unrestricted_network_param.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaUnrestrictedNetworkParam"] + + +class BetaUnrestrictedNetworkParam(TypedDict, total=False): + """Unrestricted network access.""" + + type: Required[Literal["unrestricted"]] + """Network policy type""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_url_image_source_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_url_image_source_param.py new file mode 100644 index 0000000000000000000000000000000000000000..a094a4332508f0d16d19d68af165b0d836c90cf8 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_url_image_source_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaURLImageSourceParam"] + + +class BetaURLImageSourceParam(TypedDict, total=False): + type: Required[Literal["url"]] + + url: Required[str] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_url_pdf_source_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_url_pdf_source_param.py new file mode 100644 index 0000000000000000000000000000000000000000..acc1eabf3afed918f9824838ffc0333fbe8658db --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_url_pdf_source_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaURLPDFSourceParam"] + + +class BetaURLPDFSourceParam(TypedDict, total=False): + type: Required[Literal["url"]] + + url: Required[str] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_user_profile.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_user_profile.py new file mode 100644 index 0000000000000000000000000000000000000000..24c26d5acb0d6ad510ecd3d4e0275ebbdf10d702 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_user_profile.py @@ -0,0 +1,52 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional +from datetime import datetime +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_user_profile_trust_grant import BetaUserProfileTrustGrant + +__all__ = ["BetaUserProfile"] + + +class BetaUserProfile(BaseModel): + id: str + """Unique identifier for this user profile, prefixed `uprof_`.""" + + created_at: datetime + """A timestamp in RFC 3339 format""" + + metadata: Dict[str, str] + """Arbitrary key-value metadata. + + Maximum 16 pairs, keys up to 64 chars, values up to 512 chars. + """ + + relationship: Literal["external", "resold", "internal"] + """ + How the entity behind a user profile relates to the platform that owns the API + key. `external`: an individual end-user of the platform. `resold`: a company the + platform resells Claude access to. `internal`: the platform's own usage. + """ + + trust_grants: Dict[str, BetaUserProfileTrustGrant] + """Trust grants for this profile, keyed by grant name. + + Key omitted when no grant is active or in flight. + """ + + type: Literal["user_profile"] + """Object type. Always `user_profile`.""" + + updated_at: datetime + """A timestamp in RFC 3339 format""" + + external_id: Optional[str] = None + """Platform's own identifier for this user. Not enforced unique.""" + + name: Optional[str] = None + """Display name of the entity this profile represents. + + For `resold` this is the resold-to company's name. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_user_profile_enrollment_url.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_user_profile_enrollment_url.py new file mode 100644 index 0000000000000000000000000000000000000000..41fd555a9b1ac66142bbfe70e573300c12c66ad6 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_user_profile_enrollment_url.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from datetime import datetime +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaUserProfileEnrollmentURL"] + + +class BetaUserProfileEnrollmentURL(BaseModel): + expires_at: datetime + """A timestamp in RFC 3339 format""" + + type: Literal["enrollment_url"] + """Object type. Always `enrollment_url`.""" + + url: str + """Enrollment URL to send to the end user. Valid until `expires_at`.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_block.py new file mode 100644 index 0000000000000000000000000000000000000000..223e494f0ca8e7481f0e217eaa06e799daf6218d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_block.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_document_block import BetaDocumentBlock + +__all__ = ["BetaWebFetchBlock"] + + +class BetaWebFetchBlock(BaseModel): + content: BetaDocumentBlock + + retrieved_at: Optional[str] = None + """ISO 8601 timestamp when the content was retrieved""" + + type: Literal["web_fetch_result"] + + url: str + """Fetched content URL""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_20250910_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_20250910_param.py new file mode 100644 index 0000000000000000000000000000000000000000..d323c05aca23cbf1acfd83766ad2c31bd371df76 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_20250910_param.py @@ -0,0 +1,57 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal, Required, TypedDict + +from ..._types import SequenceNotStr +from .beta_citations_config_param import BetaCitationsConfigParam +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaWebFetchTool20250910Param"] + + +class BetaWebFetchTool20250910Param(TypedDict, total=False): + name: Required[Literal["web_fetch"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["web_fetch_20250910"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + allowed_domains: Optional[SequenceNotStr[str]] + """List of domains to allow fetching from""" + + blocked_domains: Optional[SequenceNotStr[str]] + """List of domains to block fetching from""" + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + citations: Optional[BetaCitationsConfigParam] + """Citations configuration for fetched documents. + + Citations are disabled by default. + """ + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + max_content_tokens: Optional[int] + """Maximum number of tokens used by including web page text content in the context. + + The limit is approximate and does not apply to binary content such as PDFs. + """ + + max_uses: Optional[int] + """Maximum number of times the tool can be used in the API request.""" + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_20260209_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_20260209_param.py new file mode 100644 index 0000000000000000000000000000000000000000..e1b9f045238bba13de216b78c816d9ad5825577b --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_20260209_param.py @@ -0,0 +1,57 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal, Required, TypedDict + +from ..._types import SequenceNotStr +from .beta_citations_config_param import BetaCitationsConfigParam +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaWebFetchTool20260209Param"] + + +class BetaWebFetchTool20260209Param(TypedDict, total=False): + name: Required[Literal["web_fetch"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["web_fetch_20260209"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + allowed_domains: Optional[SequenceNotStr[str]] + """List of domains to allow fetching from""" + + blocked_domains: Optional[SequenceNotStr[str]] + """List of domains to block fetching from""" + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + citations: Optional[BetaCitationsConfigParam] + """Citations configuration for fetched documents. + + Citations are disabled by default. + """ + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + max_content_tokens: Optional[int] + """Maximum number of tokens used by including web page text content in the context. + + The limit is approximate and does not apply to binary content such as PDFs. + """ + + max_uses: Optional[int] + """Maximum number of times the tool can be used in the API request.""" + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_20260309_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_20260309_param.py new file mode 100644 index 0000000000000000000000000000000000000000..10db1e93ef586448baddaf9b0785b5eac78d1200 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_20260309_param.py @@ -0,0 +1,67 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal, Required, TypedDict + +from ..._types import SequenceNotStr +from .beta_citations_config_param import BetaCitationsConfigParam +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaWebFetchTool20260309Param"] + + +class BetaWebFetchTool20260309Param(TypedDict, total=False): + """Web fetch tool with use_cache parameter for bypassing cached content.""" + + name: Required[Literal["web_fetch"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["web_fetch_20260309"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + allowed_domains: Optional[SequenceNotStr[str]] + """List of domains to allow fetching from""" + + blocked_domains: Optional[SequenceNotStr[str]] + """List of domains to block fetching from""" + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + citations: Optional[BetaCitationsConfigParam] + """Citations configuration for fetched documents. + + Citations are disabled by default. + """ + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + max_content_tokens: Optional[int] + """Maximum number of tokens used by including web page text content in the context. + + The limit is approximate and does not apply to binary content such as PDFs. + """ + + max_uses: Optional[int] + """Maximum number of times the tool can be used in the API request.""" + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" + + use_cache: bool + """Whether to use cached content. + + Set to false to bypass the cache and fetch fresh content. Only set to false when + the user explicitly requests fresh content or when fetching rapidly-changing + sources. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_result_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_result_block.py new file mode 100644 index 0000000000000000000000000000000000000000..f0bc96be687a50aecd24540c6ab0f9068167eba1 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_result_block.py @@ -0,0 +1,31 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .beta_direct_caller import BetaDirectCaller +from .beta_web_fetch_block import BetaWebFetchBlock +from .beta_server_tool_caller import BetaServerToolCaller +from .beta_server_tool_caller_20260120 import BetaServerToolCaller20260120 +from .beta_web_fetch_tool_result_error_block import BetaWebFetchToolResultErrorBlock + +__all__ = ["BetaWebFetchToolResultBlock", "Content", "Caller"] + +Content: TypeAlias = Union[BetaWebFetchToolResultErrorBlock, BetaWebFetchBlock] + +Caller: TypeAlias = Annotated[ + Union[BetaDirectCaller, BetaServerToolCaller, BetaServerToolCaller20260120], PropertyInfo(discriminator="type") +] + + +class BetaWebFetchToolResultBlock(BaseModel): + content: Content + + tool_use_id: str + + type: Literal["web_fetch_tool_result"] + + caller: Optional[Caller] = None + """Tool invocation directly from the model.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..ca3c2f3f0b04b79c0c32bfd94d6ea338c7e9fb94 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_result_block_param.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .beta_direct_caller_param import BetaDirectCallerParam +from .beta_web_fetch_block_param import BetaWebFetchBlockParam +from .beta_server_tool_caller_param import BetaServerToolCallerParam +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam +from .beta_server_tool_caller_20260120_param import BetaServerToolCaller20260120Param +from .beta_web_fetch_tool_result_error_block_param import BetaWebFetchToolResultErrorBlockParam + +__all__ = ["BetaWebFetchToolResultBlockParam", "Content", "Caller"] + +Content: TypeAlias = Union[BetaWebFetchToolResultErrorBlockParam, BetaWebFetchBlockParam] + +Caller: TypeAlias = Union[BetaDirectCallerParam, BetaServerToolCallerParam, BetaServerToolCaller20260120Param] + + +class BetaWebFetchToolResultBlockParam(TypedDict, total=False): + content: Required[Content] + + tool_use_id: Required[str] + + type: Required[Literal["web_fetch_tool_result"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + caller: Caller + """Tool invocation directly from the model.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_result_error_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_result_error_block.py new file mode 100644 index 0000000000000000000000000000000000000000..d44555a815f1b79ab3ca3b87ecfd6502ba4e5032 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_result_error_block.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_web_fetch_tool_result_error_code import BetaWebFetchToolResultErrorCode + +__all__ = ["BetaWebFetchToolResultErrorBlock"] + + +class BetaWebFetchToolResultErrorBlock(BaseModel): + error_code: BetaWebFetchToolResultErrorCode + + type: Literal["web_fetch_tool_result_error"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_result_error_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_result_error_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..12f8cf8a162dac462dccc652f36ddd3cbd5d4c6c --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_result_error_block_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +from .beta_web_fetch_tool_result_error_code import BetaWebFetchToolResultErrorCode + +__all__ = ["BetaWebFetchToolResultErrorBlockParam"] + + +class BetaWebFetchToolResultErrorBlockParam(TypedDict, total=False): + error_code: Required[BetaWebFetchToolResultErrorCode] + + type: Required[Literal["web_fetch_tool_result_error"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_result_error_code.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_result_error_code.py new file mode 100644 index 0000000000000000000000000000000000000000..7f526093e3f40aa658e3acc7783e07b30bf51376 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_fetch_tool_result_error_code.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["BetaWebFetchToolResultErrorCode"] + +BetaWebFetchToolResultErrorCode: TypeAlias = Literal[ + "invalid_tool_input", + "url_too_long", + "url_not_allowed", + "url_not_accessible", + "unsupported_content_type", + "too_many_requests", + "max_uses_exceeded", + "unavailable", +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_result_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_result_block.py new file mode 100644 index 0000000000000000000000000000000000000000..35ed87cef2aac5a058f6feefd1b3c24f4d451950 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_result_block.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebSearchResultBlock"] + + +class BetaWebSearchResultBlock(BaseModel): + encrypted_content: str + + page_age: Optional[str] = None + + title: str + + type: Literal["web_search_result"] + + url: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..4a829ddbf4e59e9c734692046e51cd739c051323 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_result_block_param.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaWebSearchResultBlockParam"] + + +class BetaWebSearchResultBlockParam(TypedDict, total=False): + encrypted_content: Required[str] + + title: Required[str] + + type: Required[Literal["web_search_result"]] + + url: Required[str] + + page_age: Optional[str] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_tool_20250305_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_tool_20250305_param.py new file mode 100644 index 0000000000000000000000000000000000000000..5b5c2a44d3024ce524eefa8c603418a278f2e332 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_tool_20250305_param.py @@ -0,0 +1,57 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal, Required, TypedDict + +from ..._types import SequenceNotStr +from .beta_user_location_param import BetaUserLocationParam +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaWebSearchTool20250305Param"] + + +class BetaWebSearchTool20250305Param(TypedDict, total=False): + name: Required[Literal["web_search"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["web_search_20250305"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + allowed_domains: Optional[SequenceNotStr[str]] + """If provided, only these domains will be included in results. + + Cannot be used alongside `blocked_domains`. + """ + + blocked_domains: Optional[SequenceNotStr[str]] + """If provided, these domains will never appear in results. + + Cannot be used alongside `allowed_domains`. + """ + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + max_uses: Optional[int] + """Maximum number of times the tool can be used in the API request.""" + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" + + user_location: Optional[BetaUserLocationParam] + """Parameters for the user's location. + + Used to provide more relevant search results. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_tool_20260209_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_tool_20260209_param.py new file mode 100644 index 0000000000000000000000000000000000000000..9fd5caec4f60186bf7dc9d30ae3efb22f05171d0 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_tool_20260209_param.py @@ -0,0 +1,57 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal, Required, TypedDict + +from ..._types import SequenceNotStr +from .beta_user_location_param import BetaUserLocationParam +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam + +__all__ = ["BetaWebSearchTool20260209Param"] + + +class BetaWebSearchTool20260209Param(TypedDict, total=False): + name: Required[Literal["web_search"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["web_search_20260209"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + allowed_domains: Optional[SequenceNotStr[str]] + """If provided, only these domains will be included in results. + + Cannot be used alongside `blocked_domains`. + """ + + blocked_domains: Optional[SequenceNotStr[str]] + """If provided, these domains will never appear in results. + + Cannot be used alongside `allowed_domains`. + """ + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + max_uses: Optional[int] + """Maximum number of times the tool can be used in the API request.""" + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" + + user_location: Optional[BetaUserLocationParam] + """Parameters for the user's location. + + Used to provide more relevant search results. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_tool_request_error_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_tool_request_error_param.py new file mode 100644 index 0000000000000000000000000000000000000000..7583fb12fbebac98dadbcbaf9e372484db845829 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_tool_request_error_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +from .beta_web_search_tool_result_error_code import BetaWebSearchToolResultErrorCode + +__all__ = ["BetaWebSearchToolRequestErrorParam"] + + +class BetaWebSearchToolRequestErrorParam(TypedDict, total=False): + error_code: Required[BetaWebSearchToolResultErrorCode] + + type: Required[Literal["web_search_tool_result_error"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_tool_result_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_tool_result_block.py new file mode 100644 index 0000000000000000000000000000000000000000..dbbbce75f99909e85be6cac82966efa7ce92a526 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_tool_result_block.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .beta_direct_caller import BetaDirectCaller +from .beta_server_tool_caller import BetaServerToolCaller +from .beta_server_tool_caller_20260120 import BetaServerToolCaller20260120 +from .beta_web_search_tool_result_block_content import BetaWebSearchToolResultBlockContent + +__all__ = ["BetaWebSearchToolResultBlock", "Caller"] + +Caller: TypeAlias = Annotated[ + Union[BetaDirectCaller, BetaServerToolCaller, BetaServerToolCaller20260120], PropertyInfo(discriminator="type") +] + + +class BetaWebSearchToolResultBlock(BaseModel): + content: BetaWebSearchToolResultBlockContent + + tool_use_id: str + + type: Literal["web_search_tool_result"] + + caller: Optional[Caller] = None + """Tool invocation directly from the model.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_tool_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_tool_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..8be33a30719235a3751249cf0f466d6b8bccb861 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_tool_result_block_param.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .beta_direct_caller_param import BetaDirectCallerParam +from .beta_server_tool_caller_param import BetaServerToolCallerParam +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam +from .beta_server_tool_caller_20260120_param import BetaServerToolCaller20260120Param +from .beta_web_search_tool_result_block_param_content_param import BetaWebSearchToolResultBlockParamContentParam + +__all__ = ["BetaWebSearchToolResultBlockParam", "Caller"] + +Caller: TypeAlias = Union[BetaDirectCallerParam, BetaServerToolCallerParam, BetaServerToolCaller20260120Param] + + +class BetaWebSearchToolResultBlockParam(TypedDict, total=False): + content: Required[BetaWebSearchToolResultBlockParamContentParam] + + tool_use_id: Required[str] + + type: Required[Literal["web_search_tool_result"]] + + cache_control: Optional[BetaCacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + caller: Caller + """Tool invocation directly from the model.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_tool_result_block_param_content_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_tool_result_block_param_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..17edadb379fe648de94d48ae2ffc9130f51be864 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_tool_result_block_param_content_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import TypeAlias + +from .beta_web_search_result_block_param import BetaWebSearchResultBlockParam +from .beta_web_search_tool_request_error_param import BetaWebSearchToolRequestErrorParam + +__all__ = ["BetaWebSearchToolResultBlockParamContentParam"] + +BetaWebSearchToolResultBlockParamContentParam: TypeAlias = Union[ + Iterable[BetaWebSearchResultBlockParam], BetaWebSearchToolRequestErrorParam +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_tool_result_error_code.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_tool_result_error_code.py new file mode 100644 index 0000000000000000000000000000000000000000..388eb1025aba75ab38f8335360b4c2f54e37ec22 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_web_search_tool_result_error_code.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["BetaWebSearchToolResultErrorCode"] + +BetaWebSearchToolResultErrorCode: TypeAlias = Literal[ + "invalid_tool_input", "unavailable", "max_uses_exceeded", "too_many_requests", "query_too_long", "request_too_large" +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_event_data.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_event_data.py new file mode 100644 index 0000000000000000000000000000000000000000..db2cb99d0311ff456fc5169fbef68a0aad22f419 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_event_data.py @@ -0,0 +1,58 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from ..._utils import PropertyInfo +from .beta_webhook_session_idled_event_data import BetaWebhookSessionIdledEventData +from .beta_webhook_vault_created_event_data import BetaWebhookVaultCreatedEventData +from .beta_webhook_vault_deleted_event_data import BetaWebhookVaultDeletedEventData +from .beta_webhook_vault_archived_event_data import BetaWebhookVaultArchivedEventData +from .beta_webhook_session_created_event_data import BetaWebhookSessionCreatedEventData +from .beta_webhook_session_deleted_event_data import BetaWebhookSessionDeletedEventData +from .beta_webhook_session_pending_event_data import BetaWebhookSessionPendingEventData +from .beta_webhook_session_running_event_data import BetaWebhookSessionRunningEventData +from .beta_webhook_session_archived_event_data import BetaWebhookSessionArchivedEventData +from .beta_webhook_session_status_idled_event_data import BetaWebhookSessionStatusIdledEventData +from .beta_webhook_session_thread_idled_event_data import BetaWebhookSessionThreadIdledEventData +from .beta_webhook_session_thread_created_event_data import BetaWebhookSessionThreadCreatedEventData +from .beta_webhook_session_requires_action_event_data import BetaWebhookSessionRequiresActionEventData +from .beta_webhook_vault_credential_created_event_data import BetaWebhookVaultCredentialCreatedEventData +from .beta_webhook_vault_credential_deleted_event_data import BetaWebhookVaultCredentialDeletedEventData +from .beta_webhook_session_status_terminated_event_data import BetaWebhookSessionStatusTerminatedEventData +from .beta_webhook_session_thread_terminated_event_data import BetaWebhookSessionThreadTerminatedEventData +from .beta_webhook_vault_credential_archived_event_data import BetaWebhookVaultCredentialArchivedEventData +from .beta_webhook_session_status_rescheduled_event_data import BetaWebhookSessionStatusRescheduledEventData +from .beta_webhook_session_status_run_started_event_data import BetaWebhookSessionStatusRunStartedEventData +from .beta_webhook_vault_credential_refresh_failed_event_data import BetaWebhookVaultCredentialRefreshFailedEventData +from .beta_webhook_session_outcome_evaluation_ended_event_data import BetaWebhookSessionOutcomeEvaluationEndedEventData + +__all__ = ["BetaWebhookEventData"] + +BetaWebhookEventData: TypeAlias = Annotated[ + Union[ + BetaWebhookSessionCreatedEventData, + BetaWebhookSessionPendingEventData, + BetaWebhookSessionRunningEventData, + BetaWebhookSessionIdledEventData, + BetaWebhookSessionRequiresActionEventData, + BetaWebhookSessionArchivedEventData, + BetaWebhookSessionDeletedEventData, + BetaWebhookSessionStatusRescheduledEventData, + BetaWebhookSessionStatusRunStartedEventData, + BetaWebhookSessionStatusIdledEventData, + BetaWebhookSessionStatusTerminatedEventData, + BetaWebhookSessionThreadCreatedEventData, + BetaWebhookSessionThreadIdledEventData, + BetaWebhookSessionThreadTerminatedEventData, + BetaWebhookSessionOutcomeEvaluationEndedEventData, + BetaWebhookVaultCreatedEventData, + BetaWebhookVaultArchivedEventData, + BetaWebhookVaultDeletedEventData, + BetaWebhookVaultCredentialCreatedEventData, + BetaWebhookVaultCredentialArchivedEventData, + BetaWebhookVaultCredentialDeletedEventData, + BetaWebhookVaultCredentialRefreshFailedEventData, + ], + PropertyInfo(discriminator="type"), +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_archived_event_data.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_archived_event_data.py new file mode 100644 index 0000000000000000000000000000000000000000..02fca23a8f514487bd04b0ecc8911226fe8e0f5f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_archived_event_data.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebhookSessionArchivedEventData"] + + +class BetaWebhookSessionArchivedEventData(BaseModel): + id: str + """ID of the resource that triggered the event.""" + + organization_id: str + + type: Literal["session.archived"] + + workspace_id: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_created_event_data.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_created_event_data.py new file mode 100644 index 0000000000000000000000000000000000000000..969d637e5fe6a6877495eed1ead1cb9cb0b19604 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_created_event_data.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebhookSessionCreatedEventData"] + + +class BetaWebhookSessionCreatedEventData(BaseModel): + id: str + """ID of the resource that triggered the event.""" + + organization_id: str + + type: Literal["session.created"] + + workspace_id: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_deleted_event_data.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_deleted_event_data.py new file mode 100644 index 0000000000000000000000000000000000000000..16367dc1132b65c96801d98d97626adc89c94f10 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_deleted_event_data.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebhookSessionDeletedEventData"] + + +class BetaWebhookSessionDeletedEventData(BaseModel): + id: str + """ID of the resource that triggered the event.""" + + organization_id: str + + type: Literal["session.deleted"] + + workspace_id: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_idled_event_data.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_idled_event_data.py new file mode 100644 index 0000000000000000000000000000000000000000..8963054f17e8e85d7642ab088a13d843b1757e9a --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_idled_event_data.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebhookSessionIdledEventData"] + + +class BetaWebhookSessionIdledEventData(BaseModel): + id: str + """ID of the resource that triggered the event.""" + + organization_id: str + + type: Literal["session.idled"] + + workspace_id: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_outcome_evaluation_ended_event_data.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_outcome_evaluation_ended_event_data.py new file mode 100644 index 0000000000000000000000000000000000000000..329279230afc15780c730e19de8838aa7dbe9bbb --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_outcome_evaluation_ended_event_data.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebhookSessionOutcomeEvaluationEndedEventData"] + + +class BetaWebhookSessionOutcomeEvaluationEndedEventData(BaseModel): + id: str + """ID of the resource that triggered the event.""" + + organization_id: str + + type: Literal["session.outcome_evaluation_ended"] + + workspace_id: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_pending_event_data.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_pending_event_data.py new file mode 100644 index 0000000000000000000000000000000000000000..7b0bed507c9dfb7cd44d4a09ee42d11ad8a373cd --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_pending_event_data.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebhookSessionPendingEventData"] + + +class BetaWebhookSessionPendingEventData(BaseModel): + id: str + """ID of the resource that triggered the event.""" + + organization_id: str + + type: Literal["session.pending"] + + workspace_id: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_requires_action_event_data.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_requires_action_event_data.py new file mode 100644 index 0000000000000000000000000000000000000000..47ffc27450d7e5e9080ea144f2cf5d8a1f9bae32 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_requires_action_event_data.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebhookSessionRequiresActionEventData"] + + +class BetaWebhookSessionRequiresActionEventData(BaseModel): + id: str + """ID of the resource that triggered the event.""" + + organization_id: str + + type: Literal["session.requires_action"] + + workspace_id: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_running_event_data.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_running_event_data.py new file mode 100644 index 0000000000000000000000000000000000000000..e26bb53e05ebdcc285e3023df45a51056c99a6d3 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_running_event_data.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebhookSessionRunningEventData"] + + +class BetaWebhookSessionRunningEventData(BaseModel): + id: str + """ID of the resource that triggered the event.""" + + organization_id: str + + type: Literal["session.running"] + + workspace_id: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_status_rescheduled_event_data.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_status_rescheduled_event_data.py new file mode 100644 index 0000000000000000000000000000000000000000..26d8c8e2444d8f9a597bc03c835123c2317fea0c --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_status_rescheduled_event_data.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebhookSessionStatusRescheduledEventData"] + + +class BetaWebhookSessionStatusRescheduledEventData(BaseModel): + id: str + """ID of the resource that triggered the event.""" + + organization_id: str + + type: Literal["session.status_rescheduled"] + + workspace_id: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_status_run_started_event_data.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_status_run_started_event_data.py new file mode 100644 index 0000000000000000000000000000000000000000..0b90be142e754608ab7239c0dfc2bed31e3716b9 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_status_run_started_event_data.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebhookSessionStatusRunStartedEventData"] + + +class BetaWebhookSessionStatusRunStartedEventData(BaseModel): + id: str + """ID of the resource that triggered the event.""" + + organization_id: str + + type: Literal["session.status_run_started"] + + workspace_id: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_status_terminated_event_data.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_status_terminated_event_data.py new file mode 100644 index 0000000000000000000000000000000000000000..5365a3e47bf697ee8faad4d77e9144ce3e18e60f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_status_terminated_event_data.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebhookSessionStatusTerminatedEventData"] + + +class BetaWebhookSessionStatusTerminatedEventData(BaseModel): + id: str + """ID of the resource that triggered the event.""" + + organization_id: str + + type: Literal["session.status_terminated"] + + workspace_id: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_thread_created_event_data.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_thread_created_event_data.py new file mode 100644 index 0000000000000000000000000000000000000000..91569ed334f32a1470b632b8f01c95d751073427 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_thread_created_event_data.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebhookSessionThreadCreatedEventData"] + + +class BetaWebhookSessionThreadCreatedEventData(BaseModel): + id: str + """ID of the resource that triggered the event.""" + + organization_id: str + + type: Literal["session.thread_created"] + + workspace_id: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_thread_idled_event_data.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_thread_idled_event_data.py new file mode 100644 index 0000000000000000000000000000000000000000..b2145d805d17760137d7143618f09febe3aa6d8e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_thread_idled_event_data.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebhookSessionThreadIdledEventData"] + + +class BetaWebhookSessionThreadIdledEventData(BaseModel): + id: str + """ID of the resource that triggered the event.""" + + organization_id: str + + type: Literal["session.thread_idled"] + + workspace_id: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_thread_terminated_event_data.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_thread_terminated_event_data.py new file mode 100644 index 0000000000000000000000000000000000000000..6108045587fa8486c4273310328e63c8cc3f69c5 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_session_thread_terminated_event_data.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebhookSessionThreadTerminatedEventData"] + + +class BetaWebhookSessionThreadTerminatedEventData(BaseModel): + id: str + """ID of the resource that triggered the event.""" + + organization_id: str + + type: Literal["session.thread_terminated"] + + workspace_id: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_vault_created_event_data.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_vault_created_event_data.py new file mode 100644 index 0000000000000000000000000000000000000000..5e099008a085e031644a80feea513b985ad10fc0 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_vault_created_event_data.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebhookVaultCreatedEventData"] + + +class BetaWebhookVaultCreatedEventData(BaseModel): + id: str + """ID of the resource that triggered the event.""" + + organization_id: str + + type: Literal["vault.created"] + + workspace_id: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_vault_credential_archived_event_data.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_vault_credential_archived_event_data.py new file mode 100644 index 0000000000000000000000000000000000000000..447ff7591db493b1d27f619f22e6edd4813955ab --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_vault_credential_archived_event_data.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebhookVaultCredentialArchivedEventData"] + + +class BetaWebhookVaultCredentialArchivedEventData(BaseModel): + id: str + """ID of the resource that triggered the event.""" + + organization_id: str + + type: Literal["vault_credential.archived"] + + vault_id: str + """ID of the vault that owns this credential.""" + + workspace_id: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_vault_credential_created_event_data.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_vault_credential_created_event_data.py new file mode 100644 index 0000000000000000000000000000000000000000..99d422cc90c387572aefa48f0e26241ada0f6ec1 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_vault_credential_created_event_data.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebhookVaultCredentialCreatedEventData"] + + +class BetaWebhookVaultCredentialCreatedEventData(BaseModel): + id: str + """ID of the resource that triggered the event.""" + + organization_id: str + + type: Literal["vault_credential.created"] + + vault_id: str + """ID of the vault that owns this credential.""" + + workspace_id: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_vault_credential_deleted_event_data.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_vault_credential_deleted_event_data.py new file mode 100644 index 0000000000000000000000000000000000000000..df3f2147809cbf90c03f288904e9f78fd9f1f7a8 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_vault_credential_deleted_event_data.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebhookVaultCredentialDeletedEventData"] + + +class BetaWebhookVaultCredentialDeletedEventData(BaseModel): + id: str + """ID of the resource that triggered the event.""" + + organization_id: str + + type: Literal["vault_credential.deleted"] + + vault_id: str + """ID of the vault that owns this credential.""" + + workspace_id: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_vault_credential_refresh_failed_event_data.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_vault_credential_refresh_failed_event_data.py new file mode 100644 index 0000000000000000000000000000000000000000..4065b4d094c3b68fe24c548216af4d93713d26e6 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_vault_credential_refresh_failed_event_data.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebhookVaultCredentialRefreshFailedEventData"] + + +class BetaWebhookVaultCredentialRefreshFailedEventData(BaseModel): + id: str + """ID of the resource that triggered the event.""" + + organization_id: str + + type: Literal["vault_credential.refresh_failed"] + + vault_id: str + """ID of the vault that owns this credential.""" + + workspace_id: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_vault_deleted_event_data.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_vault_deleted_event_data.py new file mode 100644 index 0000000000000000000000000000000000000000..3a0f98f7904ca9b92bcfbc3a84f1e3ff6d2e542d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/beta_webhook_vault_deleted_event_data.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BetaWebhookVaultDeletedEventData"] + + +class BetaWebhookVaultDeletedEventData(BaseModel): + id: str + """ID of the resource that triggered the event.""" + + organization_id: str + + type: Literal["vault.deleted"] + + workspace_id: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/environment_create_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/environment_create_params.py new file mode 100644 index 0000000000000000000000000000000000000000..446aba0f6eec10df65a07dc5e292f9da8a55abf7 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/environment_create_params.py @@ -0,0 +1,32 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Optional +from typing_extensions import Required, Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..anthropic_beta_param import AnthropicBetaParam +from .beta_cloud_config_params import BetaCloudConfigParams + +__all__ = ["EnvironmentCreateParams"] + + +class EnvironmentCreateParams(TypedDict, total=False): + name: Required[str] + """Human-readable name for the environment""" + + config: Optional[BetaCloudConfigParams] + """Request params for `cloud` environment configuration. + + Fields default to null; on update, omitted fields preserve the existing value. + """ + + description: Optional[str] + """Optional description of the environment""" + + metadata: Dict[str, str] + """User-provided metadata key-value pairs""" + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/environment_list_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/environment_list_params.py new file mode 100644 index 0000000000000000000000000000000000000000..c077d3c62fadb262b9251433276b36c61497d046 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/environment_list_params.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..anthropic_beta_param import AnthropicBetaParam + +__all__ = ["EnvironmentListParams"] + + +class EnvironmentListParams(TypedDict, total=False): + include_archived: bool + """Include archived environments in the response""" + + limit: int + """Maximum number of environments to return""" + + page: Optional[str] + """Opaque cursor from previous response for pagination. + + Pass the `next_page` value from the previous response. + """ + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/environment_update_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/environment_update_params.py new file mode 100644 index 0000000000000000000000000000000000000000..1c212f535d48de1153b88e8edd21bfb2c798fe96 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/environment_update_params.py @@ -0,0 +1,35 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Optional +from typing_extensions import Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..anthropic_beta_param import AnthropicBetaParam +from .beta_cloud_config_params import BetaCloudConfigParams + +__all__ = ["EnvironmentUpdateParams"] + + +class EnvironmentUpdateParams(TypedDict, total=False): + config: Optional[BetaCloudConfigParams] + """Request params for `cloud` environment configuration. + + Fields default to null; on update, omitted fields preserve the existing value. + """ + + description: Optional[str] + """Updated description of the environment""" + + metadata: Dict[str, Optional[str]] + """User-provided metadata key-value pairs. + + Set a value to null or empty string to delete the key. + """ + + name: Optional[str] + """Updated name for the environment""" + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/file_list_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/file_list_params.py new file mode 100644 index 0000000000000000000000000000000000000000..f9fe4f8f8f3d046e0f8036c254a34849d13e22d7 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/file_list_params.py @@ -0,0 +1,40 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List +from typing_extensions import Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..anthropic_beta_param import AnthropicBetaParam + +__all__ = ["FileListParams"] + + +class FileListParams(TypedDict, total=False): + after_id: str + """ID of the object to use as a cursor for pagination. + + When provided, returns the page of results immediately after this object. + """ + + before_id: str + """ID of the object to use as a cursor for pagination. + + When provided, returns the page of results immediately before this object. + """ + + limit: int + """Number of items to return per page. + + Defaults to `20`. Ranges from `1` to `1000`. + """ + + scope_id: str + """Filter by scope ID. + + Only returns files associated with the specified scope (e.g., a session ID). + """ + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/file_metadata.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/file_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..9faf8243875d4de437c52f1a6bacc762f6de82f5 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/file_metadata.py @@ -0,0 +1,45 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from datetime import datetime +from typing_extensions import Literal + +from ..._models import BaseModel +from .beta_file_scope import BetaFileScope + +__all__ = ["FileMetadata"] + + +class FileMetadata(BaseModel): + id: str + """Unique object identifier. + + The format and length of IDs may change over time. + """ + + created_at: datetime + """RFC 3339 datetime string representing when the file was created.""" + + filename: str + """Original filename of the uploaded file.""" + + mime_type: str + """MIME type of the file.""" + + size_bytes: int + """Size of the file in bytes.""" + + type: Literal["file"] + """Object type. + + For files, this is always `"file"`. + """ + + downloadable: Optional[bool] = None + """Whether the file can be downloaded.""" + + scope: Optional[BetaFileScope] = None + """ + The scope of this file, indicating the context in which it was created (e.g., a + session). + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/file_upload_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/file_upload_params.py new file mode 100644 index 0000000000000000000000000000000000000000..a26c00bf3e78b650653927ede05427327bd92263 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/file_upload_params.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List +from typing_extensions import Required, Annotated, TypedDict + +from ..._types import FileTypes +from ..._utils import PropertyInfo +from ..anthropic_beta_param import AnthropicBetaParam + +__all__ = ["FileUploadParams"] + + +class FileUploadParams(TypedDict, total=False): + file: Required[FileTypes] + """The file to upload""" + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_store_list_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_store_list_params.py new file mode 100644 index 0000000000000000000000000000000000000000..ef7a4df53399f536f93c689db55e6ac365532397 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_store_list_params.py @@ -0,0 +1,48 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union +from datetime import datetime +from typing_extensions import Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..anthropic_beta_param import AnthropicBetaParam + +__all__ = ["MemoryStoreListParams"] + + +class MemoryStoreListParams(TypedDict, total=False): + created_at_gte: Annotated[Union[str, datetime], PropertyInfo(alias="created_at[gte]", format="iso8601")] + """Return only stores whose `created_at` is at or after this time (inclusive). + + Sent on the wire as `created_at[gte]`. + """ + + created_at_lte: Annotated[Union[str, datetime], PropertyInfo(alias="created_at[lte]", format="iso8601")] + """Return only stores whose `created_at` is at or before this time (inclusive). + + Sent on the wire as `created_at[lte]`. + """ + + include_archived: bool + """When `true`, archived stores are included in the results. + + Defaults to `false` (archived stores are excluded). + """ + + limit: int + """Maximum number of stores to return per page. + + Must be between 1 and 100. Defaults to 20 when omitted. + """ + + page: str + """Opaque pagination cursor (a `page_...` value). + + Pass the `next_page` value from a previous response to fetch the next page; omit + for the first page. + """ + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_store_update_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_store_update_params.py new file mode 100644 index 0000000000000000000000000000000000000000..56180484f4e1edc0ab7c073f19c858a9cbbc86d9 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_store_update_params.py @@ -0,0 +1,37 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Optional +from typing_extensions import Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..anthropic_beta_param import AnthropicBetaParam + +__all__ = ["MemoryStoreUpdateParams"] + + +class MemoryStoreUpdateParams(TypedDict, total=False): + description: Optional[str] + """New description for the store, up to 1024 characters. + + Pass an empty string to clear it. + """ + + metadata: Optional[Dict[str, Optional[str]]] + """Metadata patch. + + Set a key to a string to upsert it, or to null to delete it. Omit the field to + preserve. The stored bag is limited to 16 keys (up to 64 chars each) with values + up to 512 chars. + """ + + name: Optional[str] + """New human-readable name for the store. + + 1–255 characters; no control characters. Renaming changes the slug used for the + store's `mount_path` in sessions created after the update. + """ + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/__init__.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..217d6d70531d0a8ad9439f5d1e001261a0754250 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/__init__.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_actor.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_actor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5af436a0d25f2352e1d3b78c953a5e1a72642cb Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_actor.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_api_actor.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_api_actor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..790885d0b76f7e99dd768150c57ff920107e64b2 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_api_actor.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_deleted_memory.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_deleted_memory.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a7613def7f21d155f78c0099cada987a86ef879 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_deleted_memory.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_memory.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_memory.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1fa1df2b7a9cb4a8c78f5b2231abe3b1f9e88cc1 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_memory.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_memory_list_item.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_memory_list_item.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee2708c6511b62af8d9bb663176b964bedf1a23d Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_memory_list_item.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_memory_prefix.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_memory_prefix.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22dd8af71354cf7b252454208e9fb44698642728 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_memory_prefix.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_memory_version.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_memory_version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..230e3ac7952561b3975fce99dde9dd2a4f303c35 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_memory_version.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_memory_version_operation.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_memory_version_operation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82cdb60b97e19af5f76cfe7ffd72177ea78c7ea7 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_memory_version_operation.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_memory_view.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_memory_view.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..829db145b5c20de26075b00a10c0255e9748de0e Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_memory_view.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_precondition_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_precondition_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c10fe6d1ad14670e45c99330e9030eb98359ae99 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_precondition_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_session_actor.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_session_actor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09f5ebe5d094b268ebdb1975de1ccfad91445dad Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_session_actor.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_user_actor.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_user_actor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e755602827419017b1d6225e6c2e41705051382a Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/beta_managed_agents_user_actor.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/memory_create_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/memory_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51341c9201987e96f7394236b818c702a9666940 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/memory_create_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/memory_delete_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/memory_delete_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b8bc0a0e5a225f8ded0f2f3b42aa96ad1350d93 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/memory_delete_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/memory_list_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/memory_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7213060f41413bc9da3828d9fe7615bb3609fd07 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/memory_list_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/memory_retrieve_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/memory_retrieve_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b829a4d9dffb924a41db72c164a1a77e3190aabe Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/memory_retrieve_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/memory_update_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/memory_update_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d194af594d353e794d037fb62ab6c45d7dda66e Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/memory_update_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/memory_version_list_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/memory_version_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e3cdb24c3f93af8614577f5da84f041f3d00d33 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/memory_version_list_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/memory_version_retrieve_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/memory_version_retrieve_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90b6520d992ccc938c4c3df06f0ca5adf6355d96 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/memory_stores/__pycache__/memory_version_retrieve_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/message_count_tokens_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/message_count_tokens_params.py new file mode 100644 index 0000000000000000000000000000000000000000..17842a7cde14555172efa0cf0f4259a373a3eb65 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/message_count_tokens_params.py @@ -0,0 +1,291 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union, Iterable, Optional +from typing_extensions import Literal, Required, Annotated, TypeAlias, TypedDict + +from ..._utils import PropertyInfo +from ..model_param import ModelParam +from .beta_tool_param import BetaToolParam +from .beta_message_param import BetaMessageParam +from ..anthropic_beta_param import AnthropicBetaParam +from .beta_text_block_param import BetaTextBlockParam +from .beta_mcp_toolset_param import BetaMCPToolsetParam +from .beta_tool_choice_param import BetaToolChoiceParam +from .beta_output_config_param import BetaOutputConfigParam +from .beta_thinking_config_param import BetaThinkingConfigParam +from .beta_json_output_format_param import BetaJSONOutputFormatParam +from .beta_tool_bash_20241022_param import BetaToolBash20241022Param +from .beta_tool_bash_20250124_param import BetaToolBash20250124Param +from .beta_memory_tool_20250818_param import BetaMemoryTool20250818Param +from .beta_advisor_tool_20260301_param import BetaAdvisorTool20260301Param +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam +from .beta_web_fetch_tool_20250910_param import BetaWebFetchTool20250910Param +from .beta_web_fetch_tool_20260209_param import BetaWebFetchTool20260209Param +from .beta_web_fetch_tool_20260309_param import BetaWebFetchTool20260309Param +from .beta_web_search_tool_20250305_param import BetaWebSearchTool20250305Param +from .beta_web_search_tool_20260209_param import BetaWebSearchTool20260209Param +from .beta_context_management_config_param import BetaContextManagementConfigParam +from .beta_tool_text_editor_20241022_param import BetaToolTextEditor20241022Param +from .beta_tool_text_editor_20250124_param import BetaToolTextEditor20250124Param +from .beta_tool_text_editor_20250429_param import BetaToolTextEditor20250429Param +from .beta_tool_text_editor_20250728_param import BetaToolTextEditor20250728Param +from .beta_tool_computer_use_20241022_param import BetaToolComputerUse20241022Param +from .beta_tool_computer_use_20250124_param import BetaToolComputerUse20250124Param +from .beta_tool_computer_use_20251124_param import BetaToolComputerUse20251124Param +from .beta_code_execution_tool_20250522_param import BetaCodeExecutionTool20250522Param +from .beta_code_execution_tool_20250825_param import BetaCodeExecutionTool20250825Param +from .beta_code_execution_tool_20260120_param import BetaCodeExecutionTool20260120Param +from .beta_tool_search_tool_bm25_20251119_param import BetaToolSearchToolBm25_20251119Param +from .beta_tool_search_tool_regex_20251119_param import BetaToolSearchToolRegex20251119Param +from .beta_request_mcp_server_url_definition_param import BetaRequestMCPServerURLDefinitionParam + +__all__ = ["MessageCountTokensParams", "Tool"] + + +class MessageCountTokensParams(TypedDict, total=False): + messages: Required[Iterable[BetaMessageParam]] + """Input messages. + + Our models are trained to operate on alternating `user` and `assistant` + conversational turns. When creating a new `Message`, you specify the prior + conversational turns with the `messages` parameter, and the model then generates + the next `Message` in the conversation. Consecutive `user` or `assistant` turns + in your request will be combined into a single turn. + + Each input message must be an object with a `role` and `content`. You can + specify a single `user`-role message, or you can include multiple `user` and + `assistant` messages. + + If the final message uses the `assistant` role, the response content will + continue immediately from the content in that message. This can be used to + constrain part of the model's response. + + Example with a single `user` message: + + ```json + [{ "role": "user", "content": "Hello, Claude" }] + ``` + + Example with multiple conversational turns: + + ```json + [ + { "role": "user", "content": "Hello there." }, + { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" }, + { "role": "user", "content": "Can you explain LLMs in plain English?" } + ] + ``` + + Example with a partially-filled response from Claude: + + ```json + [ + { + "role": "user", + "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" + }, + { "role": "assistant", "content": "The best answer is (" } + ] + ``` + + Each input message `content` may be either a single `string` or an array of + content blocks, where each block has a specific `type`. Using a `string` for + `content` is shorthand for an array of one content block of type `"text"`. The + following input messages are equivalent: + + ```json + { "role": "user", "content": "Hello, Claude" } + ``` + + ```json + { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] } + ``` + + See [input examples](https://docs.claude.com/en/api/messages-examples). + + Note that if you want to include a + [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the + top-level `system` parameter — there is no `"system"` role for input messages in + the Messages API. + + There is a limit of 100,000 messages in a single request. + """ + + model: Required[ModelParam] + """ + The model that will complete your prompt.\n\nSee + [models](https://docs.anthropic.com/en/docs/models-overview) for additional + details and options. + """ + + cache_control: Optional[BetaCacheControlEphemeralParam] + """ + Top-level cache control automatically applies a cache_control marker to the last + cacheable block in the request. + """ + + context_management: Optional[BetaContextManagementConfigParam] + """Context management configuration. + + This allows you to control how Claude manages context across multiple requests, + such as whether to clear function results or not. + """ + + mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] + """MCP servers to be utilized in this request""" + + output_config: BetaOutputConfigParam + """Configuration options for the model's output, such as the output format.""" + + output_format: Optional[BetaJSONOutputFormatParam] + """Deprecated: Use `output_config.format` instead. + + See + [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) + + A schema to specify Claude's output format in responses. This parameter will be + removed in a future release. + """ + + speed: Optional[Literal["standard", "fast"]] + """The inference speed mode for this request. + + `"fast"` enables high output-tokens-per-second inference. + """ + + system: Union[str, Iterable[BetaTextBlockParam]] + """System prompt. + + A system prompt is a way of providing context and instructions to Claude, such + as specifying a particular goal or role. See our + [guide to system prompts](https://docs.claude.com/en/docs/system-prompts). + """ + + thinking: BetaThinkingConfigParam + """Configuration for enabling Claude's extended thinking. + + When enabled, responses include `thinking` content blocks showing Claude's + thinking process before the final answer. Requires a minimum budget of 1,024 + tokens and counts towards your `max_tokens` limit. + + See + [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) + for details. + """ + + tool_choice: BetaToolChoiceParam + """How the model should use the provided tools. + + The model can use a specific tool, any available tool, decide by itself, or not + use tools at all. + """ + + tools: Iterable[Tool] + """Definitions of tools that the model may use. + + If you include `tools` in your API request, the model may return `tool_use` + content blocks that represent the model's use of those tools. You can then run + those tools using the tool input generated by the model and then optionally + return results back to the model using `tool_result` content blocks. + + There are two types of tools: **client tools** and **server tools**. The + behavior described below applies to client tools. For + [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools), + see their individual documentation as each has its own behavior (e.g., the + [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)). + + Each tool definition includes: + + - `name`: Name of the tool. + - `description`: Optional, but strongly-recommended description of the tool. + - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the + tool `input` shape that the model will produce in `tool_use` output content + blocks. + + For example, if you defined `tools` as: + + ```json + [ + { + "name": "get_stock_price", + "description": "Get the current stock price for a given ticker symbol.", + "input_schema": { + "type": "object", + "properties": { + "ticker": { + "type": "string", + "description": "The stock ticker symbol, e.g. AAPL for Apple Inc." + } + }, + "required": ["ticker"] + } + } + ] + ``` + + And then asked the model "What's the S&P 500 at today?", the model might produce + `tool_use` content blocks in the response like this: + + ```json + [ + { + "type": "tool_use", + "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", + "name": "get_stock_price", + "input": { "ticker": "^GSPC" } + } + ] + ``` + + You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an + input, and return the following back to the model in a subsequent `user` + message: + + ```json + [ + { + "type": "tool_result", + "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", + "content": "259.75 USD" + } + ] + ``` + + Tools can be used for workflows that include running client-side tools and + functions, or more generally whenever you want the model to produce a particular + JSON structure of output. + + See our [guide](https://docs.claude.com/en/docs/tool-use) for more details. + """ + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" + + +Tool: TypeAlias = Union[ + BetaToolParam, + BetaToolBash20241022Param, + BetaToolBash20250124Param, + BetaCodeExecutionTool20250522Param, + BetaCodeExecutionTool20250825Param, + BetaCodeExecutionTool20260120Param, + BetaToolComputerUse20241022Param, + BetaMemoryTool20250818Param, + BetaToolComputerUse20250124Param, + BetaToolTextEditor20241022Param, + BetaToolComputerUse20251124Param, + BetaToolTextEditor20250124Param, + BetaToolTextEditor20250429Param, + BetaToolTextEditor20250728Param, + BetaWebSearchTool20250305Param, + BetaWebFetchTool20250910Param, + BetaWebSearchTool20260209Param, + BetaWebFetchTool20260209Param, + BetaWebFetchTool20260309Param, + BetaAdvisorTool20260301Param, + BetaToolSearchToolBm25_20251119Param, + BetaToolSearchToolRegex20251119Param, + BetaMCPToolsetParam, +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/message_create_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/message_create_params.py new file mode 100644 index 0000000000000000000000000000000000000000..b5159ea533b763321fb39a1c6c2037409bcb2e99 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/message_create_params.py @@ -0,0 +1,368 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union, Generic, Iterable, Optional +from typing_extensions import Literal, Required, Annotated, TypeAlias, TypedDict + +from ..._types import SequenceNotStr +from ..._utils import PropertyInfo +from ..model_param import ModelParam +from .beta_message_param import BetaMessageParam +from .beta_metadata_param import BetaMetadataParam +from .parsed_beta_message import ResponseFormatT +from ..anthropic_beta_param import AnthropicBetaParam +from .beta_container_params import BetaContainerParams +from .beta_text_block_param import BetaTextBlockParam +from .beta_tool_union_param import BetaToolUnionParam +from .beta_tool_choice_param import BetaToolChoiceParam +from .beta_output_config_param import BetaOutputConfigParam +from .beta_thinking_config_param import BetaThinkingConfigParam +from .beta_json_output_format_param import BetaJSONOutputFormatParam +from .beta_cache_control_ephemeral_param import BetaCacheControlEphemeralParam +from .beta_context_management_config_param import BetaContextManagementConfigParam +from .beta_request_mcp_server_url_definition_param import BetaRequestMCPServerURLDefinitionParam + +__all__ = [ + "MessageCreateParamsBase", + "Container", + "MessageCreateParamsNonStreaming", + "MessageCreateParamsStreaming", + "OutputFormat", +] + + +class MessageCreateParamsBase(TypedDict, total=False): + max_tokens: Required[int] + """The maximum number of tokens to generate before stopping. + + Note that our models may stop _before_ reaching this maximum. This parameter + only specifies the absolute maximum number of tokens to generate. + + Set to `0` to populate the + [prompt cache](https://docs.claude.com/en/docs/build-with-claude/prompt-caching#pre-warming-the-cache) + without generating a response. + + Different models have different maximum values for this parameter. See + [models](https://docs.claude.com/en/docs/models-overview) for details. + """ + + messages: Required[Iterable[BetaMessageParam]] + """Input messages. + + Our models are trained to operate on alternating `user` and `assistant` + conversational turns. When creating a new `Message`, you specify the prior + conversational turns with the `messages` parameter, and the model then generates + the next `Message` in the conversation. Consecutive `user` or `assistant` turns + in your request will be combined into a single turn. + + Each input message must be an object with a `role` and `content`. You can + specify a single `user`-role message, or you can include multiple `user` and + `assistant` messages. + + If the final message uses the `assistant` role, the response content will + continue immediately from the content in that message. This can be used to + constrain part of the model's response. + + Example with a single `user` message: + + ```json + [{ "role": "user", "content": "Hello, Claude" }] + ``` + + Example with multiple conversational turns: + + ```json + [ + { "role": "user", "content": "Hello there." }, + { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" }, + { "role": "user", "content": "Can you explain LLMs in plain English?" } + ] + ``` + + Example with a partially-filled response from Claude: + + ```json + [ + { + "role": "user", + "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" + }, + { "role": "assistant", "content": "The best answer is (" } + ] + ``` + + Each input message `content` may be either a single `string` or an array of + content blocks, where each block has a specific `type`. Using a `string` for + `content` is shorthand for an array of one content block of type `"text"`. The + following input messages are equivalent: + + ```json + { "role": "user", "content": "Hello, Claude" } + ``` + + ```json + { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] } + ``` + + See [input examples](https://docs.claude.com/en/api/messages-examples). + + Note that if you want to include a + [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the + top-level `system` parameter — there is no `"system"` role for input messages in + the Messages API. + + There is a limit of 100,000 messages in a single request. + """ + + model: Required[ModelParam] + """ + The model that will complete your prompt.\n\nSee + [models](https://docs.anthropic.com/en/docs/models-overview) for additional + details and options. + """ + + cache_control: Optional[BetaCacheControlEphemeralParam] + """ + Top-level cache control automatically applies a cache_control marker to the last + cacheable block in the request. + """ + + container: Optional[Container] + """Container identifier for reuse across requests.""" + + context_management: Optional[BetaContextManagementConfigParam] + """Context management configuration. + + This allows you to control how Claude manages context across multiple requests, + such as whether to clear function results or not. + """ + + inference_geo: Optional[str] + """Specifies the geographic region for inference processing. + + If not specified, the workspace's `default_inference_geo` is used. + """ + + mcp_servers: Iterable[BetaRequestMCPServerURLDefinitionParam] + """MCP servers to be utilized in this request""" + + metadata: BetaMetadataParam + """An object describing metadata about the request.""" + + output_config: BetaOutputConfigParam + """Configuration options for the model's output, such as the output format.""" + + output_format: Optional[BetaJSONOutputFormatParam] + """Deprecated: Use `output_config.format` instead. + + See + [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) + + A schema to specify Claude's output format in responses. This parameter will be + removed in a future release. + """ + + service_tier: Literal["auto", "standard_only"] + """ + Determines whether to use priority capacity (if available) or standard capacity + for this request. + + Anthropic offers different levels of service for your API requests. See + [service-tiers](https://docs.claude.com/en/api/service-tiers) for details. + """ + + speed: Optional[Literal["standard", "fast"]] + """The inference speed mode for this request. + + `"fast"` enables high output-tokens-per-second inference. + """ + + stop_sequences: SequenceNotStr[str] + """Custom text sequences that will cause the model to stop generating. + + Our models will normally stop when they have naturally completed their turn, + which will result in a response `stop_reason` of `"end_turn"`. + + If you want the model to stop generating when it encounters custom strings of + text, you can use the `stop_sequences` parameter. If the model encounters one of + the custom sequences, the response `stop_reason` value will be `"stop_sequence"` + and the response `stop_sequence` value will contain the matched stop sequence. + """ + + system: Union[str, Iterable[BetaTextBlockParam]] + """System prompt. + + A system prompt is a way of providing context and instructions to Claude, such + as specifying a particular goal or role. See our + [guide to system prompts](https://docs.claude.com/en/docs/system-prompts). + """ + + temperature: float + """Amount of randomness injected into the response. + + Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0` + for analytical / multiple choice, and closer to `1.0` for creative and + generative tasks. + + Note that even with `temperature` of `0.0`, the results will not be fully + deterministic. + """ + + thinking: BetaThinkingConfigParam + """Configuration for enabling Claude's extended thinking. + + When enabled, responses include `thinking` content blocks showing Claude's + thinking process before the final answer. Requires a minimum budget of 1,024 + tokens and counts towards your `max_tokens` limit. + + See + [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) + for details. + """ + + tool_choice: BetaToolChoiceParam + """How the model should use the provided tools. + + The model can use a specific tool, any available tool, decide by itself, or not + use tools at all. + """ + + tools: Iterable[BetaToolUnionParam] + """Definitions of tools that the model may use. + + If you include `tools` in your API request, the model may return `tool_use` + content blocks that represent the model's use of those tools. You can then run + those tools using the tool input generated by the model and then optionally + return results back to the model using `tool_result` content blocks. + + There are two types of tools: **client tools** and **server tools**. The + behavior described below applies to client tools. For + [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools), + see their individual documentation as each has its own behavior (e.g., the + [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)). + + Each tool definition includes: + + - `name`: Name of the tool. + - `description`: Optional, but strongly-recommended description of the tool. + - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the + tool `input` shape that the model will produce in `tool_use` output content + blocks. + + For example, if you defined `tools` as: + + ```json + [ + { + "name": "get_stock_price", + "description": "Get the current stock price for a given ticker symbol.", + "input_schema": { + "type": "object", + "properties": { + "ticker": { + "type": "string", + "description": "The stock ticker symbol, e.g. AAPL for Apple Inc." + } + }, + "required": ["ticker"] + } + } + ] + ``` + + And then asked the model "What's the S&P 500 at today?", the model might produce + `tool_use` content blocks in the response like this: + + ```json + [ + { + "type": "tool_use", + "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", + "name": "get_stock_price", + "input": { "ticker": "^GSPC" } + } + ] + ``` + + You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an + input, and return the following back to the model in a subsequent `user` + message: + + ```json + [ + { + "type": "tool_result", + "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", + "content": "259.75 USD" + } + ] + ``` + + Tools can be used for workflows that include running client-side tools and + functions, or more generally whenever you want the model to produce a particular + JSON structure of output. + + See our [guide](https://docs.claude.com/en/docs/tool-use) for more details. + """ + + top_k: int + """Only sample from the top K options for each subsequent token. + + Used to remove "long tail" low probability responses. + [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277). + + Recommended for advanced use cases only. + """ + + top_p: float + """Use nucleus sampling. + + In nucleus sampling, we compute the cumulative distribution over all the options + for each subsequent token in decreasing probability order and cut it off once it + reaches a particular probability specified by `top_p`. + + Recommended for advanced use cases only. + """ + + user_profile_id: Optional[str] + """The user profile ID to attribute this request to. + + Use when acting on behalf of a party other than your organization. + """ + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" + + +Container: TypeAlias = Union[BetaContainerParams, str] + + +class ParseMessageCreateParamsBase(MessageCreateParamsBase, Generic[ResponseFormatT]): + output_format: type[ResponseFormatT] # type: ignore[misc] + + +class OutputFormat(TypedDict, total=False): + schema: Required[object] + """The JSON schema of the format""" + + type: Required[Literal["json_schema"]] + + +class MessageCreateParamsNonStreaming(MessageCreateParamsBase, total=False): + stream: Literal[False] + """Whether to incrementally stream the response using server-sent events. + + See [streaming](https://docs.claude.com/en/api/messages-streaming) for details. + """ + + +class MessageCreateParamsStreaming(MessageCreateParamsBase): + stream: Required[Literal[True]] + """Whether to incrementally stream the response using server-sent events. + + See [streaming](https://docs.claude.com/en/api/messages-streaming) for details. + """ + + +MessageCreateParams = Union[MessageCreateParamsNonStreaming, MessageCreateParamsStreaming] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/__init__.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a674c905382f16af3c45579d15705239dc82dbb Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/__init__.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/batch_create_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/batch_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ee98aee333966f0acb09cfc3b93676fa60f6d27 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/batch_create_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/batch_list_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/batch_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97b316f7060bab01dd099674a980e62be94f6d68 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/batch_list_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_deleted_message_batch.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_deleted_message_batch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bce998034aaabedec84fa2c65bca465cbb8ad43f Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_deleted_message_batch.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe76d12bba12aaf467e3bc2475ddce48901e3bce Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch_canceled_result.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch_canceled_result.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d0b8c76f785fc5832c9c66f3f8908785d9903af Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch_canceled_result.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch_errored_result.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch_errored_result.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d55dec8ab70d18e564b67521c6f09c374a54525b Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch_errored_result.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch_expired_result.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch_expired_result.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba1013a84ae5eb405797b4e68bde11a65712ec4c Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch_expired_result.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch_individual_response.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch_individual_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..236891d46eccd5b044dcd2a77223ddf20eb2270b Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch_individual_response.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch_request_counts.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch_request_counts.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84192363317bcb64054ef29650c19ae942bf6307 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch_request_counts.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch_result.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch_result.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7486bc80362ba3b4363b62d57657738420234c7f Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch_result.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch_succeeded_result.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch_succeeded_result.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6dcf0c2f5db8457a33ace3d878d44701f2071fa Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/messages/__pycache__/beta_message_batch_succeeded_result.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/model_list_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/model_list_params.py new file mode 100644 index 0000000000000000000000000000000000000000..f353e0772fb8f39195bd7562a91599382ac661d0 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/model_list_params.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List +from typing_extensions import Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..anthropic_beta_param import AnthropicBetaParam + +__all__ = ["ModelListParams"] + + +class ModelListParams(TypedDict, total=False): + after_id: str + """ID of the object to use as a cursor for pagination. + + When provided, returns the page of results immediately after this object. + """ + + before_id: str + """ID of the object to use as a cursor for pagination. + + When provided, returns the page of results immediately before this object. + """ + + limit: int + """Number of items to return per page. + + Defaults to `20`. Ranges from `1` to `1000`. + """ + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/parsed_beta_message.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/parsed_beta_message.py new file mode 100644 index 0000000000000000000000000000000000000000..0fca18f8ffbbf99b07fd8471cf4c81f5cfbd7e3f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/parsed_beta_message.py @@ -0,0 +1,70 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, List, Union, Generic, Optional +from typing_extensions import TypeVar, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from .beta_message import BetaMessage +from .beta_text_block import BetaTextBlock +from .beta_thinking_block import BetaThinkingBlock +from .beta_tool_use_block import BetaToolUseBlock +from .beta_compaction_block import BetaCompactionBlock +from .beta_mcp_tool_use_block import BetaMCPToolUseBlock +from .beta_mcp_tool_result_block import BetaMCPToolResultBlock +from .beta_server_tool_use_block import BetaServerToolUseBlock +from .beta_container_upload_block import BetaContainerUploadBlock +from .beta_redacted_thinking_block import BetaRedactedThinkingBlock +from .beta_web_search_tool_result_block import BetaWebSearchToolResultBlock +from .beta_code_execution_tool_result_block import BetaCodeExecutionToolResultBlock +from .beta_bash_code_execution_tool_result_block import BetaBashCodeExecutionToolResultBlock +from .beta_text_editor_code_execution_tool_result_block import BetaTextEditorCodeExecutionToolResultBlock + +ResponseFormatT = TypeVar("ResponseFormatT", default=None) + + +__all__ = [ + "ParsedBetaTextBlock", + "ParsedBetaContentBlock", + "ParsedBetaMessage", +] + + +class ParsedBetaTextBlock(BetaTextBlock, Generic[ResponseFormatT]): + parsed_output: Optional[ResponseFormatT] = None + + __api_exclude__ = {"parsed_output"} + + +# Note that generic unions are not valid for pydantic at runtime +ParsedBetaContentBlock: TypeAlias = Annotated[ + Union[ + ParsedBetaTextBlock[ResponseFormatT], + BetaThinkingBlock, + BetaRedactedThinkingBlock, + BetaToolUseBlock, + BetaServerToolUseBlock, + BetaWebSearchToolResultBlock, + BetaCodeExecutionToolResultBlock, + BetaBashCodeExecutionToolResultBlock, + BetaTextEditorCodeExecutionToolResultBlock, + BetaMCPToolUseBlock, + BetaMCPToolResultBlock, + BetaContainerUploadBlock, + BetaCompactionBlock, + ], + PropertyInfo(discriminator="type"), +] + + +class ParsedBetaMessage(BetaMessage, Generic[ResponseFormatT]): + if TYPE_CHECKING: + content: List[ParsedBetaContentBlock[ResponseFormatT]] # type: ignore[assignment] + else: + content: List[ParsedBetaContentBlock] + + @property + def parsed_output(self) -> Optional[ResponseFormatT]: + for content in self.content: + if content.type == "text" and content.parsed_output: + return content.parsed_output + return None diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/session_list_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/session_list_params.py new file mode 100644 index 0000000000000000000000000000000000000000..3852606c981956e4504bf5cc8cf78c1066f34bd0 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/session_list_params.py @@ -0,0 +1,62 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union +from datetime import datetime +from typing_extensions import Literal, Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..anthropic_beta_param import AnthropicBetaParam + +__all__ = ["SessionListParams"] + + +class SessionListParams(TypedDict, total=False): + agent_id: str + """Filter sessions created with this agent ID.""" + + agent_version: int + """Filter by agent version. Only applies when agent_id is also set.""" + + created_at_gt: Annotated[Union[str, datetime], PropertyInfo(alias="created_at[gt]", format="iso8601")] + """Return sessions created after this time (exclusive).""" + + created_at_gte: Annotated[Union[str, datetime], PropertyInfo(alias="created_at[gte]", format="iso8601")] + """Return sessions created at or after this time (inclusive).""" + + created_at_lt: Annotated[Union[str, datetime], PropertyInfo(alias="created_at[lt]", format="iso8601")] + """Return sessions created before this time (exclusive).""" + + created_at_lte: Annotated[Union[str, datetime], PropertyInfo(alias="created_at[lte]", format="iso8601")] + """Return sessions created at or before this time (inclusive).""" + + include_archived: bool + """When true, includes archived sessions. Default: false (exclude archived).""" + + limit: int + """Maximum number of results to return.""" + + memory_store_id: str + """ + Filter sessions whose resources contain a memory_store with this memory store + ID. + """ + + order: Literal["asc", "desc"] + """Sort direction for results, ordered by created_at. + + Defaults to desc (newest first). + """ + + page: str + """Opaque pagination cursor from a previous response's next_page.""" + + statuses: List[Literal["rescheduling", "running", "idle", "terminated"]] + """Filter by session status. + + Repeat the parameter to match any of multiple statuses. + """ + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/__init__.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..749f20f827cf5b67fe57afc648f9db60e5dcbadd Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/__init__.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_custom_tool_use_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_custom_tool_use_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b65b91e8809481f1031f6cf77f5b0438bc5ddad Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_custom_tool_use_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_mcp_tool_result_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_mcp_tool_result_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28d6e1176f74a4403d57c02b00bc7fb64ebc5807 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_mcp_tool_result_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_mcp_tool_use_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_mcp_tool_use_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9ec054701372ac710c3bac876107636ee75d54b Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_mcp_tool_use_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_message_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_message_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91c0372972950c683c9c7f209bec4b61d5afd46d Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_message_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_thinking_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_thinking_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d55f36e332cc735660316e494e44b5d168dda8c0 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_thinking_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_thread_context_compacted_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_thread_context_compacted_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27f04653851e71e53b6626ba984ab100e5fd7c2e Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_thread_context_compacted_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_thread_message_received_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_thread_message_received_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddbd4d70822ccece4408c2004e0fa812d0fb1749 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_thread_message_received_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_thread_message_sent_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_thread_message_sent_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c270a0f165f468b728f4a6462ca9f2f10c2d3997 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_thread_message_sent_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_tool_result_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_tool_result_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9445174c236ba066bdb66f38b2c91b16de29d8a5 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_tool_result_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_tool_use_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_tool_use_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c35fc15aaaf8a8225532c1b42443e748d64892e Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_agent_tool_use_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_base64_document_source.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_base64_document_source.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a81db53b192c40281707c5764353d75db35a9dd Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_base64_document_source.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_base64_document_source_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_base64_document_source_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45a0c15872f2c932391977e1f32d5400ef23ebad Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_base64_document_source_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_base64_image_source.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_base64_image_source.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..403d6c796b0b0b1abaaa6d5d5bb84928f1107537 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_base64_image_source.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_base64_image_source_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_base64_image_source_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a2983432a1cc6222b6cbb13fa81e5f96d4cddcb Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_base64_image_source_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_billing_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_billing_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..600b725ba48dbede55a68129056d110454edba5b Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_billing_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_delete_session_resource.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_delete_session_resource.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..946dfb451cd80b4138e8625106e6cf3f2a5d5eca Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_delete_session_resource.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_document_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_document_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3df5bdeabfd6e9aff93bdc0ddaaad1ea47d7c5e Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_document_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_document_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_document_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93d66c49b35fd18c2e4e12a3344795a9ee3b0fbf Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_document_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_event_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_event_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31e2d1e0002f15c70b93c77158b2eaba735a7460 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_event_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_file_document_source.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_file_document_source.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1bf985a8284ee0e7720d1088b909e4982cd6e73 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_file_document_source.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_file_document_source_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_file_document_source_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c60786af6e4c8f649d1f2b0be0c04af7fe3b1b0d Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_file_document_source_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_file_image_source.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_file_image_source.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd6b2b1edc55c7c1282d204c40f79c92638ca9d4 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_file_image_source.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_file_image_source_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_file_image_source_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c379646d3810aa8921505229151cf3d957e1cd6 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_file_image_source_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_file_resource.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_file_resource.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a3b6efe09303f618cef972f1c6a5bc3997bdc6d Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_file_resource.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_file_rubric.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_file_rubric.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13c08f1241395c1aa9b01bcfa05801994ce21246 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_file_rubric.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_file_rubric_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_file_rubric_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b53a14ec263f28fc4ccabb385b70de32c8d0045 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_file_rubric_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_github_repository_resource.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_github_repository_resource.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..423e2ead9d0b781fb7c0f9f79c1d88a031973bf4 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_github_repository_resource.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_image_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_image_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d83b353a0029ff806a987b727cee83b99792fef6 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_image_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_image_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_image_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9621c726f705b54f813410a76567f26286cb0f4 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_image_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_mcp_authentication_failed_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_mcp_authentication_failed_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..185dd96bd018e03a7a9cbe8ec207c2eb846d75a9 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_mcp_authentication_failed_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_mcp_connection_failed_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_mcp_connection_failed_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dafa301d93e796f452e5f851258c2f8ae818d543 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_mcp_connection_failed_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_memory_store_resource.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_memory_store_resource.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e39bb90c87dca6068ad0ea77176775dac9b45ff7 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_memory_store_resource.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_model_overloaded_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_model_overloaded_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29bb9e9fb38cc3beb80079773adc5398b65d81c4 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_model_overloaded_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_model_rate_limited_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_model_rate_limited_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24407202255394d88b07662d43571abfb41c23f1 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_model_rate_limited_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_model_request_failed_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_model_request_failed_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5f58c5463511dbcbe0731f858b019326286f531 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_model_request_failed_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_plain_text_document_source.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_plain_text_document_source.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..840e4eb7f65ca203720f64041dbfdbb8f985425a Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_plain_text_document_source.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_plain_text_document_source_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_plain_text_document_source_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..596fdf0b0c3e71207e625c66c611d7f83b0110e3 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_plain_text_document_source_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_retry_status_exhausted.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_retry_status_exhausted.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49bfcffcd9f70d6cd7f22bd9c111ba44d54e5825 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_retry_status_exhausted.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_retry_status_retrying.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_retry_status_retrying.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96bdb09a32809d888beee670af5846fd0e0db704 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_retry_status_retrying.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_retry_status_terminal.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_retry_status_terminal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b154543e19922f31c2a738d0d38e2d5b2f59c80d Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_retry_status_terminal.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_send_session_events.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_send_session_events.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6c705827ac4b72e6651a202dc98c4242601a74f Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_send_session_events.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_deleted_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_deleted_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90d9de08743b70b218bfa25ed9ab1a9bd841e55f Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_deleted_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_end_turn.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_end_turn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08982f2b4224fa2f650acfca0d2bf58fbda14abd Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_end_turn.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_error_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_error_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17f0623016f0f7803b7d8ae0cedb5860fdac6527 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_error_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f3e5285a3dc87e94a92847c0600c117fa5937bd Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_requires_action.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_requires_action.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7ed1330e77fef461f71e25e7b2c22a53094021a Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_requires_action.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_resource.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_resource.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40b8baf24ca7778ff241b553560ba059fb1b82ee Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_resource.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_retries_exhausted.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_retries_exhausted.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77ef49bc5f326b2b91b5abfe548a1f3138bbb67c Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_retries_exhausted.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_status_idle_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_status_idle_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17e61ec3d5c6fa43eac830f53dd684eb0ed3644d Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_status_idle_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_status_rescheduled_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_status_rescheduled_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f865d258649a1a3f5c870b56787bc0969e1ba48c Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_status_rescheduled_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_status_running_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_status_running_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83403c13aed681fe0e9ee8ba2d7e6b0214d73a30 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_status_running_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_status_terminated_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_status_terminated_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c94f0ff92ab3c6e1a919245c2d958aeab319b68c Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_status_terminated_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16dcbf1c6430f497cdc3813a49f802f74136b03a Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_agent.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_agent.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4dac5bd98d58a9370c946c29de884dc16dfa54db Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_agent.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_created_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_created_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..774fe9a71e808fac5ecac48495c8f528f86736b8 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_created_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_stats.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_stats.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3175bf0a20449fbd8710fe58dfe813e5ac8b0f84 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_stats.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_status.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_status.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cbdf2f58cc24259ee2de4f2f83baf248654a5a2 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_status.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_status_idle_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_status_idle_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f860a7356595d006618301b0b9529a445fdb284 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_status_idle_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_status_rescheduled_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_status_rescheduled_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40dc5e68201434af44ba4b9c9c3d362656974831 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_status_rescheduled_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_status_running_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_status_running_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..989854925f14f25740d53864e27b9ea0f42293d9 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_status_running_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_status_terminated_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_status_terminated_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8e22f596f6b822e5f2a3a1bf07193bb5845b2cf Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_status_terminated_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_usage.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_usage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d417a064765a84b87ee23a02e37abda3fd7970fb Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_session_thread_usage.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_span_model_request_end_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_span_model_request_end_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42c18b5813ad6dd71f07b66f14504a1c562d8552 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_span_model_request_end_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_span_model_request_start_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_span_model_request_start_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5fd0f7c28226c56957accec448d9036cc147302 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_span_model_request_start_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_span_model_usage.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_span_model_usage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5e95ae9e9b6ea5d4308e4ae295d073f27e8b740 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_span_model_usage.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_span_outcome_evaluation_end_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_span_outcome_evaluation_end_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..391594a3a3fd15eb850b95ad0eeac76db8be1812 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_span_outcome_evaluation_end_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_span_outcome_evaluation_ongoing_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_span_outcome_evaluation_ongoing_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e1a27e4587060c7ffcbc85c1e04fb48c8665090 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_span_outcome_evaluation_ongoing_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_span_outcome_evaluation_start_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_span_outcome_evaluation_start_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74419b26558e44995f1d329627c0dc0934f81cee Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_span_outcome_evaluation_start_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_stream_session_events.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_stream_session_events.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..544d433372fb3b65f92d652c1db2affbc1eb50de Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_stream_session_events.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_stream_session_thread_events.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_stream_session_thread_events.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8fa258b4f463e5e484677507b03f6d8f1420c65 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_stream_session_thread_events.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_text_block.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_text_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ac92b0666a969919007dd99e7ff4c0fa2af3971 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_text_block.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_text_block_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_text_block_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a79bc62368b002a7b04a73bbf804de5b6699f188 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_text_block_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_text_rubric.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_text_rubric.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d959914300bc72e047e4312d3ec62a138c193e8 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_text_rubric.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_text_rubric_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_text_rubric_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aeb48aed859406410301e22b00b9e1b4ae45bed3 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_text_rubric_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_unknown_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_unknown_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a657df9abc0d5f4a423e6b9b15717a3f1708fca Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_unknown_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_url_document_source.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_url_document_source.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..039a88be84c9d868eb4278c4fc854302265c1233 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_url_document_source.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_url_document_source_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_url_document_source_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2647e3e6180c644c634d51d89dea544e5e18e6b Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_url_document_source_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_url_image_source.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_url_image_source.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a07f7610fdea040d0c6d8cb7d24c88dde7d51359 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_url_image_source.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_url_image_source_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_url_image_source_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..000af26cdf78a8c4db89a3919a687a2eb37dd95b Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_url_image_source_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_custom_tool_result_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_custom_tool_result_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad594e66760d7ca72a8b45c3299c0e3b230c12ff Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_custom_tool_result_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_custom_tool_result_event_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_custom_tool_result_event_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..096343b90b799084140e2f36892e4831bbabb679 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_custom_tool_result_event_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_define_outcome_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_define_outcome_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53f15863899a1761d146dd31c38c470b42cfa1eb Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_define_outcome_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_define_outcome_event_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_define_outcome_event_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd56efa31250ea21601d308cac048ea81caa0e47 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_define_outcome_event_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_interrupt_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_interrupt_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e09b37e1fc7716b9a78ccb741161ca062e78773 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_interrupt_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_interrupt_event_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_interrupt_event_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3d399d51f88aa362ed254e9ecb33791667dd034 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_interrupt_event_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_message_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_message_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a6964b1c5cb057e65c604c1caa7d7bc511f87bf Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_message_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_message_event_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_message_event_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c82b408207bf942685b4e21eccbcbbd8c1ee062c Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_message_event_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_tool_confirmation_event.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_tool_confirmation_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73b3890ad2006b574e91bc58785fbb01f0ac9119 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_tool_confirmation_event.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_tool_confirmation_event_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_tool_confirmation_event_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e1f7e6fc67d37e5fd653386db4275d3d4db15cb Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/beta_managed_agents_user_tool_confirmation_event_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/event_list_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/event_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0f1b00e3258dd69f1a1df92ee891f7a2a93403b Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/event_list_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/event_send_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/event_send_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..848729b3551d333dbb8f24fe8cd4ba2dbfa02873 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/event_send_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/resource_add_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/resource_add_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94ea67712c3df1b3b662cb447daa5e395df1dc74 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/resource_add_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/resource_list_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/resource_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db875799ffd292ca5e80c95263fef0d2ef7e8345 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/resource_list_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/resource_retrieve_response.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/resource_retrieve_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8dfe3f70a22c4fbbe0558b13547b76b790e51c6 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/resource_retrieve_response.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/resource_update_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/resource_update_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..800ad85be1082c498a08dbbf5cd5e724c06e07d8 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/resource_update_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/resource_update_response.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/resource_update_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8bc0b4625f20eb51cb89c1ce6826a03bf43c109 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/resource_update_response.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/thread_list_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/thread_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ee2c3061304397d66d8dfbbb646298b96ecef97 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/__pycache__/thread_list_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_custom_tool_use_event.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_custom_tool_use_event.py new file mode 100644 index 0000000000000000000000000000000000000000..d52b781d04aab1ad5eac1474439c36a53c3eb0b1 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_custom_tool_use_event.py @@ -0,0 +1,37 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional +from datetime import datetime +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["BetaManagedAgentsAgentCustomToolUseEvent"] + + +class BetaManagedAgentsAgentCustomToolUseEvent(BaseModel): + """Event emitted when the agent calls a custom tool. + + The session goes idle until the client sends a `user.custom_tool_result` event with the result. + """ + + id: str + """Unique identifier for this event.""" + + input: Dict[str, object] + """Input parameters for the tool call.""" + + name: str + """Name of the custom tool being called.""" + + processed_at: datetime + """A timestamp in RFC 3339 format""" + + type: Literal["agent.custom_tool_use"] + + session_thread_id: Optional[str] = None + """ + When set, this event was cross-posted from a subagent's thread to surface its + custom tool use on the primary thread's stream. Empty on the thread's own + events. Echo this on a `user.custom_tool_result` event to route the result back. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_mcp_tool_result_event.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_mcp_tool_result_event.py new file mode 100644 index 0000000000000000000000000000000000000000..3ce0277ee8d51d0b01018834e4d7343f83f3322b --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_mcp_tool_result_event.py @@ -0,0 +1,39 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from datetime import datetime +from typing_extensions import Literal, Annotated, TypeAlias + +from ...._utils import PropertyInfo +from ...._models import BaseModel +from .beta_managed_agents_text_block import BetaManagedAgentsTextBlock +from .beta_managed_agents_image_block import BetaManagedAgentsImageBlock +from .beta_managed_agents_document_block import BetaManagedAgentsDocumentBlock + +__all__ = ["BetaManagedAgentsAgentMCPToolResultEvent", "Content"] + +Content: TypeAlias = Annotated[ + Union[BetaManagedAgentsTextBlock, BetaManagedAgentsImageBlock, BetaManagedAgentsDocumentBlock], + PropertyInfo(discriminator="type"), +] + + +class BetaManagedAgentsAgentMCPToolResultEvent(BaseModel): + """Event representing the result of an MCP tool execution.""" + + id: str + """Unique identifier for this event.""" + + mcp_tool_use_id: str + """The id of the `agent.mcp_tool_use` event this result corresponds to.""" + + processed_at: datetime + """A timestamp in RFC 3339 format""" + + type: Literal["agent.mcp_tool_result"] + + content: Optional[List[Content]] = None + """The result content returned by the tool.""" + + is_error: Optional[bool] = None + """Whether the tool execution resulted in an error.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_mcp_tool_use_event.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_mcp_tool_use_event.py new file mode 100644 index 0000000000000000000000000000000000000000..6d2dc37492611dbe7a6cf2251f9d14f7d7126431 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_mcp_tool_use_event.py @@ -0,0 +1,41 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional +from datetime import datetime +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["BetaManagedAgentsAgentMCPToolUseEvent"] + + +class BetaManagedAgentsAgentMCPToolUseEvent(BaseModel): + """Event emitted when the agent invokes a tool provided by an MCP server.""" + + id: str + """Unique identifier for this event.""" + + input: Dict[str, object] + """Input parameters for the tool call.""" + + mcp_server_name: str + """Name of the MCP server providing the tool.""" + + name: str + """Name of the MCP tool being used.""" + + processed_at: datetime + """A timestamp in RFC 3339 format""" + + type: Literal["agent.mcp_tool_use"] + + evaluated_permission: Optional[Literal["allow", "ask", "deny"]] = None + """AgentEvaluatedPermission enum""" + + session_thread_id: Optional[str] = None + """ + When set, this event was cross-posted from a subagent's thread to surface its + permission request on the primary thread's stream. Empty on the thread's own + events. Echo this on a `user.tool_confirmation` event to route the approval + back. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_message_event.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_message_event.py new file mode 100644 index 0000000000000000000000000000000000000000..3db547b49a1bac25c86c5bff77ff110523cdf9c9 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_message_event.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List +from datetime import datetime +from typing_extensions import Literal + +from ...._models import BaseModel +from .beta_managed_agents_text_block import BetaManagedAgentsTextBlock + +__all__ = ["BetaManagedAgentsAgentMessageEvent"] + + +class BetaManagedAgentsAgentMessageEvent(BaseModel): + """An agent response event in the session conversation.""" + + id: str + """Unique identifier for this event.""" + + content: List[BetaManagedAgentsTextBlock] + """Array of text blocks comprising the agent response.""" + + processed_at: datetime + """A timestamp in RFC 3339 format""" + + type: Literal["agent.message"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_thinking_event.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_thinking_event.py new file mode 100644 index 0000000000000000000000000000000000000000..4da7326402d9ff7df88bea103cca07ffbe8f63b7 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_thinking_event.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from datetime import datetime +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["BetaManagedAgentsAgentThinkingEvent"] + + +class BetaManagedAgentsAgentThinkingEvent(BaseModel): + """Indicates the agent is making forward progress via extended thinking. + + A progress signal, not a content carrier. + """ + + id: str + """Unique identifier for this event.""" + + processed_at: datetime + """A timestamp in RFC 3339 format""" + + type: Literal["agent.thinking"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_thread_context_compacted_event.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_thread_context_compacted_event.py new file mode 100644 index 0000000000000000000000000000000000000000..6db0444ea518d6e1a7a27acfd8c967015c6c520b --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_thread_context_compacted_event.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from datetime import datetime +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["BetaManagedAgentsAgentThreadContextCompactedEvent"] + + +class BetaManagedAgentsAgentThreadContextCompactedEvent(BaseModel): + """Indicates that context compaction (summarization) occurred during the session.""" + + id: str + """Unique identifier for this event.""" + + processed_at: datetime + """A timestamp in RFC 3339 format""" + + type: Literal["agent.thread_context_compacted"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_thread_message_received_event.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_thread_message_received_event.py new file mode 100644 index 0000000000000000000000000000000000000000..b4783fc830611426c0755ed0c0e3fee38b646972 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_thread_message_received_event.py @@ -0,0 +1,44 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from datetime import datetime +from typing_extensions import Literal, Annotated, TypeAlias + +from ...._utils import PropertyInfo +from ...._models import BaseModel +from .beta_managed_agents_text_block import BetaManagedAgentsTextBlock +from .beta_managed_agents_image_block import BetaManagedAgentsImageBlock +from .beta_managed_agents_document_block import BetaManagedAgentsDocumentBlock + +__all__ = ["BetaManagedAgentsAgentThreadMessageReceivedEvent", "Content"] + +Content: TypeAlias = Annotated[ + Union[BetaManagedAgentsTextBlock, BetaManagedAgentsImageBlock, BetaManagedAgentsDocumentBlock], + PropertyInfo(discriminator="type"), +] + + +class BetaManagedAgentsAgentThreadMessageReceivedEvent(BaseModel): + """ + Delivery event written to the target thread's input stream when an agent-to-agent message arrives. + """ + + id: str + """Unique identifier for this event.""" + + content: List[Content] + """Message content blocks.""" + + from_session_thread_id: str + """Public `sthr_` ID of the thread that sent the message.""" + + processed_at: datetime + """A timestamp in RFC 3339 format""" + + type: Literal["agent.thread_message_received"] + + from_agent_name: Optional[str] = None + """Name of the callable agent this message came from. + + Absent when received from the primary agent. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_thread_message_sent_event.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_thread_message_sent_event.py new file mode 100644 index 0000000000000000000000000000000000000000..595b7de6eb9679590e24a7eb5ce13992a4391592 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_thread_message_sent_event.py @@ -0,0 +1,44 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from datetime import datetime +from typing_extensions import Literal, Annotated, TypeAlias + +from ...._utils import PropertyInfo +from ...._models import BaseModel +from .beta_managed_agents_text_block import BetaManagedAgentsTextBlock +from .beta_managed_agents_image_block import BetaManagedAgentsImageBlock +from .beta_managed_agents_document_block import BetaManagedAgentsDocumentBlock + +__all__ = ["BetaManagedAgentsAgentThreadMessageSentEvent", "Content"] + +Content: TypeAlias = Annotated[ + Union[BetaManagedAgentsTextBlock, BetaManagedAgentsImageBlock, BetaManagedAgentsDocumentBlock], + PropertyInfo(discriminator="type"), +] + + +class BetaManagedAgentsAgentThreadMessageSentEvent(BaseModel): + """ + Observability event emitted to the sender's output stream when an agent-to-agent message is sent. + """ + + id: str + """Unique identifier for this event.""" + + content: List[Content] + """Message content blocks.""" + + processed_at: datetime + """A timestamp in RFC 3339 format""" + + to_session_thread_id: str + """Public `sthr_` ID of the thread the message was sent to.""" + + type: Literal["agent.thread_message_sent"] + + to_agent_name: Optional[str] = None + """Name of the callable agent this message was sent to. + + Absent when sent to the primary agent. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_tool_result_event.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_tool_result_event.py new file mode 100644 index 0000000000000000000000000000000000000000..f61925d19665596aa6274f26d343c1f746e6587e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_tool_result_event.py @@ -0,0 +1,39 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from datetime import datetime +from typing_extensions import Literal, Annotated, TypeAlias + +from ...._utils import PropertyInfo +from ...._models import BaseModel +from .beta_managed_agents_text_block import BetaManagedAgentsTextBlock +from .beta_managed_agents_image_block import BetaManagedAgentsImageBlock +from .beta_managed_agents_document_block import BetaManagedAgentsDocumentBlock + +__all__ = ["BetaManagedAgentsAgentToolResultEvent", "Content"] + +Content: TypeAlias = Annotated[ + Union[BetaManagedAgentsTextBlock, BetaManagedAgentsImageBlock, BetaManagedAgentsDocumentBlock], + PropertyInfo(discriminator="type"), +] + + +class BetaManagedAgentsAgentToolResultEvent(BaseModel): + """Event representing the result of an agent tool execution.""" + + id: str + """Unique identifier for this event.""" + + processed_at: datetime + """A timestamp in RFC 3339 format""" + + tool_use_id: str + """The id of the `agent.tool_use` event this result corresponds to.""" + + type: Literal["agent.tool_result"] + + content: Optional[List[Content]] = None + """The result content returned by the tool.""" + + is_error: Optional[bool] = None + """Whether the tool execution resulted in an error.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_tool_use_event.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_tool_use_event.py new file mode 100644 index 0000000000000000000000000000000000000000..3acf695170098739da74a61d1588ef0d255d8bbd --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_agent_tool_use_event.py @@ -0,0 +1,38 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional +from datetime import datetime +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["BetaManagedAgentsAgentToolUseEvent"] + + +class BetaManagedAgentsAgentToolUseEvent(BaseModel): + """Event emitted when the agent invokes a built-in agent tool.""" + + id: str + """Unique identifier for this event.""" + + input: Dict[str, object] + """Input parameters for the tool call.""" + + name: str + """Name of the agent tool being used.""" + + processed_at: datetime + """A timestamp in RFC 3339 format""" + + type: Literal["agent.tool_use"] + + evaluated_permission: Optional[Literal["allow", "ask", "deny"]] = None + """AgentEvaluatedPermission enum""" + + session_thread_id: Optional[str] = None + """ + When set, this event was cross-posted from a subagent's thread to surface its + permission request on the primary thread's stream. Empty on the thread's own + events. Echo this on a `user.tool_confirmation` event to route the approval + back. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_base64_document_source.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_base64_document_source.py new file mode 100644 index 0000000000000000000000000000000000000000..45e488fc23fa455d911cb90fcf0ef1216663921e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_base64_document_source.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["BetaManagedAgentsBase64DocumentSource"] + + +class BetaManagedAgentsBase64DocumentSource(BaseModel): + """Base64-encoded document data.""" + + data: str + """Base64-encoded document data.""" + + media_type: str + """MIME type of the document (e.g., "application/pdf").""" + + type: Literal["base64"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_base64_document_source_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_base64_document_source_param.py new file mode 100644 index 0000000000000000000000000000000000000000..7526fc2938a13014de6e7e56df2c8387af16d1b8 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_base64_document_source_param.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaManagedAgentsBase64DocumentSourceParam"] + + +class BetaManagedAgentsBase64DocumentSourceParam(TypedDict, total=False): + """Base64-encoded document data.""" + + data: Required[str] + """Base64-encoded document data.""" + + media_type: Required[str] + """MIME type of the document (e.g., "application/pdf").""" + + type: Required[Literal["base64"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_base64_image_source.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_base64_image_source.py new file mode 100644 index 0000000000000000000000000000000000000000..925627527a5fe8f99378ca64a42c8b2b96503c74 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_base64_image_source.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["BetaManagedAgentsBase64ImageSource"] + + +class BetaManagedAgentsBase64ImageSource(BaseModel): + """Base64-encoded image data.""" + + data: str + """Base64-encoded image data.""" + + media_type: str + """ + MIME type of the image (e.g., "image/png", "image/jpeg", "image/gif", + "image/webp"). + """ + + type: Literal["base64"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_base64_image_source_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_base64_image_source_param.py new file mode 100644 index 0000000000000000000000000000000000000000..46a555108d31fadc1749d50421fe22dc5aa1e0b5 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_base64_image_source_param.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BetaManagedAgentsBase64ImageSourceParam"] + + +class BetaManagedAgentsBase64ImageSourceParam(TypedDict, total=False): + """Base64-encoded image data.""" + + data: Required[str] + """Base64-encoded image data.""" + + media_type: Required[str] + """ + MIME type of the image (e.g., "image/png", "image/jpeg", "image/gif", + "image/webp"). + """ + + type: Required[Literal["base64"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_billing_error.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_billing_error.py new file mode 100644 index 0000000000000000000000000000000000000000..325c3aa6dcc3653098602937767b297f8dba28fb --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_billing_error.py @@ -0,0 +1,35 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Literal, Annotated, TypeAlias + +from ...._utils import PropertyInfo +from ...._models import BaseModel +from .beta_managed_agents_retry_status_retrying import BetaManagedAgentsRetryStatusRetrying +from .beta_managed_agents_retry_status_terminal import BetaManagedAgentsRetryStatusTerminal +from .beta_managed_agents_retry_status_exhausted import BetaManagedAgentsRetryStatusExhausted + +__all__ = ["BetaManagedAgentsBillingError", "RetryStatus"] + +RetryStatus: TypeAlias = Annotated[ + Union[ + BetaManagedAgentsRetryStatusRetrying, + BetaManagedAgentsRetryStatusExhausted, + BetaManagedAgentsRetryStatusTerminal, + ], + PropertyInfo(discriminator="type"), +] + + +class BetaManagedAgentsBillingError(BaseModel): + """ + The caller's organization or workspace cannot make model requests — out of credits or spend limit reached. Retrying with the same credentials will not succeed; the caller must resolve the billing state. + """ + + message: str + """Human-readable error description.""" + + retry_status: RetryStatus + """What the client should do next in response to this error.""" + + type: Literal["billing_error"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_delete_session_resource.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_delete_session_resource.py new file mode 100644 index 0000000000000000000000000000000000000000..54d6a5906a2daa4b13623a2833ab7255c6958c5d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_delete_session_resource.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["BetaManagedAgentsDeleteSessionResource"] + + +class BetaManagedAgentsDeleteSessionResource(BaseModel): + """Confirmation of resource deletion.""" + + id: str + + type: Literal["session_resource_deleted"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_document_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_document_block.py new file mode 100644 index 0000000000000000000000000000000000000000..3e4ddb9ed2492fc8b575644945c2252b623aada2 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_document_block.py @@ -0,0 +1,40 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from ...._utils import PropertyInfo +from ...._models import BaseModel +from .beta_managed_agents_url_document_source import BetaManagedAgentsURLDocumentSource +from .beta_managed_agents_file_document_source import BetaManagedAgentsFileDocumentSource +from .beta_managed_agents_base64_document_source import BetaManagedAgentsBase64DocumentSource +from .beta_managed_agents_plain_text_document_source import BetaManagedAgentsPlainTextDocumentSource + +__all__ = ["BetaManagedAgentsDocumentBlock", "Source"] + +Source: TypeAlias = Annotated[ + Union[ + BetaManagedAgentsBase64DocumentSource, + BetaManagedAgentsPlainTextDocumentSource, + BetaManagedAgentsURLDocumentSource, + BetaManagedAgentsFileDocumentSource, + ], + PropertyInfo(discriminator="type"), +] + + +class BetaManagedAgentsDocumentBlock(BaseModel): + """ + Document content, either specified directly as base64 data, as text, or as a reference via a URL. + """ + + source: Source + """Union type for document source variants.""" + + type: Literal["document"] + + context: Optional[str] = None + """Additional context about the document for the model.""" + + title: Optional[str] = None + """The title of the document.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_document_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_document_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..00d863f6f2330166ee579fc2ebe388346d25956d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_document_block_param.py @@ -0,0 +1,37 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .beta_managed_agents_url_document_source_param import BetaManagedAgentsURLDocumentSourceParam +from .beta_managed_agents_file_document_source_param import BetaManagedAgentsFileDocumentSourceParam +from .beta_managed_agents_base64_document_source_param import BetaManagedAgentsBase64DocumentSourceParam +from .beta_managed_agents_plain_text_document_source_param import BetaManagedAgentsPlainTextDocumentSourceParam + +__all__ = ["BetaManagedAgentsDocumentBlockParam", "Source"] + +Source: TypeAlias = Union[ + BetaManagedAgentsBase64DocumentSourceParam, + BetaManagedAgentsPlainTextDocumentSourceParam, + BetaManagedAgentsURLDocumentSourceParam, + BetaManagedAgentsFileDocumentSourceParam, +] + + +class BetaManagedAgentsDocumentBlockParam(TypedDict, total=False): + """ + Document content, either specified directly as base64 data, as text, or as a reference via a URL. + """ + + source: Required[Source] + """Union type for document source variants.""" + + type: Required[Literal["document"]] + + context: Optional[str] + """Additional context about the document for the model.""" + + title: Optional[str] + """The title of the document.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_event_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_event_params.py new file mode 100644 index 0000000000000000000000000000000000000000..75327dd560f4f01df5638b2fd9fee32eb8285f1e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/beta_managed_agents_event_params.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .beta_managed_agents_user_message_event_params import BetaManagedAgentsUserMessageEventParams +from .beta_managed_agents_user_interrupt_event_params import BetaManagedAgentsUserInterruptEventParams +from .beta_managed_agents_user_define_outcome_event_params import BetaManagedAgentsUserDefineOutcomeEventParams +from .beta_managed_agents_user_tool_confirmation_event_params import BetaManagedAgentsUserToolConfirmationEventParams +from .beta_managed_agents_user_custom_tool_result_event_params import BetaManagedAgentsUserCustomToolResultEventParams + +__all__ = ["BetaManagedAgentsEventParams"] + +BetaManagedAgentsEventParams: TypeAlias = Union[ + BetaManagedAgentsUserMessageEventParams, + BetaManagedAgentsUserInterruptEventParams, + BetaManagedAgentsUserToolConfirmationEventParams, + BetaManagedAgentsUserCustomToolResultEventParams, + BetaManagedAgentsUserDefineOutcomeEventParams, +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/threads/__init__.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/threads/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..520b224811a76b6a6f0769cd25aafb9a7445715e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/threads/__init__.py @@ -0,0 +1,5 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .event_list_params import EventListParams as EventListParams diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/threads/__pycache__/__init__.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/threads/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b75b47a63fae474477053bda8d6d676efa3ddcc Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/threads/__pycache__/__init__.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/threads/__pycache__/event_list_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/threads/__pycache__/event_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adf6135d1711d5b9acf18b10d5423f9146139a95 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/threads/__pycache__/event_list_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/threads/event_list_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/threads/event_list_params.py new file mode 100644 index 0000000000000000000000000000000000000000..c2128b975f941325258d3818c00521fa6cefd89d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/sessions/threads/event_list_params.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List +from typing_extensions import Required, Annotated, TypedDict + +from ....._utils import PropertyInfo +from ....anthropic_beta_param import AnthropicBetaParam + +__all__ = ["EventListParams"] + + +class EventListParams(TypedDict, total=False): + session_id: Required[str] + + limit: int + """Query parameter for limit""" + + page: str + """Query parameter for page""" + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skill_create_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skill_create_params.py new file mode 100644 index 0000000000000000000000000000000000000000..d0341f9b88a41966d03031ddde7c6c1460caa30c --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skill_create_params.py @@ -0,0 +1,31 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Annotated, TypedDict + +from ..._types import FileTypes, SequenceNotStr +from ..._utils import PropertyInfo +from ..anthropic_beta_param import AnthropicBetaParam + +__all__ = ["SkillCreateParams"] + + +class SkillCreateParams(TypedDict, total=False): + display_title: Optional[str] + """Display title for the skill. + + This is a human-readable label that is not included in the prompt sent to the + model. + """ + + files: Optional[SequenceNotStr[FileTypes]] + """Files to upload for the skill. + + All files must be in the same top-level directory and must include a SKILL.md + file at the root of that directory. + """ + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skill_list_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skill_list_params.py new file mode 100644 index 0000000000000000000000000000000000000000..df2faed31fa72e6f3f97556d12d3ceb2d15862aa --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skill_list_params.py @@ -0,0 +1,38 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..anthropic_beta_param import AnthropicBetaParam + +__all__ = ["SkillListParams"] + + +class SkillListParams(TypedDict, total=False): + limit: int + """Number of results to return per page. + + Maximum value is 100. Defaults to 20. + """ + + page: Optional[str] + """Pagination token for fetching a specific page of results. + + Pass the value from a previous response's `next_page` field to get the next page + of results. + """ + + source: Optional[str] + """Filter skills by source. + + If provided, only skills from the specified source will be returned: + + - `"custom"`: only return user-created skills + - `"anthropic"`: only return Anthropic-created skills + """ + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skill_list_response.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skill_list_response.py new file mode 100644 index 0000000000000000000000000000000000000000..d4cceab479c35caf811f0a4c0fd7b2372f507fdc --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skill_list_response.py @@ -0,0 +1,49 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ..._models import BaseModel + +__all__ = ["SkillListResponse"] + + +class SkillListResponse(BaseModel): + id: str + """Unique identifier for the skill. + + The format and length of IDs may change over time. + """ + + created_at: str + """ISO 8601 timestamp of when the skill was created.""" + + display_title: Optional[str] = None + """Display title for the skill. + + This is a human-readable label that is not included in the prompt sent to the + model. + """ + + latest_version: Optional[str] = None + """The latest version identifier for the skill. + + This represents the most recent version of the skill that has been created. + """ + + source: str + """Source of the skill. + + This may be one of the following values: + + - `"custom"`: the skill was created by a user + - `"anthropic"`: the skill was created by Anthropic + """ + + type: str + """Object type. + + For Skills, this is always `"skill"`. + """ + + updated_at: str + """ISO 8601 timestamp of when the skill was last updated.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skill_retrieve_response.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skill_retrieve_response.py new file mode 100644 index 0000000000000000000000000000000000000000..b57930172cf86528d84ed104e04a8c396f7135c0 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skill_retrieve_response.py @@ -0,0 +1,49 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ..._models import BaseModel + +__all__ = ["SkillRetrieveResponse"] + + +class SkillRetrieveResponse(BaseModel): + id: str + """Unique identifier for the skill. + + The format and length of IDs may change over time. + """ + + created_at: str + """ISO 8601 timestamp of when the skill was created.""" + + display_title: Optional[str] = None + """Display title for the skill. + + This is a human-readable label that is not included in the prompt sent to the + model. + """ + + latest_version: Optional[str] = None + """The latest version identifier for the skill. + + This represents the most recent version of the skill that has been created. + """ + + source: str + """Source of the skill. + + This may be one of the following values: + + - `"custom"`: the skill was created by a user + - `"anthropic"`: the skill was created by Anthropic + """ + + type: str + """Object type. + + For Skills, this is always `"skill"`. + """ + + updated_at: str + """ISO 8601 timestamp of when the skill was last updated.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skills/__pycache__/__init__.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skills/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4814f05e26b635842b22210393afe156d91a1e8d Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skills/__pycache__/__init__.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skills/__pycache__/version_create_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skills/__pycache__/version_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2edf17f3f075f4d48982920c92cf55c27d667a29 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skills/__pycache__/version_create_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skills/__pycache__/version_create_response.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skills/__pycache__/version_create_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3fa6c9b58ab37428e3f30e98b8b09b5d1751eee2 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skills/__pycache__/version_create_response.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skills/__pycache__/version_delete_response.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skills/__pycache__/version_delete_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2796e6bace94b9759d25ef824ccc6f4b669b2b18 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skills/__pycache__/version_delete_response.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skills/__pycache__/version_list_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skills/__pycache__/version_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0d446802212fb49e75d918aebad9abd42446e6a Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skills/__pycache__/version_list_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skills/__pycache__/version_list_response.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skills/__pycache__/version_list_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f08580671e146e2b195b9bae8c80dd697cb6317 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skills/__pycache__/version_list_response.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skills/__pycache__/version_retrieve_response.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skills/__pycache__/version_retrieve_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6e27d56eb6f0464cb282f7432cd2fa7434da646 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/skills/__pycache__/version_retrieve_response.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/user_profile_list_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/user_profile_list_params.py new file mode 100644 index 0000000000000000000000000000000000000000..0cf2a3df3844c6afa8dd3e99058d14ec3456410a --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/user_profile_list_params.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List +from typing_extensions import Literal, Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..anthropic_beta_param import AnthropicBetaParam + +__all__ = ["UserProfileListParams"] + + +class UserProfileListParams(TypedDict, total=False): + limit: int + """Query parameter for limit""" + + order: Literal["asc", "desc"] + """Query parameter for order""" + + page: str + """Query parameter for page""" + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/user_profile_update_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/user_profile_update_params.py new file mode 100644 index 0000000000000000000000000000000000000000..4487d7b1d29f2fe4f637c39a6b1a823a7bab57f3 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/user_profile_update_params.py @@ -0,0 +1,43 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Optional +from typing_extensions import Literal, Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..anthropic_beta_param import AnthropicBetaParam + +__all__ = ["UserProfileUpdateParams"] + + +class UserProfileUpdateParams(TypedDict, total=False): + external_id: Optional[str] + """If present, replaces the stored external_id. + + Omit to leave unchanged. Maximum 255 characters. + """ + + metadata: Dict[str, str] + """Key-value pairs to merge into the stored metadata. + + Keys provided overwrite existing values. To remove a key, set its value to an + empty string. Keys not provided are left unchanged. Maximum 16 keys, with keys + up to 64 characters and values up to 512 characters. + """ + + name: Optional[str] + """If present, replaces the stored name. + + Omit to leave unchanged. Maximum 255 characters. + """ + + relationship: Optional[Literal["external", "resold", "internal"]] + """ + How the entity behind a user profile relates to the platform that owns the API + key. `external`: an individual end-user of the platform. `resold`: a company the + platform resells Claude access to. `internal`: the platform's own usage. + """ + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vault_create_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vault_create_params.py new file mode 100644 index 0000000000000000000000000000000000000000..80b4dba2d8afa29f42df96a535117fd234eca920 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vault_create_params.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List +from typing_extensions import Required, Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..anthropic_beta_param import AnthropicBetaParam + +__all__ = ["VaultCreateParams"] + + +class VaultCreateParams(TypedDict, total=False): + display_name: Required[str] + """Human-readable name for the vault. 1-255 characters.""" + + metadata: Dict[str, str] + """Arbitrary key-value metadata to attach to the vault. + + Maximum 16 pairs, keys up to 64 chars, values up to 512 chars. + """ + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vault_list_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vault_list_params.py new file mode 100644 index 0000000000000000000000000000000000000000..234a82a8c514224386fae18834f496f35396862b --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vault_list_params.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List +from typing_extensions import Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..anthropic_beta_param import AnthropicBetaParam + +__all__ = ["VaultListParams"] + + +class VaultListParams(TypedDict, total=False): + include_archived: bool + """Whether to include archived vaults in the results.""" + + limit: int + """Maximum number of vaults to return per page. Defaults to 20, maximum 100.""" + + page: str + """Opaque pagination token from a previous `list_vaults` response.""" + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vault_update_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vault_update_params.py new file mode 100644 index 0000000000000000000000000000000000000000..9ec0782d416bfea4cab9a9b8e42b0e98614bc35d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vault_update_params.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Optional +from typing_extensions import Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..anthropic_beta_param import AnthropicBetaParam + +__all__ = ["VaultUpdateParams"] + + +class VaultUpdateParams(TypedDict, total=False): + display_name: Optional[str] + """Updated human-readable name for the vault. 1-255 characters.""" + + metadata: Optional[Dict[str, Optional[str]]] + """Metadata patch. + + Set a key to a string to upsert it, or to null to delete it. Omitted keys are + preserved. + """ + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/__init__.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92ae4d65fc4f1838f101dcb46db32a8dc3c9d72a Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/__init__.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_credential.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_credential.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecf1d987095acf83e2dbb125d2e8570b25e22505 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_credential.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_credential_validation.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_credential_validation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d84a75b11a4f5d29e1aefe025b76cb3181026f55 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_credential_validation.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_credential_validation_status.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_credential_validation_status.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4bae9fffe1adeaeeddd17a80daeb9ac2c5d71bc3 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_credential_validation_status.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_deleted_credential.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_deleted_credential.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24a14e6f34a7f08d87a050961c8dfdb558f13254 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_deleted_credential.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_mcp_oauth_auth_response.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_mcp_oauth_auth_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ae023ebb21914f132b73c2ed2e513caee3b227a Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_mcp_oauth_auth_response.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_mcp_oauth_create_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_mcp_oauth_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bdd6c4c8db832f8d9829f0e02ae97535418457b1 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_mcp_oauth_create_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_mcp_oauth_refresh_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_mcp_oauth_refresh_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97b3c1be6c5cbef4676c00fe77bcc6ecee0640ac Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_mcp_oauth_refresh_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_mcp_oauth_refresh_response.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_mcp_oauth_refresh_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a6ef1d82c0283d4afe09daa155b4e0ea26b07ac Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_mcp_oauth_refresh_response.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_mcp_oauth_refresh_update_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_mcp_oauth_refresh_update_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..160ce6b8d66926d2c273a1bc99e7e5c35cb822c5 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_mcp_oauth_refresh_update_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_mcp_oauth_update_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_mcp_oauth_update_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0726a2b08b5b86ab2bc73708e895929d97e8d042 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_mcp_oauth_update_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_mcp_probe.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_mcp_probe.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7c7738d4378909c29dd7b35d24a87f02c2f621b Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_mcp_probe.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_refresh_http_response.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_refresh_http_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5fd51c51b046dc82c1ad2423c11b63541e0f36c Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_refresh_http_response.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_refresh_object.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_refresh_object.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b2c05a738590bedc9980fb8d712361fac8514cb Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_refresh_object.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_static_bearer_auth_response.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_static_bearer_auth_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9234dcaa78b55d5da00d48571ad6dbd31539969 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_static_bearer_auth_response.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_static_bearer_create_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_static_bearer_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd56657ec1fd14d59a61d334bca20d9cf3cfa14f Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_static_bearer_create_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_static_bearer_update_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_static_bearer_update_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e34ad6132a67ca11cdc4dc6494a07a318e7c321 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_static_bearer_update_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_basic_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_basic_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33a553c90a0e2aed0071537bfb05bddd00aa3aca Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_basic_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_basic_response.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_basic_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d6bcac12682f493d471bae3a1fdfa32cce5d248 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_basic_response.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_basic_update_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_basic_update_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d3474b3226631ea6d951619ece1a253e3a89a34 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_basic_update_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_none_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_none_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..141081884a8fba07889384837cf48de74fb9d801 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_none_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_none_response.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_none_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06fddbce2a1c65aaed2d239d39b7a6963b018a35 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_none_response.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_post_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_post_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..345c8e9a6a2df8e6b594e3ae575128b8a63a4110 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_post_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_post_response.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_post_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4695d8ad7d54f3b8629d07264ca8bdae0d57dbd3 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_post_response.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_post_update_param.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_post_update_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7175eff756a105532520ef3fe29f0134d1e4aba Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/beta_managed_agents_token_endpoint_auth_post_update_param.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/credential_create_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/credential_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1604e73133bebcd203a876eed9ff7365d1d223bf Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/credential_create_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/credential_list_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/credential_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..283a4cfe5cf172a20e68297597db5cb75527277d Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/credential_list_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/credential_update_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/credential_update_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea38c40aaf6b8564173f2a3e412eb399b3819618 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta/vaults/__pycache__/credential_update_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta_authentication_error.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta_authentication_error.py new file mode 100644 index 0000000000000000000000000000000000000000..8a555570475e96ab9f2cf3c550e7d016db747761 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta_authentication_error.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["BetaAuthenticationError"] + + +class BetaAuthenticationError(BaseModel): + message: str + + type: Literal["authentication_error"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta_invalid_request_error.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta_invalid_request_error.py new file mode 100644 index 0000000000000000000000000000000000000000..a84d53cc100b243f595dea76817f5684eb0c174e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta_invalid_request_error.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["BetaInvalidRequestError"] + + +class BetaInvalidRequestError(BaseModel): + message: str + + type: Literal["invalid_request_error"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta_not_found_error.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta_not_found_error.py new file mode 100644 index 0000000000000000000000000000000000000000..3d57cb5a68861af2f342ccb6a90eca9904d454c8 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta_not_found_error.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["BetaNotFoundError"] + + +class BetaNotFoundError(BaseModel): + message: str + + type: Literal["not_found_error"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta_overloaded_error.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta_overloaded_error.py new file mode 100644 index 0000000000000000000000000000000000000000..ff5dbe81454f5e61bfe775cc6281e6fd3e851946 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/beta_overloaded_error.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["BetaOverloadedError"] + + +class BetaOverloadedError(BaseModel): + message: str + + type: Literal["overloaded_error"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/cache_creation.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/cache_creation.py new file mode 100644 index 0000000000000000000000000000000000000000..6f3e127e0dc91ec37d2dfac91b9f66f39315fc68 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/cache_creation.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .._models import BaseModel + +__all__ = ["CacheCreation"] + + +class CacheCreation(BaseModel): + ephemeral_1h_input_tokens: int + """The number of input tokens used to create the 1 hour cache entry.""" + + ephemeral_5m_input_tokens: int + """The number of input tokens used to create the 5 minute cache entry.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/citation_content_block_location_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/citation_content_block_location_param.py new file mode 100644 index 0000000000000000000000000000000000000000..37049382af3a29a96a17210b8cbbb48c544a2f23 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/citation_content_block_location_param.py @@ -0,0 +1,37 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["CitationContentBlockLocationParam"] + + +class CitationContentBlockLocationParam(TypedDict, total=False): + cited_text: Required[str] + """The full text of the cited block range, concatenated. + + Always equals the contents of `content[start_block_index:end_block_index]` + joined together. The text block is the minimal citable unit; this field is never + a substring of a single block. Not counted toward output tokens, and not counted + toward input tokens when sent back in subsequent turns. + """ + + document_index: Required[int] + + document_title: Required[Optional[str]] + + end_block_index: Required[int] + """ + Exclusive 0-based end index of the cited block range in the source's `content` + array. + + Always greater than `start_block_index`; a single-block citation has + `end_block_index = start_block_index + 1`. + """ + + start_block_index: Required[int] + """0-based index of the first cited block in the source's `content` array.""" + + type: Required[Literal["content_block_location"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/citations_web_search_result_location.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/citations_web_search_result_location.py new file mode 100644 index 0000000000000000000000000000000000000000..02a113cafdaf422ecf37c9f24a4f71ba08a7d1f8 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/citations_web_search_result_location.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["CitationsWebSearchResultLocation"] + + +class CitationsWebSearchResultLocation(BaseModel): + cited_text: str + + encrypted_index: str + + title: Optional[str] = None + + type: Literal["web_search_result_location"] + + url: str diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/code_execution_tool_20250825_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/code_execution_tool_20250825_param.py new file mode 100644 index 0000000000000000000000000000000000000000..bd9af5eabd723c1187a5596e0b04aa947c15ff9b --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/code_execution_tool_20250825_param.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal, Required, TypedDict + +from .cache_control_ephemeral_param import CacheControlEphemeralParam + +__all__ = ["CodeExecutionTool20250825Param"] + + +class CodeExecutionTool20250825Param(TypedDict, total=False): + name: Required[Literal["code_execution"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["code_execution_20250825"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + cache_control: Optional[CacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/completion_create_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/completion_create_params.py new file mode 100644 index 0000000000000000000000000000000000000000..9f337e8fd467756623792f944aa3bca604a0a970 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/completion_create_params.py @@ -0,0 +1,133 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union +from typing_extensions import Literal, Required, Annotated, TypeAlias, TypedDict + +from .._types import SequenceNotStr +from .._utils import PropertyInfo +from .model_param import ModelParam +from .metadata_param import MetadataParam +from .anthropic_beta_param import AnthropicBetaParam + +__all__ = [ + "CompletionRequestStreamingMetadata", + "CompletionRequestNonStreamingMetadata", + "CompletionRequestNonStreaming", + "CompletionRequestStreaming", + "CompletionCreateParamsBase", + "Metadata", + "CompletionCreateParamsNonStreaming", + "CompletionCreateParamsStreaming", +] + + +class CompletionCreateParamsBase(TypedDict, total=False): + max_tokens_to_sample: Required[int] + """The maximum number of tokens to generate before stopping. + + Note that our models may stop _before_ reaching this maximum. This parameter + only specifies the absolute maximum number of tokens to generate. + """ + + model: Required[ModelParam] + """ + The model that will complete your prompt.\n\nSee + [models](https://docs.anthropic.com/en/docs/models-overview) for additional + details and options. + """ + + prompt: Required[str] + """The prompt that you want Claude to complete. + + For proper response generation you will need to format your prompt using + alternating `\n\nHuman:` and `\n\nAssistant:` conversational turns. For example: + + ``` + "\n\nHuman: {userQuestion}\n\nAssistant:" + ``` + + See [prompt validation](https://docs.claude.com/en/api/prompt-validation) and + our guide to [prompt design](https://docs.claude.com/en/docs/intro-to-prompting) + for more details. + """ + + metadata: MetadataParam + """An object describing metadata about the request.""" + + stop_sequences: SequenceNotStr[str] + """Sequences that will cause the model to stop generating. + + Our models stop on `"\n\nHuman:"`, and may include additional built-in stop + sequences in the future. By providing the stop_sequences parameter, you may + include additional strings that will cause the model to stop generating. + """ + + temperature: float + """Amount of randomness injected into the response. + + Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0` + for analytical / multiple choice, and closer to `1.0` for creative and + generative tasks. + + Note that even with `temperature` of `0.0`, the results will not be fully + deterministic. + """ + + top_k: int + """Only sample from the top K options for each subsequent token. + + Used to remove "long tail" low probability responses. + [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277). + + Recommended for advanced use cases only. + """ + + top_p: float + """Use nucleus sampling. + + In nucleus sampling, we compute the cumulative distribution over all the options + for each subsequent token in decreasing probability order and cut it off once it + reaches a particular probability specified by `top_p`. + + Recommended for advanced use cases only. + """ + + betas: Annotated[List[AnthropicBetaParam], PropertyInfo(alias="anthropic-beta")] + """Optional header to specify the beta version(s) you want to use.""" + + +Metadata: TypeAlias = MetadataParam +"""This is deprecated, `MetadataParam` should be used instead""" + + +class CompletionCreateParamsNonStreaming(CompletionCreateParamsBase, total=False): + stream: Literal[False] + """Whether to incrementally stream the response using server-sent events. + + See [streaming](https://docs.claude.com/en/api/streaming) for details. + """ + + +class CompletionCreateParamsStreaming(CompletionCreateParamsBase): + stream: Required[Literal[True]] + """Whether to incrementally stream the response using server-sent events. + + See [streaming](https://docs.claude.com/en/api/streaming) for details. + """ + + +CompletionRequestStreamingMetadata = MetadataParam +"""This is deprecated, `MetadataParam` should be used instead""" + +CompletionRequestNonStreamingMetadata = MetadataParam +"""This is deprecated, `MetadataParam` should be used instead""" + +CompletionRequestNonStreaming = CompletionCreateParamsNonStreaming +"""This is deprecated, `CompletionCreateParamsNonStreaming` should be used instead""" + +CompletionRequestStreaming = CompletionCreateParamsStreaming +"""This is deprecated, `CompletionCreateParamsStreaming` should be used instead""" + +CompletionCreateParams = Union[CompletionCreateParamsNonStreaming, CompletionCreateParamsStreaming] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/content_block_source_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/content_block_source_param.py new file mode 100644 index 0000000000000000000000000000000000000000..8050f3e6b7e78a422fd17d3a7d51f91c5589c735 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/content_block_source_param.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import Literal, Required, TypedDict + +from .content_block_source_content_param import ContentBlockSourceContentParam + +__all__ = ["ContentBlockSourceParam"] + + +class ContentBlockSourceParam(TypedDict, total=False): + content: Required[Union[str, Iterable[ContentBlockSourceContentParam]]] + + type: Required[Literal["content"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/content_block_stop_event.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/content_block_stop_event.py new file mode 100644 index 0000000000000000000000000000000000000000..2c67bcccf784ac654375b6776f891e6e23bed740 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/content_block_stop_event.py @@ -0,0 +1,8 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .raw_content_block_stop_event import RawContentBlockStopEvent + +__all__ = ["ContentBlockStopEvent"] + +ContentBlockStopEvent = RawContentBlockStopEvent +"""The RawContentBlockStopEvent type should be used instead""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/direct_caller_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/direct_caller_param.py new file mode 100644 index 0000000000000000000000000000000000000000..15eed6bd7cafdc538d233caa0f80712a92a13484 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/direct_caller_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["DirectCallerParam"] + + +class DirectCallerParam(TypedDict, total=False): + """Tool invocation directly from the model.""" + + type: Required[Literal["direct"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/effort_capability.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/effort_capability.py new file mode 100644 index 0000000000000000000000000000000000000000..26b61ef7f057957b6b67ca6ca5b60dd2da8c7845 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/effort_capability.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from .._models import BaseModel +from .capability_support import CapabilitySupport + +__all__ = ["EffortCapability"] + + +class EffortCapability(BaseModel): + """Effort (reasoning_effort) capability details.""" + + high: CapabilitySupport + """Whether the model supports high effort level.""" + + low: CapabilitySupport + """Whether the model supports low effort level.""" + + max: CapabilitySupport + """Whether the model supports max effort level.""" + + medium: CapabilitySupport + """Whether the model supports medium effort level.""" + + supported: bool + """Whether this capability is supported by the model.""" + + xhigh: Optional[CapabilitySupport] = None + """Indicates whether a capability is supported.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/encrypted_code_execution_result_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/encrypted_code_execution_result_block.py new file mode 100644 index 0000000000000000000000000000000000000000..ebbdf9c80a8ed97b74e02b4f926dcf1e71d6b6e3 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/encrypted_code_execution_result_block.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List +from typing_extensions import Literal + +from .._models import BaseModel +from .code_execution_output_block import CodeExecutionOutputBlock + +__all__ = ["EncryptedCodeExecutionResultBlock"] + + +class EncryptedCodeExecutionResultBlock(BaseModel): + """Code execution result with encrypted stdout for PFC + web_search results.""" + + content: List[CodeExecutionOutputBlock] + + encrypted_stdout: str + + return_code: int + + stderr: str + + type: Literal["encrypted_code_execution_result"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/encrypted_code_execution_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/encrypted_code_execution_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..931e3a343a1497f4fb5b6e39bad1a374b0b4500b --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/encrypted_code_execution_result_block_param.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Literal, Required, TypedDict + +from .code_execution_output_block_param import CodeExecutionOutputBlockParam + +__all__ = ["EncryptedCodeExecutionResultBlockParam"] + + +class EncryptedCodeExecutionResultBlockParam(TypedDict, total=False): + """Code execution result with encrypted stdout for PFC + web_search results.""" + + content: Required[Iterable[CodeExecutionOutputBlockParam]] + + encrypted_stdout: Required[str] + + return_code: Required[int] + + stderr: Required[str] + + type: Required[Literal["encrypted_code_execution_result"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/memory_tool_20250818_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/memory_tool_20250818_param.py new file mode 100644 index 0000000000000000000000000000000000000000..a8e199e05fa7dd51c013b8e385eb032293e6ad50 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/memory_tool_20250818_param.py @@ -0,0 +1,36 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Iterable, Optional +from typing_extensions import Literal, Required, TypedDict + +from .cache_control_ephemeral_param import CacheControlEphemeralParam + +__all__ = ["MemoryTool20250818Param"] + + +class MemoryTool20250818Param(TypedDict, total=False): + name: Required[Literal["memory"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["memory_20250818"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + cache_control: Optional[CacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + input_examples: Iterable[Dict[str, object]] + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/message_count_tokens_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/message_count_tokens_params.py new file mode 100644 index 0000000000000000000000000000000000000000..a056a5b5fdec972d7b81d7727c6e18cb0cc02df0 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/message_count_tokens_params.py @@ -0,0 +1,208 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable, Optional +from typing_extensions import Required, TypedDict + +from .model_param import ModelParam +from .message_param import MessageParam +from .text_block_param import TextBlockParam +from .tool_choice_param import ToolChoiceParam +from .output_config_param import OutputConfigParam +from .thinking_config_param import ThinkingConfigParam +from .cache_control_ephemeral_param import CacheControlEphemeralParam +from .message_count_tokens_tool_param import MessageCountTokensToolParam + +__all__ = ["MessageCountTokensParams"] + + +class MessageCountTokensParams(TypedDict, total=False): + messages: Required[Iterable[MessageParam]] + """Input messages. + + Our models are trained to operate on alternating `user` and `assistant` + conversational turns. When creating a new `Message`, you specify the prior + conversational turns with the `messages` parameter, and the model then generates + the next `Message` in the conversation. Consecutive `user` or `assistant` turns + in your request will be combined into a single turn. + + Each input message must be an object with a `role` and `content`. You can + specify a single `user`-role message, or you can include multiple `user` and + `assistant` messages. + + If the final message uses the `assistant` role, the response content will + continue immediately from the content in that message. This can be used to + constrain part of the model's response. + + Example with a single `user` message: + + ```json + [{ "role": "user", "content": "Hello, Claude" }] + ``` + + Example with multiple conversational turns: + + ```json + [ + { "role": "user", "content": "Hello there." }, + { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" }, + { "role": "user", "content": "Can you explain LLMs in plain English?" } + ] + ``` + + Example with a partially-filled response from Claude: + + ```json + [ + { + "role": "user", + "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" + }, + { "role": "assistant", "content": "The best answer is (" } + ] + ``` + + Each input message `content` may be either a single `string` or an array of + content blocks, where each block has a specific `type`. Using a `string` for + `content` is shorthand for an array of one content block of type `"text"`. The + following input messages are equivalent: + + ```json + { "role": "user", "content": "Hello, Claude" } + ``` + + ```json + { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] } + ``` + + See [input examples](https://docs.claude.com/en/api/messages-examples). + + Note that if you want to include a + [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the + top-level `system` parameter — there is no `"system"` role for input messages in + the Messages API. + + There is a limit of 100,000 messages in a single request. + """ + + model: Required[ModelParam] + """ + The model that will complete your prompt.\n\nSee + [models](https://docs.anthropic.com/en/docs/models-overview) for additional + details and options. + """ + + cache_control: Optional[CacheControlEphemeralParam] + """ + Top-level cache control automatically applies a cache_control marker to the last + cacheable block in the request. + """ + + output_config: OutputConfigParam + """Configuration options for the model's output, such as the output format.""" + + system: Union[str, Iterable[TextBlockParam]] + """System prompt. + + A system prompt is a way of providing context and instructions to Claude, such + as specifying a particular goal or role. See our + [guide to system prompts](https://docs.claude.com/en/docs/system-prompts). + """ + + thinking: ThinkingConfigParam + """Configuration for enabling Claude's extended thinking. + + When enabled, responses include `thinking` content blocks showing Claude's + thinking process before the final answer. Requires a minimum budget of 1,024 + tokens and counts towards your `max_tokens` limit. + + See + [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) + for details. + """ + + tool_choice: ToolChoiceParam + """How the model should use the provided tools. + + The model can use a specific tool, any available tool, decide by itself, or not + use tools at all. + """ + + tools: Iterable[MessageCountTokensToolParam] + """Definitions of tools that the model may use. + + If you include `tools` in your API request, the model may return `tool_use` + content blocks that represent the model's use of those tools. You can then run + those tools using the tool input generated by the model and then optionally + return results back to the model using `tool_result` content blocks. + + There are two types of tools: **client tools** and **server tools**. The + behavior described below applies to client tools. For + [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools), + see their individual documentation as each has its own behavior (e.g., the + [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)). + + Each tool definition includes: + + - `name`: Name of the tool. + - `description`: Optional, but strongly-recommended description of the tool. + - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the + tool `input` shape that the model will produce in `tool_use` output content + blocks. + + For example, if you defined `tools` as: + + ```json + [ + { + "name": "get_stock_price", + "description": "Get the current stock price for a given ticker symbol.", + "input_schema": { + "type": "object", + "properties": { + "ticker": { + "type": "string", + "description": "The stock ticker symbol, e.g. AAPL for Apple Inc." + } + }, + "required": ["ticker"] + } + } + ] + ``` + + And then asked the model "What's the S&P 500 at today?", the model might produce + `tool_use` content blocks in the response like this: + + ```json + [ + { + "type": "tool_use", + "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", + "name": "get_stock_price", + "input": { "ticker": "^GSPC" } + } + ] + ``` + + You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an + input, and return the following back to the model in a subsequent `user` + message: + + ```json + [ + { + "type": "tool_result", + "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", + "content": "259.75 USD" + } + ] + ``` + + Tools can be used for workflows that include running client-side tools and + functions, or more generally whenever you want the model to produce a particular + JSON structure of output. + + See our [guide](https://docs.claude.com/en/docs/tool-use) for more details. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/message_count_tokens_tool_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/message_count_tokens_tool_param.py new file mode 100644 index 0000000000000000000000000000000000000000..09cf99ca4e751f478502b01668b6b963e31ae810 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/message_count_tokens_tool_param.py @@ -0,0 +1,44 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .tool_param import ToolParam +from .tool_bash_20250124_param import ToolBash20250124Param +from .memory_tool_20250818_param import MemoryTool20250818Param +from .web_fetch_tool_20250910_param import WebFetchTool20250910Param +from .web_fetch_tool_20260209_param import WebFetchTool20260209Param +from .web_fetch_tool_20260309_param import WebFetchTool20260309Param +from .web_search_tool_20250305_param import WebSearchTool20250305Param +from .web_search_tool_20260209_param import WebSearchTool20260209Param +from .tool_text_editor_20250124_param import ToolTextEditor20250124Param +from .tool_text_editor_20250429_param import ToolTextEditor20250429Param +from .tool_text_editor_20250728_param import ToolTextEditor20250728Param +from .code_execution_tool_20250522_param import CodeExecutionTool20250522Param +from .code_execution_tool_20250825_param import CodeExecutionTool20250825Param +from .code_execution_tool_20260120_param import CodeExecutionTool20260120Param +from .tool_search_tool_bm25_20251119_param import ToolSearchToolBm25_20251119Param +from .tool_search_tool_regex_20251119_param import ToolSearchToolRegex20251119Param + +__all__ = ["MessageCountTokensToolParam"] + +MessageCountTokensToolParam: TypeAlias = Union[ + ToolParam, + ToolBash20250124Param, + CodeExecutionTool20250522Param, + CodeExecutionTool20250825Param, + CodeExecutionTool20260120Param, + MemoryTool20250818Param, + ToolTextEditor20250124Param, + ToolTextEditor20250429Param, + ToolTextEditor20250728Param, + WebSearchTool20250305Param, + WebFetchTool20250910Param, + WebSearchTool20260209Param, + WebFetchTool20260209Param, + WebFetchTool20260309Param, + ToolSearchToolBm25_20251119Param, + ToolSearchToolRegex20251119Param, +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/message_delta_usage.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/message_delta_usage.py new file mode 100644 index 0000000000000000000000000000000000000000..11bd49d7ff47fcf38a80ff13a8b28aeb3d9a71b3 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/message_delta_usage.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from .._models import BaseModel +from .server_tool_usage import ServerToolUsage + +__all__ = ["MessageDeltaUsage"] + + +class MessageDeltaUsage(BaseModel): + cache_creation_input_tokens: Optional[int] = None + """The cumulative number of input tokens used to create the cache entry.""" + + cache_read_input_tokens: Optional[int] = None + """The cumulative number of input tokens read from the cache.""" + + input_tokens: Optional[int] = None + """The cumulative number of input tokens which were used.""" + + output_tokens: int + """The cumulative number of output tokens which were used.""" + + server_tool_use: Optional[ServerToolUsage] = None + """The number of server tool requests.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/message_stop_event.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/message_stop_event.py new file mode 100644 index 0000000000000000000000000000000000000000..30564cbedcf752742e88ef81521fa0a5514e9822 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/message_stop_event.py @@ -0,0 +1,8 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .raw_message_stop_event import RawMessageStopEvent + +__all__ = ["MessageStopEvent"] + +MessageStopEvent = RawMessageStopEvent +"""The RawMessageStopEvent type should be used instead""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__init__.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..25d311da471bbef5761a50f5c11dbb43153982b6 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__init__.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .message_batch import MessageBatch as MessageBatch +from .batch_list_params import BatchListParams as BatchListParams +from .batch_create_params import BatchCreateParams as BatchCreateParams +from .message_batch_result import MessageBatchResult as MessageBatchResult +from .deleted_message_batch import DeletedMessageBatch as DeletedMessageBatch +from .message_batch_errored_result import MessageBatchErroredResult as MessageBatchErroredResult +from .message_batch_expired_result import MessageBatchExpiredResult as MessageBatchExpiredResult +from .message_batch_request_counts import MessageBatchRequestCounts as MessageBatchRequestCounts +from .message_batch_canceled_result import MessageBatchCanceledResult as MessageBatchCanceledResult +from .message_batch_succeeded_result import MessageBatchSucceededResult as MessageBatchSucceededResult +from .message_batch_individual_response import MessageBatchIndividualResponse as MessageBatchIndividualResponse diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/__init__.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14ee5eecf2255a4d2179758bf09082c17e21b3cf Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/__init__.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/batch_create_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/batch_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e5bfd7bc249849e152c69d1c073f566373677f3 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/batch_create_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/batch_list_params.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/batch_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c3131cf5fcf76a89fcea5f4d0ed39118ef85af5 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/batch_list_params.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/deleted_message_batch.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/deleted_message_batch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec2954b8a9e9510f4857c1412657ac2f4c3c8153 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/deleted_message_batch.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9911f45437259c1c95dc5e9beb7ba1226a498a48 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch_canceled_result.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch_canceled_result.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc38d96afa2c7693c8452c9ca875c03d2621d554 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch_canceled_result.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch_errored_result.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch_errored_result.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58d020d816ec4fc0430ff33d0ee6cc28af3acaee Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch_errored_result.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch_expired_result.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch_expired_result.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43b5d61f85a767f0c205c824c9822b1d203a639b Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch_expired_result.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch_individual_response.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch_individual_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7896b2acc8d5c1bef27b547a3f789fbcdb6b735 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch_individual_response.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch_request_counts.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch_request_counts.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9b2c2168bfc38811e71ac6e6c1740efda77326b Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch_request_counts.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch_result.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch_result.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee111eb429dc1c30ff30638e4e9edf4abd2c25c7 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch_result.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch_succeeded_result.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch_succeeded_result.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3d2d036bc2a825813ca6ad600b88ab114116698 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/__pycache__/message_batch_succeeded_result.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/batch_create_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/batch_create_params.py new file mode 100644 index 0000000000000000000000000000000000000000..880136e21d7a558a1d8b0d0fa6b8669433a8b96d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/batch_create_params.py @@ -0,0 +1,37 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Required, TypedDict + +from ..message_create_params import MessageCreateParamsNonStreaming + +__all__ = ["BatchCreateParams", "Request"] + + +class BatchCreateParams(TypedDict, total=False): + requests: Required[Iterable[Request]] + """List of requests for prompt completion. + + Each is an individual request to create a Message. + """ + + + +class Request(TypedDict, total=False): + custom_id: Required[str] + """Developer-provided ID created for each request in a Message Batch. + + Useful for matching results to requests, as results may be given out of request + order. + + Must be unique for each request within the Message Batch. + """ + + params: Required[MessageCreateParamsNonStreaming] + """Messages API creation parameters for the individual request. + + See the [Messages API reference](https://docs.claude.com/en/api/messages) for + full documentation on available parameters. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/batch_list_params.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/batch_list_params.py new file mode 100644 index 0000000000000000000000000000000000000000..7b290a774dc4bacc980d21fb6284274bc784ebdc --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/batch_list_params.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["BatchListParams"] + + +class BatchListParams(TypedDict, total=False): + after_id: str + """ID of the object to use as a cursor for pagination. + + When provided, returns the page of results immediately after this object. + """ + + before_id: str + """ID of the object to use as a cursor for pagination. + + When provided, returns the page of results immediately before this object. + """ + + limit: int + """Number of items to return per page. + + Defaults to `20`. Ranges from `1` to `1000`. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/deleted_message_batch.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/deleted_message_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..7a6c321e7b5fe3b5c8abeabf49467d85dd1b2657 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/deleted_message_batch.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["DeletedMessageBatch"] + + +class DeletedMessageBatch(BaseModel): + id: str + """ID of the Message Batch.""" + + type: Literal["message_batch_deleted"] + """Deleted object type. + + For Message Batches, this is always `"message_batch_deleted"`. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..a03e73e1b01c292b8bda0ff5d05424965831ddf6 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch.py @@ -0,0 +1,77 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from datetime import datetime +from typing_extensions import Literal + +from ..._models import BaseModel +from .message_batch_request_counts import MessageBatchRequestCounts + +__all__ = ["MessageBatch"] + + +class MessageBatch(BaseModel): + id: str + """Unique object identifier. + + The format and length of IDs may change over time. + """ + + archived_at: Optional[datetime] = None + """ + RFC 3339 datetime string representing the time at which the Message Batch was + archived and its results became unavailable. + """ + + cancel_initiated_at: Optional[datetime] = None + """ + RFC 3339 datetime string representing the time at which cancellation was + initiated for the Message Batch. Specified only if cancellation was initiated. + """ + + created_at: datetime + """ + RFC 3339 datetime string representing the time at which the Message Batch was + created. + """ + + ended_at: Optional[datetime] = None + """ + RFC 3339 datetime string representing the time at which processing for the + Message Batch ended. Specified only once processing ends. + + Processing ends when every request in a Message Batch has either succeeded, + errored, canceled, or expired. + """ + + expires_at: datetime + """ + RFC 3339 datetime string representing the time at which the Message Batch will + expire and end processing, which is 24 hours after creation. + """ + + processing_status: Literal["in_progress", "canceling", "ended"] + """Processing status of the Message Batch.""" + + request_counts: MessageBatchRequestCounts + """Tallies requests within the Message Batch, categorized by their status. + + Requests start as `processing` and move to one of the other statuses only once + processing of the entire batch ends. The sum of all values always matches the + total number of requests in the batch. + """ + + results_url: Optional[str] = None + """URL to a `.jsonl` file containing the results of the Message Batch requests. + + Specified only once processing ends. + + Results in the file are not guaranteed to be in the same order as requests. Use + the `custom_id` field to match results to requests. + """ + + type: Literal["message_batch"] + """Object type. + + For Message Batches, this is always `"message_batch"`. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch_canceled_result.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch_canceled_result.py new file mode 100644 index 0000000000000000000000000000000000000000..9826aa9117b6f9f309b69513d4747814ff08816b --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch_canceled_result.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["MessageBatchCanceledResult"] + + +class MessageBatchCanceledResult(BaseModel): + type: Literal["canceled"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch_errored_result.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch_errored_result.py new file mode 100644 index 0000000000000000000000000000000000000000..5f890bfd6e0957f838cd0558fcc8db88afe644e1 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch_errored_result.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel +from ..shared.error_response import ErrorResponse + +__all__ = ["MessageBatchErroredResult"] + + +class MessageBatchErroredResult(BaseModel): + error: ErrorResponse + + type: Literal["errored"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch_expired_result.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch_expired_result.py new file mode 100644 index 0000000000000000000000000000000000000000..ab9964e7669b05353233956a53abfeb1aee7949e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch_expired_result.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["MessageBatchExpiredResult"] + + +class MessageBatchExpiredResult(BaseModel): + type: Literal["expired"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch_individual_response.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch_individual_response.py new file mode 100644 index 0000000000000000000000000000000000000000..2bb5c5f33a82a5bb8b46c542fc18a221f70edafd --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch_individual_response.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel +from .message_batch_result import MessageBatchResult + +__all__ = ["MessageBatchIndividualResponse"] + + +class MessageBatchIndividualResponse(BaseModel): + """ + This is a single line in the response `.jsonl` file and does not represent the response as a whole. + """ + + custom_id: str + """Developer-provided ID created for each request in a Message Batch. + + Useful for matching results to requests, as results may be given out of request + order. + + Must be unique for each request within the Message Batch. + """ + + result: MessageBatchResult + """Processing result for this request. + + Contains a Message output if processing was successful, an error response if + processing failed, or the reason why processing was not attempted, such as + cancellation or expiration. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch_request_counts.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch_request_counts.py new file mode 100644 index 0000000000000000000000000000000000000000..041f3b3802cc4fdefadca842eb23eddb5353527b --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch_request_counts.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["MessageBatchRequestCounts"] + + +class MessageBatchRequestCounts(BaseModel): + canceled: int + """Number of requests in the Message Batch that have been canceled. + + This is zero until processing of the entire Message Batch has ended. + """ + + errored: int + """Number of requests in the Message Batch that encountered an error. + + This is zero until processing of the entire Message Batch has ended. + """ + + expired: int + """Number of requests in the Message Batch that have expired. + + This is zero until processing of the entire Message Batch has ended. + """ + + processing: int + """Number of requests in the Message Batch that are processing.""" + + succeeded: int + """Number of requests in the Message Batch that have completed successfully. + + This is zero until processing of the entire Message Batch has ended. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch_result.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch_result.py new file mode 100644 index 0000000000000000000000000000000000000000..3186f2aa4ac6997a837cc99bf65283ed6d0e1c26 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch_result.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from ..._utils import PropertyInfo +from .message_batch_errored_result import MessageBatchErroredResult +from .message_batch_expired_result import MessageBatchExpiredResult +from .message_batch_canceled_result import MessageBatchCanceledResult +from .message_batch_succeeded_result import MessageBatchSucceededResult + +__all__ = ["MessageBatchResult"] + +MessageBatchResult: TypeAlias = Annotated[ + Union[ + MessageBatchSucceededResult, MessageBatchErroredResult, MessageBatchCanceledResult, MessageBatchExpiredResult + ], + PropertyInfo(discriminator="type"), +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch_succeeded_result.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch_succeeded_result.py new file mode 100644 index 0000000000000000000000000000000000000000..1cc454a4512c3ea86a1b6b29565d89f2c157a0ee --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/messages/message_batch_succeeded_result.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..message import Message +from ..._models import BaseModel + +__all__ = ["MessageBatchSucceededResult"] + + +class MessageBatchSucceededResult(BaseModel): + message: Message + + type: Literal["succeeded"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/model_capabilities.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/model_capabilities.py new file mode 100644 index 0000000000000000000000000000000000000000..c7d69b6132131956888cfef870b4b5177a36913e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/model_capabilities.py @@ -0,0 +1,40 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .._models import BaseModel +from .effort_capability import EffortCapability +from .capability_support import CapabilitySupport +from .thinking_capability import ThinkingCapability +from .context_management_capability import ContextManagementCapability + +__all__ = ["ModelCapabilities"] + + +class ModelCapabilities(BaseModel): + """Model capability information.""" + + batch: CapabilitySupport + """Whether the model supports the Batch API.""" + + citations: CapabilitySupport + """Whether the model supports citation generation.""" + + code_execution: CapabilitySupport + """Whether the model supports code execution tools.""" + + context_management: ContextManagementCapability + """Context management support and available strategies.""" + + effort: EffortCapability + """Effort (reasoning_effort) support and available levels.""" + + image_input: CapabilitySupport + """Whether the model accepts image content blocks.""" + + pdf_input: CapabilitySupport + """Whether the model accepts PDF content blocks.""" + + structured_outputs: CapabilitySupport + """Whether the model supports structured output / JSON mode / strict tool schemas.""" + + thinking: ThinkingCapability + """Thinking capability and supported type configurations.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/plain_text_source_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/plain_text_source_param.py new file mode 100644 index 0000000000000000000000000000000000000000..a2a3b8de30a55aa8913dff307a53b73dd5860aaf --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/plain_text_source_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["PlainTextSourceParam"] + + +class PlainTextSourceParam(TypedDict, total=False): + data: Required[str] + + media_type: Required[Literal["text/plain"]] + + type: Required[Literal["text"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/raw_message_delta_event.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/raw_message_delta_event.py new file mode 100644 index 0000000000000000000000000000000000000000..c7915b600c902d2bd529e94d9008afacc3f8fba0 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/raw_message_delta_event.py @@ -0,0 +1,51 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .container import Container +from .stop_reason import StopReason +from .message_delta_usage import MessageDeltaUsage +from .refusal_stop_details import RefusalStopDetails + +__all__ = ["RawMessageDeltaEvent", "Delta"] + + +class Delta(BaseModel): + container: Optional[Container] = None + """ + Information about the container used in the request (for the code execution + tool) + """ + + stop_details: Optional[RefusalStopDetails] = None + """Structured information about a refusal.""" + + stop_reason: Optional[StopReason] = None + + stop_sequence: Optional[str] = None + + +class RawMessageDeltaEvent(BaseModel): + delta: Delta + + type: Literal["message_delta"] + + usage: MessageDeltaUsage + """Billing and rate-limit usage. + + Anthropic's API bills and rate-limits by token counts, as tokens represent the + underlying cost to our systems. + + Under the hood, the API transforms requests into a format suitable for the + model. The model's output then goes through a parsing stage before becoming an + API response. As a result, the token counts in `usage` will not match one-to-one + with the exact visible content of an API request or response. + + For example, `output_tokens` will be non-zero, even for an empty string response + from Claude. + + Total input tokens in a request is the summation of `input_tokens`, + `cache_creation_input_tokens`, and `cache_read_input_tokens`. + """ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/raw_message_start_event.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/raw_message_start_event.py new file mode 100644 index 0000000000000000000000000000000000000000..1b9e89040bb0c9174cda95962be1448291858c0e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/raw_message_start_event.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .message import Message +from .._models import BaseModel + +__all__ = ["RawMessageStartEvent"] + + +class RawMessageStartEvent(BaseModel): + message: Message + + type: Literal["message_start"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/raw_message_stop_event.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/raw_message_stop_event.py new file mode 100644 index 0000000000000000000000000000000000000000..d40ccfe2c04c9a6570cf41bd1c17aca1a65a2583 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/raw_message_stop_event.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["RawMessageStopEvent"] + + +class RawMessageStopEvent(BaseModel): + type: Literal["message_stop"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/redacted_thinking_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/redacted_thinking_block.py new file mode 100644 index 0000000000000000000000000000000000000000..4850b335a05ec751cee22a713da1548336f4ff46 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/redacted_thinking_block.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["RedactedThinkingBlock"] + + +class RedactedThinkingBlock(BaseModel): + data: str + + type: Literal["redacted_thinking"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/search_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/search_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..706e6c0a57498e7e4e14740d02671252c5ce7b54 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/search_result_block_param.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable, Optional +from typing_extensions import Literal, Required, TypedDict + +from .text_block_param import TextBlockParam +from .citations_config_param import CitationsConfigParam +from .cache_control_ephemeral_param import CacheControlEphemeralParam + +__all__ = ["SearchResultBlockParam"] + + +class SearchResultBlockParam(TypedDict, total=False): + content: Required[Iterable[TextBlockParam]] + + source: Required[str] + + title: Required[str] + + type: Required[Literal["search_result"]] + + cache_control: Optional[CacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + citations: CitationsConfigParam diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/server_tool_caller_20260120_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/server_tool_caller_20260120_param.py new file mode 100644 index 0000000000000000000000000000000000000000..26a2d79aa1c95263307e12b1994249043fc03f93 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/server_tool_caller_20260120_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ServerToolCaller20260120Param"] + + +class ServerToolCaller20260120Param(TypedDict, total=False): + tool_id: Required[str] + + type: Required[Literal["code_execution_20260120"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/server_tool_caller_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/server_tool_caller_param.py new file mode 100644 index 0000000000000000000000000000000000000000..cea02648ee8e3479e6e23c7b4c2c093405913dc3 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/server_tool_caller_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ServerToolCallerParam"] + + +class ServerToolCallerParam(TypedDict, total=False): + """Tool invocation generated by a server-side tool.""" + + tool_id: Required[str] + + type: Required[Literal["code_execution_20250825"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/server_tool_usage.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/server_tool_usage.py new file mode 100644 index 0000000000000000000000000000000000000000..7381c4aa52f42633f341fbaf171b03815fcc1eae --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/server_tool_usage.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .._models import BaseModel + +__all__ = ["ServerToolUsage"] + + +class ServerToolUsage(BaseModel): + web_fetch_requests: int + """The number of web fetch tool requests.""" + + web_search_requests: int + """The number of web search tool requests.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__init__.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d519bae59535f8093f3586fea43017adeaf4164c --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__init__.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .error_type import ErrorType as ErrorType +from .error_object import ErrorObject as ErrorObject +from .billing_error import BillingError as BillingError +from .error_response import ErrorResponse as ErrorResponse +from .not_found_error import NotFoundError as NotFoundError +from .api_error_object import APIErrorObject as APIErrorObject +from .overloaded_error import OverloadedError as OverloadedError +from .permission_error import PermissionError as PermissionError +from .rate_limit_error import RateLimitError as RateLimitError +from .authentication_error import AuthenticationError as AuthenticationError +from .gateway_timeout_error import GatewayTimeoutError as GatewayTimeoutError +from .invalid_request_error import InvalidRequestError as InvalidRequestError diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/__init__.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1eb968ab880d22a21cd9d79660ae40b9c2e65dc Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/__init__.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/api_error_object.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/api_error_object.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00cde76624e464cf291110203363cb74853e75d1 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/api_error_object.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/authentication_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/authentication_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24d7299f6235b62294a7aea2774f93c8addbb055 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/authentication_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/billing_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/billing_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e41380761697d014cba3a76328d396394fbf473 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/billing_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/error_object.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/error_object.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fa8afdee096ffb883bd1ece23268a5f8f35ab51 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/error_object.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/error_response.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/error_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb149ef2c425c614393a7dc344724e41cb98ea58 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/error_response.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/error_type.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/error_type.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4482835cda25a236b46a51e0bcdbc98b79a388d1 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/error_type.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/gateway_timeout_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/gateway_timeout_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53af772f2ec0fe0289885871755e09f2dde32d6d Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/gateway_timeout_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/invalid_request_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/invalid_request_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44e437909d714276ca00bc675a88a0cf67cac664 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/invalid_request_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/not_found_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/not_found_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d18a5c14741540ecc6ba58e0b3cb253c09e188f Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/not_found_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/overloaded_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/overloaded_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..433e4ad49ff2134f433b1797b91830f80e06fe77 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/overloaded_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/permission_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/permission_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cadadd67a04f216aee41e885ec2eeb4f41db4a1 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/permission_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/rate_limit_error.cpython-312.pyc b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/rate_limit_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d923e8f6e77d337d64b6279ef4ff401023afa74 Binary files /dev/null and b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/__pycache__/rate_limit_error.cpython-312.pyc differ diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/api_error_object.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/api_error_object.py new file mode 100644 index 0000000000000000000000000000000000000000..dd92bead2820f6ccbf71290c4d1c70fc96e4c512 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/api_error_object.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["APIErrorObject"] + + +class APIErrorObject(BaseModel): + message: str + + type: Literal["api_error"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/authentication_error.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/authentication_error.py new file mode 100644 index 0000000000000000000000000000000000000000..f777f5c8eac2389ee37c7d515bf8dd439643dafe --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/authentication_error.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["AuthenticationError"] + + +class AuthenticationError(BaseModel): + message: str + + type: Literal["authentication_error"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/billing_error.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/billing_error.py new file mode 100644 index 0000000000000000000000000000000000000000..26be12bb70f007d6413720fc0ab6402efd21e6e1 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/billing_error.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["BillingError"] + + +class BillingError(BaseModel): + message: str + + type: Literal["billing_error"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/error_object.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/error_object.py new file mode 100644 index 0000000000000000000000000000000000000000..086db50369c9a5752c67cf677ea60dc717962d78 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/error_object.py @@ -0,0 +1,32 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from ..._utils import PropertyInfo +from .billing_error import BillingError +from .not_found_error import NotFoundError +from .api_error_object import APIErrorObject +from .overloaded_error import OverloadedError +from .permission_error import PermissionError +from .rate_limit_error import RateLimitError +from .authentication_error import AuthenticationError +from .gateway_timeout_error import GatewayTimeoutError +from .invalid_request_error import InvalidRequestError + +__all__ = ["ErrorObject"] + +ErrorObject: TypeAlias = Annotated[ + Union[ + InvalidRequestError, + AuthenticationError, + BillingError, + PermissionError, + NotFoundError, + RateLimitError, + GatewayTimeoutError, + APIErrorObject, + OverloadedError, + ], + PropertyInfo(discriminator="type"), +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/error_response.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/error_response.py new file mode 100644 index 0000000000000000000000000000000000000000..cc44ade282e01f11b055288d6d3499d5132f2445 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/error_response.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel +from .error_object import ErrorObject + +__all__ = ["ErrorResponse"] + + +class ErrorResponse(BaseModel): + error: ErrorObject + + request_id: Optional[str] = None + + type: Literal["error"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/error_type.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/error_type.py new file mode 100644 index 0000000000000000000000000000000000000000..f452d75b45d8e1bbe04d89109a20e84873c590a8 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/error_type.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["ErrorType"] + +ErrorType: TypeAlias = Literal[ + "invalid_request_error", + "authentication_error", + "permission_error", + "not_found_error", + "rate_limit_error", + "timeout_error", + "overloaded_error", + "api_error", + "billing_error", +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/gateway_timeout_error.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/gateway_timeout_error.py new file mode 100644 index 0000000000000000000000000000000000000000..908aa12f264179325598f6342d9d9736b5bd1489 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/gateway_timeout_error.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["GatewayTimeoutError"] + + +class GatewayTimeoutError(BaseModel): + message: str + + type: Literal["timeout_error"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/invalid_request_error.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/invalid_request_error.py new file mode 100644 index 0000000000000000000000000000000000000000..ee5befc06d537e1f9c297f3e742a0392bdb47a69 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/invalid_request_error.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["InvalidRequestError"] + + +class InvalidRequestError(BaseModel): + message: str + + type: Literal["invalid_request_error"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/not_found_error.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/not_found_error.py new file mode 100644 index 0000000000000000000000000000000000000000..43e826fbba602325f658b746019f86bbc7fe05be --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/not_found_error.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["NotFoundError"] + + +class NotFoundError(BaseModel): + message: str + + type: Literal["not_found_error"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/overloaded_error.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/overloaded_error.py new file mode 100644 index 0000000000000000000000000000000000000000..74ee83738f203d551d3afe8ec286d881bcdd620b --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/overloaded_error.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["OverloadedError"] + + +class OverloadedError(BaseModel): + message: str + + type: Literal["overloaded_error"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/permission_error.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/permission_error.py new file mode 100644 index 0000000000000000000000000000000000000000..48eb3546bebabf4a4ab62959e1787943ccc108d6 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/permission_error.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["PermissionError"] + + +class PermissionError(BaseModel): + message: str + + type: Literal["permission_error"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/rate_limit_error.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/rate_limit_error.py new file mode 100644 index 0000000000000000000000000000000000000000..3fa065acf28ecb2f02155a066cb10f9d283ae6e8 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/shared/rate_limit_error.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["RateLimitError"] + + +class RateLimitError(BaseModel): + message: str + + type: Literal["rate_limit_error"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/text_citation.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/text_citation.py new file mode 100644 index 0000000000000000000000000000000000000000..a5a7ad535dd134cb38036512d3c65745264143b0 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/text_citation.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from .._utils import PropertyInfo +from .citation_char_location import CitationCharLocation +from .citation_page_location import CitationPageLocation +from .citation_content_block_location import CitationContentBlockLocation +from .citations_search_result_location import CitationsSearchResultLocation +from .citations_web_search_result_location import CitationsWebSearchResultLocation + +__all__ = ["TextCitation"] + +TextCitation: TypeAlias = Annotated[ + Union[ + CitationCharLocation, + CitationPageLocation, + CitationContentBlockLocation, + CitationsWebSearchResultLocation, + CitationsSearchResultLocation, + ], + PropertyInfo(discriminator="type"), +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/text_editor_code_execution_tool_result_error.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/text_editor_code_execution_tool_result_error.py new file mode 100644 index 0000000000000000000000000000000000000000..d4f23c8dc0989f8e8f47940bee1d6257e431f039 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/text_editor_code_execution_tool_result_error.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .text_editor_code_execution_tool_result_error_code import TextEditorCodeExecutionToolResultErrorCode + +__all__ = ["TextEditorCodeExecutionToolResultError"] + + +class TextEditorCodeExecutionToolResultError(BaseModel): + error_code: TextEditorCodeExecutionToolResultErrorCode + + error_message: Optional[str] = None + + type: Literal["text_editor_code_execution_tool_result_error"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/text_editor_code_execution_tool_result_error_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/text_editor_code_execution_tool_result_error_param.py new file mode 100644 index 0000000000000000000000000000000000000000..fd1c2abab40f4c78f0b76629d7781b5e0537da94 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/text_editor_code_execution_tool_result_error_param.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +from .text_editor_code_execution_tool_result_error_code import TextEditorCodeExecutionToolResultErrorCode + +__all__ = ["TextEditorCodeExecutionToolResultErrorParam"] + + +class TextEditorCodeExecutionToolResultErrorParam(TypedDict, total=False): + error_code: Required[TextEditorCodeExecutionToolResultErrorCode] + + type: Required[Literal["text_editor_code_execution_tool_result_error"]] + + error_message: Optional[str] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/thinking_types.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/thinking_types.py new file mode 100644 index 0000000000000000000000000000000000000000..e0b9e5f9484ad20cca905649fd6eeca8f91a154d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/thinking_types.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .._models import BaseModel +from .capability_support import CapabilitySupport + +__all__ = ["ThinkingTypes"] + + +class ThinkingTypes(BaseModel): + """Supported thinking type configurations.""" + + adaptive: CapabilitySupport + """Whether the model supports thinking with type 'adaptive' (auto).""" + + enabled: CapabilitySupport + """Whether the model supports thinking with type 'enabled'.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/tool_choice_none_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/tool_choice_none_param.py new file mode 100644 index 0000000000000000000000000000000000000000..e185cc22cf253159ae5f40a708981c720bebcfdb --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/tool_choice_none_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ToolChoiceNoneParam"] + + +class ToolChoiceNoneParam(TypedDict, total=False): + """The model will not be allowed to use tools.""" + + type: Required[Literal["none"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/tool_reference_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/tool_reference_block.py new file mode 100644 index 0000000000000000000000000000000000000000..e58375895df1eb7ab9b296d3f78f49dabc7fc8f5 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/tool_reference_block.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["ToolReferenceBlock"] + + +class ToolReferenceBlock(BaseModel): + tool_name: str + + type: Literal["tool_reference"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/tool_search_tool_search_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/tool_search_tool_search_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..ed248234699b1275d11f83c049b26ef95c12e97c --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/tool_search_tool_search_result_block_param.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Literal, Required, TypedDict + +from .tool_reference_block_param import ToolReferenceBlockParam + +__all__ = ["ToolSearchToolSearchResultBlockParam"] + + +class ToolSearchToolSearchResultBlockParam(TypedDict, total=False): + tool_references: Required[Iterable[ToolReferenceBlockParam]] + + type: Required[Literal["tool_search_tool_search_result"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/tool_union_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/tool_union_param.py new file mode 100644 index 0000000000000000000000000000000000000000..b74efaba6e238c9b935f029be7b098cc7146003f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/tool_union_param.py @@ -0,0 +1,44 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .tool_param import ToolParam +from .tool_bash_20250124_param import ToolBash20250124Param +from .memory_tool_20250818_param import MemoryTool20250818Param +from .web_fetch_tool_20250910_param import WebFetchTool20250910Param +from .web_fetch_tool_20260209_param import WebFetchTool20260209Param +from .web_fetch_tool_20260309_param import WebFetchTool20260309Param +from .web_search_tool_20250305_param import WebSearchTool20250305Param +from .web_search_tool_20260209_param import WebSearchTool20260209Param +from .tool_text_editor_20250124_param import ToolTextEditor20250124Param +from .tool_text_editor_20250429_param import ToolTextEditor20250429Param +from .tool_text_editor_20250728_param import ToolTextEditor20250728Param +from .code_execution_tool_20250522_param import CodeExecutionTool20250522Param +from .code_execution_tool_20250825_param import CodeExecutionTool20250825Param +from .code_execution_tool_20260120_param import CodeExecutionTool20260120Param +from .tool_search_tool_bm25_20251119_param import ToolSearchToolBm25_20251119Param +from .tool_search_tool_regex_20251119_param import ToolSearchToolRegex20251119Param + +__all__ = ["ToolUnionParam"] + +ToolUnionParam: TypeAlias = Union[ + ToolParam, + ToolBash20250124Param, + CodeExecutionTool20250522Param, + CodeExecutionTool20250825Param, + CodeExecutionTool20260120Param, + MemoryTool20250818Param, + ToolTextEditor20250124Param, + ToolTextEditor20250429Param, + ToolTextEditor20250728Param, + WebSearchTool20250305Param, + WebFetchTool20250910Param, + WebSearchTool20260209Param, + WebFetchTool20260209Param, + WebFetchTool20260309Param, + ToolSearchToolBm25_20251119Param, + ToolSearchToolRegex20251119Param, +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/tool_use_block.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/tool_use_block.py new file mode 100644 index 0000000000000000000000000000000000000000..99ac7f2b8c73bd7d328e85c7cd071e9caec9d4ce --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/tool_use_block.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from .._utils import PropertyInfo +from .._models import BaseModel +from .direct_caller import DirectCaller +from .server_tool_caller import ServerToolCaller +from .server_tool_caller_20260120 import ServerToolCaller20260120 + +__all__ = ["ToolUseBlock", "Caller"] + +Caller: TypeAlias = Annotated[ + Union[DirectCaller, ServerToolCaller, ServerToolCaller20260120], PropertyInfo(discriminator="type") +] + + +class ToolUseBlock(BaseModel): + id: str + + caller: Optional[Caller] = None + """Tool invocation directly from the model.""" + + input: Dict[str, object] + + name: str + + type: Literal["tool_use"] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/tool_use_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/tool_use_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..e673195ab56b88c9fd5bfba0dc25e91748580aee --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/tool_use_block_param.py @@ -0,0 +1,31 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Union, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .direct_caller_param import DirectCallerParam +from .server_tool_caller_param import ServerToolCallerParam +from .cache_control_ephemeral_param import CacheControlEphemeralParam +from .server_tool_caller_20260120_param import ServerToolCaller20260120Param + +__all__ = ["ToolUseBlockParam", "Caller"] + +Caller: TypeAlias = Union[DirectCallerParam, ServerToolCallerParam, ServerToolCaller20260120Param] + + +class ToolUseBlockParam(TypedDict, total=False): + id: Required[str] + + input: Required[Dict[str, object]] + + name: Required[str] + + type: Required[Literal["tool_use"]] + + cache_control: Optional[CacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + caller: Caller + """Tool invocation directly from the model.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/web_fetch_tool_20260209_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/web_fetch_tool_20260209_param.py new file mode 100644 index 0000000000000000000000000000000000000000..c2155cc59b1aeea2b587abc480d90c062d9bef2d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/web_fetch_tool_20260209_param.py @@ -0,0 +1,57 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal, Required, TypedDict + +from .._types import SequenceNotStr +from .citations_config_param import CitationsConfigParam +from .cache_control_ephemeral_param import CacheControlEphemeralParam + +__all__ = ["WebFetchTool20260209Param"] + + +class WebFetchTool20260209Param(TypedDict, total=False): + name: Required[Literal["web_fetch"]] + """Name of the tool. + + This is how the tool will be called by the model and in `tool_use` blocks. + """ + + type: Required[Literal["web_fetch_20260209"]] + + allowed_callers: List[Literal["direct", "code_execution_20250825", "code_execution_20260120"]] + + allowed_domains: Optional[SequenceNotStr[str]] + """List of domains to allow fetching from""" + + blocked_domains: Optional[SequenceNotStr[str]] + """List of domains to block fetching from""" + + cache_control: Optional[CacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + citations: Optional[CitationsConfigParam] + """Citations configuration for fetched documents. + + Citations are disabled by default. + """ + + defer_loading: bool + """If true, tool will not be included in initial system prompt. + + Only loaded when returned via tool_reference from tool search. + """ + + max_content_tokens: Optional[int] + """Maximum number of tokens used by including web page text content in the context. + + The limit is approximate and does not apply to binary content such as PDFs. + """ + + max_uses: Optional[int] + """Maximum number of times the tool can be used in the API request.""" + + strict: bool + """When true, guarantees schema validation on tool names and inputs""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/web_fetch_tool_result_block_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/web_fetch_tool_result_block_param.py new file mode 100644 index 0000000000000000000000000000000000000000..28d552896d4cc08a24918ebd1376e274dabc8ff3 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/web_fetch_tool_result_block_param.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .direct_caller_param import DirectCallerParam +from .web_fetch_block_param import WebFetchBlockParam +from .server_tool_caller_param import ServerToolCallerParam +from .cache_control_ephemeral_param import CacheControlEphemeralParam +from .server_tool_caller_20260120_param import ServerToolCaller20260120Param +from .web_fetch_tool_result_error_block_param import WebFetchToolResultErrorBlockParam + +__all__ = ["WebFetchToolResultBlockParam", "Content", "Caller"] + +Content: TypeAlias = Union[WebFetchToolResultErrorBlockParam, WebFetchBlockParam] + +Caller: TypeAlias = Union[DirectCallerParam, ServerToolCallerParam, ServerToolCaller20260120Param] + + +class WebFetchToolResultBlockParam(TypedDict, total=False): + content: Required[Content] + + tool_use_id: Required[str] + + type: Required[Literal["web_fetch_tool_result"]] + + cache_control: Optional[CacheControlEphemeralParam] + """Create a cache control breakpoint at this content block.""" + + caller: Caller + """Tool invocation directly from the model.""" diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/web_search_tool_request_error_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/web_search_tool_request_error_param.py new file mode 100644 index 0000000000000000000000000000000000000000..fcbc62c511b88104c4c9bd583e78ad356fbe26e2 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/web_search_tool_request_error_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +from .web_search_tool_result_error_code import WebSearchToolResultErrorCode + +__all__ = ["WebSearchToolRequestErrorParam"] + + +class WebSearchToolRequestErrorParam(TypedDict, total=False): + error_code: Required[WebSearchToolResultErrorCode] + + type: Required[Literal["web_search_tool_result_error"]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/web_search_tool_result_block_content.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/web_search_tool_result_block_content.py new file mode 100644 index 0000000000000000000000000000000000000000..c617e2ee0c87308b56733db4cec0990282dfdc53 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/web_search_tool_result_block_content.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union +from typing_extensions import TypeAlias + +from .web_search_result_block import WebSearchResultBlock +from .web_search_tool_result_error import WebSearchToolResultError + +__all__ = ["WebSearchToolResultBlockContent"] + +WebSearchToolResultBlockContent: TypeAlias = Union[WebSearchToolResultError, List[WebSearchResultBlock]] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/web_search_tool_result_block_param_content_param.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/web_search_tool_result_block_param_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..0d9c63f63a0af96346dae580dbb85f79f138a284 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/anthropic/types/web_search_tool_result_block_param_content_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import TypeAlias + +from .web_search_result_block_param import WebSearchResultBlockParam +from .web_search_tool_request_error_param import WebSearchToolRequestErrorParam + +__all__ = ["WebSearchToolResultBlockParamContentParam"] + +WebSearchToolResultBlockParamContentParam: TypeAlias = Union[ + Iterable[WebSearchResultBlockParam], WebSearchToolRequestErrorParam +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/YoutubeDL.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/YoutubeDL.py new file mode 100644 index 0000000000000000000000000000000000000000..7db6303d4fda37af1327d5c1a8cd248c7b2bc682 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/YoutubeDL.py @@ -0,0 +1,4512 @@ +import collections +import contextlib +import copy +import datetime as dt +import errno +import fileinput +import functools +import http.cookiejar +import io +import itertools +import json +import locale +import operator +import os +import random +import re +import shutil +import string +import subprocess +import sys +import tempfile +import time +import tokenize +import traceback +import unicodedata + +from .cache import Cache +from .compat import urllib # isort: split +from .compat import urllib_req_to_req +from .cookies import CookieLoadError, LenientSimpleCookie, load_cookies +from .downloader import FFmpegFD, get_suitable_downloader, shorten_protocol_name +from .downloader.rtmp import rtmpdump_version +from .extractor import gen_extractor_classes, get_info_extractor, import_extractors +from .extractor.common import UnsupportedURLIE +from .extractor.openload import PhantomJSwrapper +from .globals import ( + IN_CLI, + LAZY_EXTRACTORS, + WINDOWS_VT_MODE, + plugin_ies, + plugin_ies_overrides, + plugin_pps, + all_plugins_loaded, + plugin_dirs, + supported_js_runtimes, + supported_remote_components, +) +from .minicurses import format_text +from .networking import HEADRequest, Request, RequestDirector +from .networking.common import _REQUEST_HANDLERS, _RH_PREFERENCES +from .networking.exceptions import ( + HTTPError, + NoSupportingHandlers, + RequestError, + SSLError, + network_exceptions, +) +from .networking.impersonate import ImpersonateRequestHandler, ImpersonateTarget +from .plugins import directories as plugin_directories, load_all_plugins +from .postprocessor import ( + EmbedThumbnailPP, + FFmpegFixupDuplicateMoovPP, + FFmpegFixupDurationPP, + FFmpegFixupM3u8PP, + FFmpegFixupM4aPP, + FFmpegFixupStretchedPP, + FFmpegFixupTimestampPP, + FFmpegMergerPP, + FFmpegPostProcessor, + FFmpegVideoConvertorPP, + MoveFilesAfterDownloadPP, + get_postprocessor, +) +from .postprocessor.ffmpeg import resolve_mapping as resolve_recode_mapping +from .update import ( + REPOSITORY, + _get_system_deprecation, + _get_outdated_warning, + _make_label, + current_git_head, + detect_variant, +) +from .utils import ( + DEFAULT_OUTTMPL, + IDENTITY, + LINK_TEMPLATES, + MEDIA_EXTENSIONS, + NO_DEFAULT, + NUMBER_RE, + OUTTMPL_TYPES, + POSTPROCESS_WHEN, + STR_FORMAT_RE_TMPL, + STR_FORMAT_TYPES, + ContentTooShortError, + DateRange, + DownloadCancelled, + DownloadError, + EntryNotInPlaylist, + ExistingVideoReached, + ExtractorError, + FormatSorter, + GeoRestrictedError, + ISO3166Utils, + LazyList, + MaxDownloadsReached, + Namespace, + PagedList, + PlaylistEntries, + Popen, + PostProcessingError, + ReExtractInfo, + RejectedVideoReached, + SameFileError, + UnavailableVideoError, + UserNotLive, + YoutubeDLError, + age_restricted, + bug_reports_message, + date_from_str, + deprecation_warning, + determine_ext, + determine_protocol, + encode_compat_str, + escapeHTML, + expand_path, + extract_basic_auth, + filter_dict, + float_or_none, + format_bytes, + format_decimal_suffix, + format_field, + formatSeconds, + get_compatible_ext, + get_domain, + int_or_none, + iri_to_uri, + is_path_like, + join_nonempty, + locked_file, + make_archive_id, + make_dir, + number_of_digits, + orderedSet, + orderedSet_from_options, + parse_filesize, + preferredencoding, + prepend_extension, + remove_terminal_sequences, + render_table, + replace_extension, + sanitize_filename, + sanitize_path, + sanitize_url, + shell_quote, + str_or_none, + strftime_or_none, + subtitles_filename, + supports_terminal_sequences, + system_identifier, + filesize_from_tbr, + timetuple_from_msec, + to_high_limit_path, + traverse_obj, + try_call, + try_get, + url_basename, + variadic, + windows_enable_vt_mode, + write_json_file, + write_string, +) +from .utils._utils import _UnsafeExtensionError, _YDLLogger, _ProgressState +from .utils.networking import ( + HTTPHeaderDict, + clean_headers, + clean_proxies, + std_headers, +) +from .version import CHANNEL, ORIGIN, RELEASE_GIT_HEAD, VARIANT, __version__ + +if os.name == 'nt': + import ctypes + + +def _catch_unsafe_extension_error(func): + @functools.wraps(func) + def wrapper(self, *args, **kwargs): + try: + return func(self, *args, **kwargs) + except _UnsafeExtensionError as error: + self.report_error( + f'The extracted extension ({error.extension!r}) is unusual ' + 'and will be skipped for safety reasons. ' + f'If you believe this is an error{bug_reports_message(",")}') + + return wrapper + + +class YoutubeDL: + """YoutubeDL class. + + YoutubeDL objects are the ones responsible of downloading the + actual video file and writing it to disk if the user has requested + it, among some other tasks. In most cases there should be one per + program. As, given a video URL, the downloader doesn't know how to + extract all the needed information, task that InfoExtractors do, it + has to pass the URL to one of them. + + For this, YoutubeDL objects have a method that allows + InfoExtractors to be registered in a given order. When it is passed + a URL, the YoutubeDL object handles it to the first InfoExtractor it + finds that reports being able to handle it. The InfoExtractor extracts + all the information about the video or videos the URL refers to, and + YoutubeDL process the extracted information, possibly using a File + Downloader to download the video. + + YoutubeDL objects accept a lot of parameters. In order not to saturate + the object constructor with arguments, it receives a dictionary of + options instead. These options are available through the params + attribute for the InfoExtractors to use. The YoutubeDL also + registers itself as the downloader in charge for the InfoExtractors + that are added to it, so this is a "mutual registration". + + Available options: + + username: Username for authentication purposes. + password: Password for authentication purposes. + videopassword: Password for accessing a video. + ap_mso: Adobe Pass multiple-system operator identifier. + ap_username: Multiple-system operator account username. + ap_password: Multiple-system operator account password. + usenetrc: Use netrc for authentication instead. + netrc_location: Location of the netrc file. Defaults to ~/.netrc. + netrc_cmd: Use a shell command to get credentials + verbose: Print additional info to stdout. + quiet: Do not print messages to stdout. + no_warnings: Do not print out anything for warnings. + forceprint: A dict with keys WHEN mapped to a list of templates to + print to stdout. The allowed keys are video or any of the + items in utils.POSTPROCESS_WHEN. + For compatibility, a single list is also accepted + print_to_file: A dict with keys WHEN (same as forceprint) mapped to + a list of tuples with (template, filename) + forcejson: Force printing info_dict as JSON. + dump_single_json: Force printing the info_dict of the whole playlist + (or video) as a single JSON line. + force_write_download_archive: Force writing download archive regardless + of 'skip_download' or 'simulate'. + simulate: Do not download the video files. If unset (or None), + simulate only if listsubtitles, listformats or list_thumbnails is used + format: Video format code. see "FORMAT SELECTION" for more details. + You can also pass a function. The function takes 'ctx' as + argument and returns the formats to download. + See "build_format_selector" for an implementation + allow_unplayable_formats: Allow unplayable formats to be extracted and downloaded. + ignore_no_formats_error: Ignore "No video formats" error. Usefull for + extracting metadata even if the video is not actually + available for download (experimental) + format_sort: A list of fields by which to sort the video formats. + See "Sorting Formats" for more details. + format_sort_force: Force the given format_sort. see "Sorting Formats" + for more details. + prefer_free_formats: Whether to prefer video formats with free containers + over non-free ones of the same quality. + allow_multiple_video_streams: Allow multiple video streams to be merged + into a single file + allow_multiple_audio_streams: Allow multiple audio streams to be merged + into a single file + check_formats Whether to test if the formats are downloadable. + Can be True (check all), False (check none), + 'selected' (check selected formats), + or None (check only if requested by extractor) + paths: Dictionary of output paths. The allowed keys are 'home' + 'temp' and the keys of OUTTMPL_TYPES (in utils/_utils.py) + outtmpl: Dictionary of templates for output names. Allowed keys + are 'default' and the keys of OUTTMPL_TYPES (in utils/_utils.py). + For compatibility with youtube-dl, a single string can also be used + outtmpl_na_placeholder: Placeholder for unavailable meta fields. + restrictfilenames: Do not allow "&" and spaces in file names + trim_file_name: Limit length of filename (extension excluded) + windowsfilenames: True: Force filenames to be Windows compatible + False: Sanitize filenames only minimally + This option has no effect when running on Windows + ignoreerrors: Do not stop on download/postprocessing errors. + Can be 'only_download' to ignore only download errors. + Default is 'only_download' for CLI, but False for API + skip_playlist_after_errors: Number of allowed failures until the rest of + the playlist is skipped + allowed_extractors: List of regexes to match against extractor names that are allowed + overwrites: Overwrite all video and metadata files if True, + overwrite only non-video files if None + and don't overwrite any file if False + playlist_items: Specific indices of playlist to download. + playlistrandom: Download playlist items in random order. + lazy_playlist: Process playlist entries as they are received. + matchtitle: Download only matching titles. + rejecttitle: Reject downloads for matching titles. + logger: A class having a `debug`, `warning` and `error` function where + each has a single string parameter, the message to be logged. + For compatibility reasons, both debug and info messages are passed to `debug`. + A debug message will have a prefix of `[debug] ` to discern it from info messages. + logtostderr: Print everything to stderr instead of stdout. + consoletitle: Display progress in the console window's titlebar. + writedescription: Write the video description to a .description file + writeinfojson: Write the video description to a .info.json file + clean_infojson: Remove internal metadata from the infojson + getcomments: Extract video comments. This will not be written to disk + unless writeinfojson is also given + writethumbnail: Write the thumbnail image to a file + allow_playlist_files: Whether to write playlists' description, infojson etc + also to disk when using the 'write*' options + write_all_thumbnails: Write all thumbnail formats to files + writelink: Write an internet shortcut file, depending on the + current platform (.url/.webloc/.desktop) + writeurllink: Write a Windows internet shortcut file (.url) + writewebloclink: Write a macOS internet shortcut file (.webloc) + writedesktoplink: Write a Linux internet shortcut file (.desktop) + writesubtitles: Write the video subtitles to a file + writeautomaticsub: Write the automatically generated subtitles to a file + listsubtitles: Lists all available subtitles for the video + subtitlesformat: The format code for subtitles + subtitleslangs: List of languages of the subtitles to download (can be regex). + The list may contain "all" to refer to all the available + subtitles. The language can be prefixed with a "-" to + exclude it from the requested languages, e.g. ['all', '-live_chat'] + keepvideo: Keep the video file after post-processing + daterange: A utils.DateRange object, download only if the upload_date is in the range. + skip_download: Skip the actual download of the video file + cachedir: Location of the cache files in the filesystem. + False to disable filesystem cache. + noplaylist: Download single video instead of a playlist if in doubt. + age_limit: An integer representing the user's age in years. + Unsuitable videos for the given age are skipped. + min_views: An integer representing the minimum view count the video + must have in order to not be skipped. + Videos without view count information are always + downloaded. None for no limit. + max_views: An integer representing the maximum view count. + Videos that are more popular than that are not + downloaded. + Videos without view count information are always + downloaded. None for no limit. + download_archive: A set, or the name of a file where all downloads are recorded. + Videos already present in the file are not downloaded again. + break_on_existing: Stop the download process after attempting to download a + file that is in the archive. + break_per_url: Whether break_on_reject and break_on_existing + should act on each input URL as opposed to for the entire queue + cookiefile: File name or text stream from where cookies should be read and dumped to + cookiesfrombrowser: A tuple containing the name of the browser, the profile + name/path from where cookies are loaded, the name of the keyring, + and the container name, e.g. ('chrome', ) or + ('vivaldi', 'default', 'BASICTEXT') or ('firefox', 'default', None, 'Meta') + legacyserverconnect: Explicitly allow HTTPS connection to servers that do not + support RFC 5746 secure renegotiation + nocheckcertificate: Do not verify SSL certificates + client_certificate: Path to client certificate file in PEM format. May include the private key + client_certificate_key: Path to private key file for client certificate + client_certificate_password: Password for client certificate private key, if encrypted. + If not provided and the key is encrypted, yt-dlp will ask interactively + prefer_insecure: Use HTTP instead of HTTPS to retrieve information. + (Only supported by some extractors) + enable_file_urls: Enable file:// URLs. This is disabled by default for security reasons. + http_headers: A dictionary of custom headers to be used for all requests + proxy: URL of the proxy server to use + geo_verification_proxy: URL of the proxy to use for IP address verification + on geo-restricted sites. + socket_timeout: Time to wait for unresponsive hosts, in seconds + bidi_workaround: Work around buggy terminals without bidirectional text + support, using fridibi + debug_printtraffic:Print out sent and received HTTP traffic + default_search: Prepend this string if an input url is not valid. + 'auto' for elaborate guessing + encoding: Use this encoding instead of the system-specified. + extract_flat: Whether to resolve and process url_results further + * False: Always process. Default for API + * True: Never process + * 'in_playlist': Do not process inside playlist/multi_video + * 'discard': Always process, but don't return the result + from inside playlist/multi_video + * 'discard_in_playlist': Same as "discard", but only for + playlists (not multi_video). Default for CLI + wait_for_video: If given, wait for scheduled streams to become available. + The value should be a tuple containing the range + (min_secs, max_secs) to wait between retries + postprocessors: A list of dictionaries, each with an entry + * key: The name of the postprocessor. See + yt_dlp/postprocessor/__init__.py for a list. + * when: When to run the postprocessor. Allowed values are + the entries of utils.POSTPROCESS_WHEN + Assumed to be 'post_process' if not given + progress_hooks: A list of functions that get called on download + progress, with a dictionary with the entries + * status: One of "downloading", "error", or "finished". + Check this first and ignore unknown values. + * info_dict: The extracted info_dict + + If status is one of "downloading", or "finished", the + following properties may also be present: + * filename: The final filename (always present) + * tmpfilename: The filename we're currently writing to + * downloaded_bytes: Bytes on disk + * total_bytes: Size of the whole file, None if unknown + * total_bytes_estimate: Guess of the eventual file size, + None if unavailable. + * elapsed: The number of seconds since download started. + * eta: The estimated time in seconds, None if unknown + * speed: The download speed in bytes/second, None if + unknown + * fragment_index: The counter of the currently + downloaded video fragment. + * fragment_count: The number of fragments (= individual + files that will be merged) + + Progress hooks are guaranteed to be called at least once + (with status "finished") if the download is successful. + postprocessor_hooks: A list of functions that get called on postprocessing + progress, with a dictionary with the entries + * status: One of "started", "processing", or "finished". + Check this first and ignore unknown values. + * postprocessor: Name of the postprocessor + * info_dict: The extracted info_dict + + Progress hooks are guaranteed to be called at least twice + (with status "started" and "finished") if the processing is successful. + merge_output_format: "/" separated list of extensions to use when merging formats. + final_ext: Expected final extension; used to detect when the file was + already downloaded and converted + fixup: Automatically correct known faults of the file. + One of: + - "never": do nothing + - "warn": only emit a warning + - "detect_or_warn": check whether we can do anything + about it, warn otherwise (default) + source_address: Client-side IP address to bind to. + impersonate: Client to impersonate for requests. + An ImpersonateTarget (from yt_dlp.networking.impersonate) + sleep_interval_requests: Number of seconds to sleep between requests + during extraction + sleep_interval: Number of seconds to sleep before each download when + used alone or a lower bound of a range for randomized + sleep before each download (minimum possible number + of seconds to sleep) when used along with + max_sleep_interval. + max_sleep_interval:Upper bound of a range for randomized sleep before each + download (maximum possible number of seconds to sleep). + Must only be used along with sleep_interval. + Actual sleep time will be a random float from range + [sleep_interval; max_sleep_interval]. + sleep_interval_subtitles: Number of seconds to sleep before each subtitle download + listformats: Print an overview of available video formats and exit. + list_thumbnails: Print a table of all thumbnails and exit. + match_filter: A function that gets called for every video with the signature + (info_dict, *, incomplete: bool) -> Optional[str] + For backward compatibility with youtube-dl, the signature + (info_dict) -> Optional[str] is also allowed. + - If it returns a message, the video is ignored. + - If it returns None, the video is downloaded. + - If it returns utils.NO_DEFAULT, the user is interactively + asked whether to download the video. + - Raise utils.DownloadCancelled(msg) to abort remaining + downloads when a video is rejected. + match_filter_func in utils/_utils.py is one example for this. + color: A Dictionary with output stream names as keys + and their respective color policy as values. + Can also just be a single color policy, + in which case it applies to all outputs. + Valid stream names are 'stdout' and 'stderr'. + Valid color policies are one of 'always', 'auto', + 'no_color', 'never', 'auto-tty' or 'no_color-tty'. + geo_bypass: Bypass geographic restriction via faking X-Forwarded-For + HTTP header + geo_bypass_country: + Two-letter ISO 3166-2 country code that will be used for + explicit geographic restriction bypassing via faking + X-Forwarded-For HTTP header + geo_bypass_ip_block: + IP range in CIDR notation that will be used similarly to + geo_bypass_country + external_downloader: A dictionary of protocol keys and the executable of the + external downloader to use for it. The allowed protocols + are default|http|ftp|m3u8|dash|rtsp|rtmp|mms. + Set the value to 'native' to use the native downloader + compat_opts: Compatibility options. See "Differences in default behavior". + The following options do not work when used through the API: + filename, abort-on-error, multistreams, no-live-chat, + format-sort, no-clean-infojson, no-playlist-metafiles, + no-keep-subs, no-attach-info-json, allow-unsafe-ext, prefer-vp9-sort, + mtime-by-default. + Refer __init__.py for their implementation + progress_template: Dictionary of templates for progress outputs. + Allowed keys are 'download', 'postprocess', + 'download-title' (console title) and 'postprocess-title'. + The template is mapped on a dictionary with keys 'progress' and 'info' + retry_sleep_functions: Dictionary of functions that takes the number of attempts + as argument and returns the time to sleep in seconds. + Allowed keys are 'http', 'fragment', 'file_access', 'extractor' + download_ranges: A callback function that gets called for every video with + the signature (info_dict, ydl) -> Iterable[Section]. + Only the returned sections will be downloaded. + Each Section is a dict with the following keys: + * start_time: Start time of the section in seconds + * end_time: End time of the section in seconds + * title: Section title (Optional) + * index: Section number (Optional) + force_keyframes_at_cuts: Re-encode the video when downloading ranges to get precise cuts + noprogress: Do not print the progress bar + live_from_start: Whether to download livestreams videos from the start + warn_when_outdated: Emit a warning if the yt-dlp version is older than 90 days + + The following parameters are not used by YoutubeDL itself, they are used by + the downloader (see yt_dlp/downloader/common.py): + nopart, updatetime, buffersize, ratelimit, throttledratelimit, min_filesize, + max_filesize, test, noresizebuffer, retries, file_access_retries, fragment_retries, + continuedl, hls_use_mpegts, http_chunk_size, external_downloader_args, + concurrent_fragment_downloads, progress_delta. + + The following options are used by the post processors: + ffmpeg_location: Location of the ffmpeg binary; either the path + to the binary or its containing directory. + postprocessor_args: A dictionary of postprocessor/executable keys (in lower case) + and a list of additional command-line arguments for the + postprocessor/executable. The dict can also have "PP+EXE" keys + which are used when the given exe is used by the given PP. + Use 'default' as the name for arguments to passed to all PP + For compatibility with youtube-dl, a single list of args + can also be used + + The following options are used by the extractors: + extractor_retries: Number of times to retry for known errors (default: 3) + dynamic_mpd: Whether to process dynamic DASH manifests (default: True) + hls_split_discontinuity: Split HLS playlists into different formats at + discontinuities such as ad breaks (default: False) + extractor_args: A dictionary of arguments to be passed to the extractors. + See "EXTRACTOR ARGUMENTS" for details. + Argument values must always be a list of string(s). + E.g. {'youtube': {'skip': ['dash', 'hls']}} + js_runtimes: A dictionary of JavaScript runtime keys (in lower case) to enable + and a dictionary of additional configuration for the runtime. + Currently supported runtimes are 'deno', 'node', 'bun', and 'quickjs'. + If None, the default runtime of "deno" will be enabled. + The runtime configuration dictionary can have the following keys: + - path: Path to the executable (optional) + E.g. {'deno': {'path': '/path/to/deno'} + remote_components: A list of remote components that are allowed to be fetched when required. + Supported components: + - ejs:npm (external JavaScript components from npm) + - ejs:github (external JavaScript components from yt-dlp-ejs GitHub) + By default, no remote components are allowed to be fetched. + mark_watched: Mark videos watched (even with --simulate). Only for YouTube + + The following options are deprecated and may be removed in the future: + + break_on_reject: Stop the download process when encountering a video that + has been filtered out. + - `raise DownloadCancelled(msg)` in match_filter instead + force_generic_extractor: Force downloader to use the generic extractor + - Use allowed_extractors = ['generic', 'default'] + playliststart: - Use playlist_items + Playlist item to start at. + playlistend: - Use playlist_items + Playlist item to end at. + playlistreverse: - Use playlist_items + Download playlist items in reverse order. + forceurl: - Use forceprint + Force printing final URL. + forcetitle: - Use forceprint + Force printing title. + forceid: - Use forceprint + Force printing ID. + forcethumbnail: - Use forceprint + Force printing thumbnail URL. + forcedescription: - Use forceprint + Force printing description. + forcefilename: - Use forceprint + Force printing final filename. + forceduration: - Use forceprint + Force printing duration. + allsubtitles: - Use subtitleslangs = ['all'] + Downloads all the subtitles of the video + (requires writesubtitles or writeautomaticsub) + post_hooks: - Register a custom postprocessor + A list of functions that get called as the final step + for each video file, after all postprocessors have been + called. The filename will be passed as the only argument. + hls_prefer_native: - Use external_downloader = {'m3u8': 'native'} or {'m3u8': 'ffmpeg'}. + Use the native HLS downloader instead of ffmpeg + if True, otherwise use ffmpeg if False, otherwise + use downloader suggested by extractor if None. + no_color: Same as `color='no_color'` + no_overwrites: Same as `overwrites=False` + """ + + _NUMERIC_FIELDS = { + 'width', 'height', 'asr', 'audio_channels', 'fps', + 'tbr', 'abr', 'vbr', 'filesize', 'filesize_approx', + 'timestamp', 'release_timestamp', 'available_at', + 'duration', 'view_count', 'like_count', 'dislike_count', 'repost_count', 'save_count', + 'average_rating', 'comment_count', 'age_limit', + 'start_time', 'end_time', + 'chapter_number', 'season_number', 'episode_number', + 'track_number', 'disc_number', 'release_year', + } + + _format_fields = { + # NB: Keep in sync with the docstring of extractor/common.py + 'url', 'manifest_url', 'manifest_stream_number', 'ext', 'format', 'format_id', 'format_note', 'available_at', + 'width', 'height', 'aspect_ratio', 'resolution', 'dynamic_range', 'tbr', 'abr', 'acodec', 'asr', 'audio_channels', + 'vbr', 'fps', 'vcodec', 'container', 'filesize', 'filesize_approx', 'rows', 'columns', 'hls_media_playlist_data', + 'player_url', 'protocol', 'fragment_base_url', 'fragments', 'is_from_start', 'is_dash_periods', 'request_data', + 'preference', 'language', 'language_preference', 'quality', 'source_preference', 'cookies', + 'http_headers', 'stretched_ratio', 'no_resume', 'has_drm', 'extra_param_to_segment_url', 'extra_param_to_key_url', + 'hls_aes', 'downloader_options', 'impersonate', 'page_url', 'app', 'play_path', 'tc_url', 'flash_version', + 'rtmp_live', 'rtmp_conn', 'rtmp_protocol', 'rtmp_real_time', + } + _deprecated_multivalue_fields = { + 'album_artist': 'album_artists', + 'artist': 'artists', + 'composer': 'composers', + 'creator': 'creators', + 'genre': 'genres', + } + _format_selection_exts = { + 'audio': set(MEDIA_EXTENSIONS.common_audio), + 'video': {*MEDIA_EXTENSIONS.common_video, '3gp'}, + 'storyboards': set(MEDIA_EXTENSIONS.storyboards), + } + + def __init__(self, params=None, auto_init=True): + """Create a FileDownloader object with the given options. + @param auto_init Whether to load the default extractors and print header (if verbose). + Set to 'no_verbose_header' to not print the header + """ + if params is None: + params = {} + self.params = params + self._ies = {} + self._ies_instances = {} + self._pps = {k: [] for k in POSTPROCESS_WHEN} + self._printed_messages = set() + self._first_webpage_request = True + self._post_hooks = [] + self._close_hooks = [] + self._progress_hooks = [] + self._postprocessor_hooks = [] + self._download_retcode = 0 + self._num_downloads = 0 + self._num_videos = 0 + self._playlist_level = 0 + self._playlist_urls = set() + self.cache = Cache(self) + self.__header_cookies = [] + + # compat for API: load plugins if they have not already + if not all_plugins_loaded.value: + load_all_plugins() + + stdout = sys.stderr if self.params.get('logtostderr') else sys.stdout + self._out_files = Namespace( + out=stdout, + error=sys.stderr, + screen=sys.stderr if self.params.get('quiet') else stdout, + ) + + try: + windows_enable_vt_mode() + except Exception as e: + self.write_debug(f'Failed to enable VT mode: {e}') + + # hehe "immutable" namespace + self._out_files.console = next(filter(supports_terminal_sequences, (sys.stderr, sys.stdout)), None) + + if self.params.get('no_color'): + if self.params.get('color') is not None: + self.params.setdefault('_warnings', []).append( + 'Overwriting params from "color" with "no_color"') + self.params['color'] = 'no_color' + + term_allow_color = os.getenv('TERM', '').lower() != 'dumb' + base_no_color = bool(os.getenv('NO_COLOR')) + + def process_color_policy(stream): + stream_name = {sys.stdout: 'stdout', sys.stderr: 'stderr'}[stream] + policy = traverse_obj(self.params, ('color', (stream_name, None), {str}, any)) or 'auto' + if policy in ('auto', 'auto-tty', 'no_color-tty'): + no_color = base_no_color + if policy.endswith('tty'): + no_color = policy.startswith('no_color') + if term_allow_color and supports_terminal_sequences(stream): + return 'no_color' if no_color else True + return False + assert policy in ('always', 'never', 'no_color'), policy + return {'always': True, 'never': False}.get(policy, policy) + + self._allow_colors = Namespace(**{ + name: process_color_policy(stream) + for name, stream in self._out_files.items_ if name != 'console' + }) + + system_deprecation = _get_system_deprecation() + if system_deprecation: + self.deprecated_feature(system_deprecation.replace('\n', '\n ')) + elif self.params.get('warn_when_outdated'): + if outdated_warning := _get_outdated_warning(): + self.report_warning(outdated_warning) + + if self.params.get('allow_unplayable_formats'): + self.report_warning( + f'You have asked for {self._format_err("UNPLAYABLE", self.Styles.EMPHASIS)} formats to be listed/downloaded. ' + 'This is a developer option intended for debugging. \n' + ' If you experience any issues while using this option, ' + f'{self._format_err("DO NOT", self.Styles.ERROR)} open a bug report') + + if self.params.get('bidi_workaround', False): + try: + import pty + master, slave = pty.openpty() + width = shutil.get_terminal_size().columns + width_args = [] if width is None else ['-w', str(width)] + sp_kwargs = {'stdin': subprocess.PIPE, 'stdout': slave, 'stderr': self._out_files.error} + try: + self._output_process = Popen(['bidiv', *width_args], **sp_kwargs) + except OSError: + self._output_process = Popen(['fribidi', '-c', 'UTF-8', *width_args], **sp_kwargs) + self._output_channel = os.fdopen(master, 'rb') + except OSError as ose: + if ose.errno == errno.ENOENT: + self.report_warning( + 'Could not find fribidi executable, ignoring --bidi-workaround. ' + 'Make sure that fribidi is an executable file in one of the directories in your $PATH.') + else: + raise + + # Note: this must be after plugins are loaded + self.params['js_runtimes'] = self.params.get('js_runtimes', {'deno': {}}) + self._clean_js_runtimes(self.params['js_runtimes']) + + self.params['remote_components'] = set(self.params.get('remote_components', ())) + self._clean_remote_components(self.params['remote_components']) + + self.params['compat_opts'] = set(self.params.get('compat_opts', ())) + self.params['http_headers'] = HTTPHeaderDict(std_headers, self.params.get('http_headers')) + self._load_cookies(self.params['http_headers'].get('Cookie')) # compat + self.params['http_headers'].pop('Cookie', None) + + if auto_init and auto_init != 'no_verbose_header': + self.print_debug_header() + + def check_deprecated(param, option, suggestion): + if self.params.get(param) is not None: + self.report_warning(f'{option} is deprecated. Use {suggestion} instead') + return True + return False + + check_deprecated('useid', '--id', '-o "%(id)s.%(ext)s"') + + for msg in self.params.get('_warnings', []): + self.report_warning(msg) + for msg in self.params.get('_deprecation_warnings', []): + self.deprecated_feature(msg) + + if impersonate_target := self.params.get('impersonate'): + if not self._impersonate_target_available(impersonate_target): + raise YoutubeDLError( + f'Impersonate target "{impersonate_target}" is not available. ' + f'Use --list-impersonate-targets to see available targets. ' + f'You may be missing dependencies required to support this target.') + + if 'list-formats' in self.params['compat_opts']: + self.params['listformats_table'] = False + + if 'overwrites' not in self.params and self.params.get('nooverwrites') is not None: + # nooverwrites was unnecessarily changed to overwrites + # in 0c3d0f51778b153f65c21906031c2e091fcfb641 + # This ensures compatibility with both keys + self.params['overwrites'] = not self.params['nooverwrites'] + elif self.params.get('overwrites') is None: + self.params.pop('overwrites', None) + else: + self.params['nooverwrites'] = not self.params['overwrites'] + + if self.params.get('simulate') is None and any(( + self.params.get('list_thumbnails'), + self.params.get('listformats'), + self.params.get('listsubtitles'), + )): + self.params['simulate'] = 'list_only' + + self.params.setdefault('forceprint', {}) + self.params.setdefault('print_to_file', {}) + + # Compatibility with older syntax + if not isinstance(params['forceprint'], dict): + self.params['forceprint'] = {'video': params['forceprint']} + + if auto_init: + self.add_default_info_extractors() + + if (sys.platform != 'win32' + and sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968'] + and not self.params.get('restrictfilenames', False)): + # Unicode filesystem API will throw errors (#1474, #13027) + self.report_warning( + 'Assuming --restrict-filenames since file system encoding ' + 'cannot encode all characters. ' + 'Set the LC_ALL environment variable to fix this.') + self.params['restrictfilenames'] = True + + self._parse_outtmpl() + + # Creating format selector here allows us to catch syntax errors before the extraction + self.format_selector = ( + self.params.get('format') if self.params.get('format') in (None, '-') + else self.params['format'] if callable(self.params['format']) + else self.build_format_selector(self.params['format'])) + + hooks = { + 'post_hooks': self.add_post_hook, + 'progress_hooks': self.add_progress_hook, + 'postprocessor_hooks': self.add_postprocessor_hook, + } + for opt, fn in hooks.items(): + for ph in self.params.get(opt, []): + fn(ph) + + for pp_def_raw in self.params.get('postprocessors', []): + pp_def = dict(pp_def_raw) + when = pp_def.pop('when', 'post_process') + self.add_post_processor( + get_postprocessor(pp_def.pop('key'))(self, **pp_def), + when=when) + + def preload_download_archive(fn): + """Preload the archive, if any is specified""" + archive = set() + if fn is None: + return archive + elif not is_path_like(fn): + return fn + + self.write_debug(f'Loading archive file {fn!r}') + try: + with locked_file(fn, 'r', encoding='utf-8') as archive_file: + for line in archive_file: + archive.add(line.strip()) + except OSError as ioe: + if ioe.errno != errno.ENOENT: + raise + return archive + + self.archive = preload_download_archive(self.params.get('download_archive')) + + def _clean_js_runtimes(self, runtimes): + if not ( + isinstance(runtimes, dict) + and all(isinstance(k, str) and (v is None or isinstance(v, dict)) for k, v in runtimes.items()) + ): + raise ValueError('Invalid js_runtimes format, expected a dict of {runtime: {config}}') + + if unsupported_runtimes := runtimes.keys() - supported_js_runtimes.value.keys(): + self.report_warning( + f'Ignoring unsupported JavaScript runtime(s): {", ".join(unsupported_runtimes)}.' + f' Supported runtimes: {", ".join(supported_js_runtimes.value.keys())}.') + for rt in unsupported_runtimes: + runtimes.pop(rt) + + def _clean_remote_components(self, remote_components: set): + if unsupported_remote_components := set(remote_components) - set(supported_remote_components.value): + self.report_warning( + f'Ignoring unsupported remote component(s): {", ".join(unsupported_remote_components)}.' + f' Supported remote components: {", ".join(supported_remote_components.value)}.') + for rt in unsupported_remote_components: + remote_components.remove(rt) + + @functools.cached_property + def _js_runtimes(self): + runtimes = {} + for name, config in self.params.get('js_runtimes', {}).items(): + runtime_cls = supported_js_runtimes.value.get(name) + runtimes[name] = runtime_cls(path=config.get('path')) if runtime_cls else None + return runtimes + + def warn_if_short_id(self, argv): + # short YouTube ID starting with dash? + idxs = [ + i for i, a in enumerate(argv) + if re.match(r'^-[0-9A-Za-z_-]{10}$', a)] + if idxs: + correct_argv = ( + ['yt-dlp'] + + [a for i, a in enumerate(argv) if i not in idxs] + + ['--'] + [argv[i] for i in idxs] + ) + self.report_warning( + 'Long argument string detected. ' + f'Use -- to separate parameters and URLs, like this:\n{shell_quote(correct_argv)}') + + def add_info_extractor(self, ie): + """Add an InfoExtractor object to the end of the list.""" + ie_key = ie.ie_key() + self._ies[ie_key] = ie + if not isinstance(ie, type): + self._ies_instances[ie_key] = ie + ie.set_downloader(self) + + def get_info_extractor(self, ie_key): + """ + Get an instance of an IE with name ie_key, it will try to get one from + the _ies list, if there's no instance it will create a new one and add + it to the extractor list. + """ + ie = self._ies_instances.get(ie_key) + if ie is None: + ie = get_info_extractor(ie_key)() + self.add_info_extractor(ie) + return ie + + def add_default_info_extractors(self): + """ + Add the InfoExtractors returned by gen_extractors to the end of the list + """ + all_ies = {ie.IE_NAME.lower(): ie for ie in gen_extractor_classes()} + all_ies['end'] = UnsupportedURLIE() + try: + ie_names = orderedSet_from_options( + self.params.get('allowed_extractors', ['default']), { + 'all': list(all_ies), + 'default': [name for name, ie in all_ies.items() if ie._ENABLED], + }, use_regex=True) + except re.error as e: + raise ValueError(f'Wrong regex for allowed_extractors: {e.pattern}') + for name in ie_names: + self.add_info_extractor(all_ies[name]) + self.write_debug(f'Loaded {len(ie_names)} extractors') + + def add_post_processor(self, pp, when='post_process'): + """Add a PostProcessor object to the end of the chain.""" + assert when in POSTPROCESS_WHEN, f'Invalid when={when}' + self._pps[when].append(pp) + pp.set_downloader(self) + + def add_post_hook(self, ph): + """Add the post hook""" + self._post_hooks.append(ph) + + def add_close_hook(self, ch): + """Add a close hook, called when YoutubeDL.close() is called""" + assert callable(ch), 'Close hook must be callable' + self._close_hooks.append(ch) + + def add_progress_hook(self, ph): + """Add the download progress hook""" + self._progress_hooks.append(ph) + + def add_postprocessor_hook(self, ph): + """Add the postprocessing progress hook""" + self._postprocessor_hooks.append(ph) + for pps in self._pps.values(): + for pp in pps: + pp.add_progress_hook(ph) + + def _bidi_workaround(self, message): + if not hasattr(self, '_output_channel'): + return message + + assert hasattr(self, '_output_process') + assert isinstance(message, str) + line_count = message.count('\n') + 1 + self._output_process.stdin.write((message + '\n').encode()) + self._output_process.stdin.flush() + res = ''.join(self._output_channel.readline().decode() + for _ in range(line_count)) + return res[:-len('\n')] + + def _write_string(self, message, out=None, only_once=False): + if only_once: + if message in self._printed_messages: + return + self._printed_messages.add(message) + write_string(message, out=out, encoding=self.params.get('encoding')) + + def to_stdout(self, message, skip_eol=False, quiet=None): + """Print message to stdout""" + if quiet is not None: + self.deprecation_warning('"YoutubeDL.to_stdout" no longer accepts the argument quiet. ' + 'Use "YoutubeDL.to_screen" instead') + if skip_eol is not False: + self.deprecation_warning('"YoutubeDL.to_stdout" no longer accepts the argument skip_eol. ' + 'Use "YoutubeDL.to_screen" instead') + self._write_string(f'{self._bidi_workaround(message)}\n', self._out_files.out) + + def to_screen(self, message, skip_eol=False, quiet=None, only_once=False): + """Print message to screen if not in quiet mode""" + if self.params.get('logger'): + self.params['logger'].debug(message) + return + if (self.params.get('quiet') if quiet is None else quiet) and not self.params.get('verbose'): + return + self._write_string( + '{}{}'.format(self._bidi_workaround(message), ('' if skip_eol else '\n')), + self._out_files.screen, only_once=only_once) + + def to_stderr(self, message, only_once=False): + """Print message to stderr""" + assert isinstance(message, str) + if self.params.get('logger'): + self.params['logger'].error(message) + else: + self._write_string(f'{self._bidi_workaround(message)}\n', self._out_files.error, only_once=only_once) + + def _send_console_code(self, code): + if not supports_terminal_sequences(self._out_files.console): + return False + self._write_string(code, self._out_files.console) + return True + + def to_console_title(self, message=None, progress_state=None, percent=None): + if not self.params.get('consoletitle'): + return + + if message: + success = self._send_console_code(f'\033]0;{remove_terminal_sequences(message)}\007') + if not success and os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow(): + ctypes.windll.kernel32.SetConsoleTitleW(message) + + if isinstance(progress_state, _ProgressState): + self._send_console_code(progress_state.get_ansi_escape(percent)) + + def save_console_title(self): + if not self.params.get('consoletitle') or self.params.get('simulate'): + return + self._send_console_code('\033[22;0t') # Save the title on stack + + def restore_console_title(self): + if not self.params.get('consoletitle') or self.params.get('simulate'): + return + self._send_console_code('\033[23;0t') # Restore the title from stack + + def __enter__(self): + self.save_console_title() + self.to_console_title(progress_state=_ProgressState.INDETERMINATE) + return self + + def save_cookies(self): + if self.params.get('cookiefile') is not None: + self.cookiejar.save() + + def __exit__(self, *args): + self.restore_console_title() + self.to_console_title(progress_state=_ProgressState.HIDDEN) + self.close() + + def close(self): + self.save_cookies() + if '_request_director' in self.__dict__: + self._request_director.close() + del self._request_director + + for close_hook in self._close_hooks: + close_hook() + + def trouble(self, message=None, tb=None, is_error=True): + """Determine action to take when a download problem appears. + + Depending on if the downloader has been configured to ignore + download errors or not, this method may throw an exception or + not when errors are found, after printing the message. + + @param tb If given, is additional traceback information + @param is_error Whether to raise error according to ignorerrors + """ + if message is not None: + self.to_stderr(message) + if self.params.get('verbose'): + if tb is None: + if sys.exc_info()[0]: # if .trouble has been called from an except block + tb = '' + if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]: + tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info)) + tb += encode_compat_str(traceback.format_exc()) + else: + tb_data = traceback.format_list(traceback.extract_stack()) + tb = ''.join(tb_data) + if tb: + self.to_stderr(tb) + if not is_error: + return + if not self.params.get('ignoreerrors'): + if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]: + exc_info = sys.exc_info()[1].exc_info + else: + exc_info = sys.exc_info() + raise DownloadError(message, exc_info) + self._download_retcode = 1 + + Styles = Namespace( + HEADERS='yellow', + EMPHASIS='light blue', + FILENAME='green', + ID='green', + DELIM='blue', + ERROR='red', + BAD_FORMAT='light red', + WARNING='yellow', + SUPPRESS='light black', + ) + + def _format_text(self, handle, allow_colors, text, f, fallback=None, *, test_encoding=False): + text = str(text) + if test_encoding: + original_text = text + # handle.encoding can be None. See https://github.com/yt-dlp/yt-dlp/issues/2711 + encoding = self.params.get('encoding') or getattr(handle, 'encoding', None) or 'ascii' + text = text.encode(encoding, 'ignore').decode(encoding) + if fallback is not None and text != original_text: + text = fallback + return format_text(text, f) if allow_colors is True else text if fallback is None else fallback + + def _format_out(self, *args, **kwargs): + return self._format_text(self._out_files.out, self._allow_colors.out, *args, **kwargs) + + def _format_screen(self, *args, **kwargs): + return self._format_text(self._out_files.screen, self._allow_colors.screen, *args, **kwargs) + + def _format_err(self, *args, **kwargs): + return self._format_text(self._out_files.error, self._allow_colors.error, *args, **kwargs) + + def report_warning(self, message, only_once=False): + """ + Print the message to stderr, it will be prefixed with 'WARNING:' + If stderr is a tty file the 'WARNING:' will be colored + """ + if self.params.get('logger') is not None: + self.params['logger'].warning(message) + else: + if self.params.get('no_warnings'): + return + self.to_stderr(f'{self._format_err("WARNING:", self.Styles.WARNING)} {message}', only_once) + + def deprecation_warning(self, message, *, stacklevel=0): + deprecation_warning( + message, stacklevel=stacklevel + 1, printer=self.report_error, is_error=False) + + def deprecated_feature(self, message): + if self.params.get('logger') is not None: + self.params['logger'].warning(f'Deprecated Feature: {message}') + self.to_stderr(f'{self._format_err("Deprecated Feature:", self.Styles.ERROR)} {message}', True) + + def report_error(self, message, *args, **kwargs): + """ + Do the same as trouble, but prefixes the message with 'ERROR:', colored + in red if stderr is a tty file. + """ + self.trouble(f'{self._format_err("ERROR:", self.Styles.ERROR)} {message}', *args, **kwargs) + + def write_debug(self, message, only_once=False): + """Log debug message or Print message to stderr""" + if not self.params.get('verbose', False): + return + message = f'[debug] {message}' + if self.params.get('logger'): + self.params['logger'].debug(message) + else: + self.to_stderr(message, only_once) + + def report_file_already_downloaded(self, file_name): + """Report file has already been fully downloaded.""" + try: + self.to_screen(f'[download] {file_name} has already been downloaded') + except UnicodeEncodeError: + self.to_screen('[download] The file has already been downloaded') + + def report_file_delete(self, file_name): + """Report that existing file will be deleted.""" + try: + self.to_screen(f'Deleting existing file {file_name}') + except UnicodeEncodeError: + self.to_screen('Deleting existing file') + + def raise_no_formats(self, info, forced=False, *, msg=None): + has_drm = info.get('_has_drm') + ignored, expected = self.params.get('ignore_no_formats_error'), bool(msg) + msg = msg or (has_drm and 'This video is DRM protected') or 'No video formats found!' + if forced or not ignored: + raise ExtractorError(msg, video_id=info['id'], ie=info['extractor'], + expected=has_drm or ignored or expected) + else: + self.report_warning(msg) + + def parse_outtmpl(self): + self.deprecation_warning('"YoutubeDL.parse_outtmpl" is deprecated and may be removed in a future version') + self._parse_outtmpl() + return self.params['outtmpl'] + + def _parse_outtmpl(self): + sanitize = IDENTITY + if self.params.get('restrictfilenames'): # Remove spaces in the default template + sanitize = lambda x: x.replace(' - ', ' ').replace(' ', '-') + + outtmpl = self.params.setdefault('outtmpl', {}) + if not isinstance(outtmpl, dict): + self.params['outtmpl'] = outtmpl = {'default': outtmpl} + outtmpl.update({k: sanitize(v) for k, v in DEFAULT_OUTTMPL.items() if outtmpl.get(k) is None}) + + def get_output_path(self, dir_type='', filename=None): + paths = self.params.get('paths', {}) + assert isinstance(paths, dict), '"paths" parameter must be a dictionary' + path = os.path.join( + expand_path(paths.get('home', '').strip()), + expand_path(paths.get(dir_type, '').strip()) if dir_type else '', + filename or '') + return sanitize_path(path, force=self.params.get('windowsfilenames')) + + @staticmethod + def _outtmpl_expandpath(outtmpl): + # expand_path translates '%%' into '%' and '$$' into '$' + # correspondingly that is not what we want since we need to keep + # '%%' intact for template dict substitution step. Working around + # with boundary-alike separator hack. + sep = ''.join(random.choices(string.ascii_letters, k=32)) + outtmpl = outtmpl.replace('%%', f'%{sep}%').replace('$$', f'${sep}$') + + # outtmpl should be expand_path'ed before template dict substitution + # because meta fields may contain env variables we don't want to + # be expanded. E.g. for outtmpl "%(title)s.%(ext)s" and + # title "Hello $PATH", we don't want `$PATH` to be expanded. + return expand_path(outtmpl).replace(sep, '') + + @staticmethod + def escape_outtmpl(outtmpl): + """ Escape any remaining strings like %s, %abc% etc. """ + return re.sub( + STR_FORMAT_RE_TMPL.format('', '(?![%(\0])'), + lambda mobj: ('' if mobj.group('has_key') else '%') + mobj.group(0), + outtmpl) + + @classmethod + def validate_outtmpl(cls, outtmpl): + """ @return None or Exception object """ + outtmpl = re.sub( + STR_FORMAT_RE_TMPL.format('[^)]*', '[ljhqBUDS]'), + lambda mobj: f'{mobj.group(0)[:-1]}s', + cls._outtmpl_expandpath(outtmpl)) + try: + cls.escape_outtmpl(outtmpl) % collections.defaultdict(int) + return None + except ValueError as err: + return err + + @staticmethod + def _copy_infodict(info_dict): + info_dict = dict(info_dict) + info_dict.pop('__postprocessors', None) + info_dict.pop('__pending_error', None) + return info_dict + + def prepare_outtmpl(self, outtmpl, info_dict, sanitize=False): + """ Make the outtmpl and info_dict suitable for substitution: ydl.escape_outtmpl(outtmpl) % info_dict + @param sanitize Whether to sanitize the output as a filename + """ + + info_dict.setdefault('epoch', int(time.time())) # keep epoch consistent once set + + info_dict = self._copy_infodict(info_dict) + info_dict['duration_string'] = ( # %(duration>%H-%M-%S)s is wrong if duration > 24hrs + formatSeconds(info_dict['duration'], '-' if sanitize else ':') + if info_dict.get('duration', None) is not None + else None) + info_dict['autonumber'] = int(self.params.get('autonumber_start', 1) - 1 + self._num_downloads) + info_dict['video_autonumber'] = self._num_videos + if info_dict.get('resolution') is None: + info_dict['resolution'] = self.format_resolution(info_dict, default=None) + + # For fields playlist_index, playlist_autonumber and autonumber convert all occurrences + # of %(field)s to %(field)0Nd for backward compatibility + field_size_compat_map = { + 'playlist_index': number_of_digits(info_dict.get('__last_playlist_index') or 0), + 'playlist_autonumber': number_of_digits(info_dict.get('n_entries') or 0), + 'autonumber': self.params.get('autonumber_size') or 5, + } + + TMPL_DICT = {} + EXTERNAL_FORMAT_RE = re.compile(STR_FORMAT_RE_TMPL.format('[^)]*', f'[{STR_FORMAT_TYPES}ljhqBUDS]')) + MATH_FUNCTIONS = { + '+': float.__add__, + '-': float.__sub__, + '*': float.__mul__, + } + # Field is of the form key1.key2... + # where keys (except first) can be string, int, slice or "{field, ...}" + FIELD_INNER_RE = r'(?:\w+|%(num)s|%(num)s?(?::%(num)s?){1,2})' % {'num': r'(?:-?\d+)'} # noqa: UP031 + FIELD_RE = r'\w*(?:\.(?:%(inner)s|{%(field)s(?:,%(field)s)*}))*' % { # noqa: UP031 + 'inner': FIELD_INNER_RE, + 'field': rf'\w*(?:\.{FIELD_INNER_RE})*', + } + MATH_FIELD_RE = rf'(?:{FIELD_RE}|-?{NUMBER_RE})' + MATH_OPERATORS_RE = r'(?:{})'.format('|'.join(map(re.escape, MATH_FUNCTIONS.keys()))) + INTERNAL_FORMAT_RE = re.compile(rf'''(?xs) + (?P-)? + (?P{FIELD_RE}) + (?P(?:{MATH_OPERATORS_RE}{MATH_FIELD_RE})*) + (?:>(?P.+?))? + (?P + (?P(?.*?))? + (?:\|(?P.*?))? + )$''') + + def _from_user_input(field): + if field == ':': + return ... + elif ':' in field: + return slice(*map(int_or_none, field.split(':'))) + elif int_or_none(field) is not None: + return int(field) + return field + + def _traverse_infodict(fields): + fields = [f for x in re.split(r'\.({.+?})\.?', fields) + for f in ([x] if x.startswith('{') else x.split('.'))] + for i in (0, -1): + if fields and not fields[i]: + fields.pop(i) + + for i, f in enumerate(fields): + if not f.startswith('{'): + fields[i] = _from_user_input(f) + continue + assert f.endswith('}'), f'No closing brace for {f} in {fields}' + fields[i] = {k: list(map(_from_user_input, k.split('.'))) for k in f[1:-1].split(',')} + + return traverse_obj(info_dict, fields, traverse_string=True) + + def get_value(mdict): + # Object traversal + value = _traverse_infodict(mdict['fields']) + # Negative + if mdict['negate']: + value = float_or_none(value) + if value is not None: + value *= -1 + # Do maths + offset_key = mdict['maths'] + if offset_key: + value = float_or_none(value) + operator = None + while offset_key: + item = re.match( + MATH_FIELD_RE if operator else MATH_OPERATORS_RE, + offset_key).group(0) + offset_key = offset_key[len(item):] + if operator is None: + operator = MATH_FUNCTIONS[item] + continue + item, multiplier = (item[1:], -1) if item[0] == '-' else (item, 1) + offset = float_or_none(item) + if offset is None: + offset = float_or_none(_traverse_infodict(item)) + try: + value = operator(value, multiplier * offset) + except (TypeError, ZeroDivisionError): + return None + operator = None + # Datetime formatting + if mdict['strf_format']: + value = strftime_or_none(value, mdict['strf_format'].replace('\\,', ',')) + + # XXX: Workaround for https://github.com/yt-dlp/yt-dlp/issues/4485 + if sanitize and value == '': + value = None + return value + + na = self.params.get('outtmpl_na_placeholder', 'NA') + + def filename_sanitizer(key, value, restricted): + return sanitize_filename(str(value), restricted=restricted, is_id=( + bool(re.search(r'(^|[_.])id(\.|$)', key)) + if 'filename-sanitization' in self.params['compat_opts'] + else NO_DEFAULT)) + + if callable(sanitize): + self.deprecation_warning('Passing a callable "sanitize" to YoutubeDL.prepare_outtmpl is deprecated') + elif not sanitize: + pass + elif (sys.platform != 'win32' and not self.params.get('restrictfilenames') + and self.params.get('windowsfilenames') is False): + def sanitize(key, value): + return str(value).replace('/', '\u29F8').replace('\0', '') + else: + def sanitize(key, value): + return filename_sanitizer(key, value, restricted=self.params.get('restrictfilenames')) + + def _dumpjson_default(obj): + if isinstance(obj, (set, LazyList)): + return list(obj) + return repr(obj) + + class _ReplacementFormatter(string.Formatter): + def get_field(self, field_name, args, kwargs): + if field_name.isdigit(): + return args[0], -1 + raise ValueError('Unsupported field') + + replacement_formatter = _ReplacementFormatter() + + def create_key(outer_mobj): + if not outer_mobj.group('has_key'): + return outer_mobj.group(0) + key = outer_mobj.group('key') + mobj = re.match(INTERNAL_FORMAT_RE, key) + value, replacement, default, last_field = None, None, na, '' + while mobj: + mobj = mobj.groupdict() + default = mobj['default'] if mobj['default'] is not None else default + value = get_value(mobj) + last_field, replacement = mobj['fields'], mobj['replacement'] + if value is None and mobj['alternate']: + mobj = re.match(INTERNAL_FORMAT_RE, mobj['remaining'][1:]) + else: + break + + if None not in (value, replacement): + try: + value = replacement_formatter.format(replacement, value) + except ValueError: + value, default = None, na + + fmt = outer_mobj.group('format') + if fmt == 's' and last_field in field_size_compat_map and isinstance(value, int): + fmt = f'0{field_size_compat_map[last_field]:d}d' + + flags = outer_mobj.group('conversion') or '' + str_fmt = f'{fmt[:-1]}s' + if value is None: + value, fmt = default, 's' + elif fmt[-1] == 'l': # list + delim = '\n' if '#' in flags else ', ' + value, fmt = delim.join(map(str, variadic(value, allowed_types=(str, bytes)))), str_fmt + elif fmt[-1] == 'j': # json + value, fmt = json.dumps( + value, default=_dumpjson_default, + indent=4 if '#' in flags else None, ensure_ascii='+' not in flags), str_fmt + elif fmt[-1] == 'h': # html + value, fmt = escapeHTML(str(value)), str_fmt + elif fmt[-1] == 'q': # quoted + value = map(str, variadic(value) if '#' in flags else [value]) + value, fmt = shell_quote(value, shell=True), str_fmt + elif fmt[-1] == 'B': # bytes + value = f'%{str_fmt}'.encode() % str(value).encode() + value, fmt = value.decode('utf-8', 'ignore'), 's' + elif fmt[-1] == 'U': # unicode normalized + value, fmt = unicodedata.normalize( + # "+" = compatibility equivalence, "#" = NFD + 'NF{}{}'.format('K' if '+' in flags else '', 'D' if '#' in flags else 'C'), + value), str_fmt + elif fmt[-1] == 'D': # decimal suffix + num_fmt, fmt = fmt[:-1].replace('#', ''), 's' + value = format_decimal_suffix(value, f'%{num_fmt}f%s' if num_fmt else '%d%s', + factor=1024 if '#' in flags else 1000) + elif fmt[-1] == 'S': # filename sanitization + value, fmt = filename_sanitizer(last_field, value, restricted='#' in flags), str_fmt + elif fmt[-1] == 'c': + if value: + value = str(value)[0] + else: + fmt = str_fmt + elif fmt[-1] not in 'rsa': # numeric + value = float_or_none(value) + if value is None: + value, fmt = default, 's' + + if sanitize: + # If value is an object, sanitize might convert it to a string + # So we manually convert it before sanitizing + if fmt[-1] == 'r': + value, fmt = repr(value), str_fmt + elif fmt[-1] == 'a': + value, fmt = ascii(value), str_fmt + if fmt[-1] in 'csra': + value = sanitize(last_field, value) + + key = '{}\0{}'.format(key.replace('%', '%\0'), outer_mobj.group('format')) + TMPL_DICT[key] = value + return '{prefix}%({key}){fmt}'.format(key=key, fmt=fmt, prefix=outer_mobj.group('prefix')) + + return EXTERNAL_FORMAT_RE.sub(create_key, outtmpl), TMPL_DICT + + def evaluate_outtmpl(self, outtmpl, info_dict, *args, **kwargs): + outtmpl, info_dict = self.prepare_outtmpl(outtmpl, info_dict, *args, **kwargs) + return self.escape_outtmpl(outtmpl) % info_dict + + @_catch_unsafe_extension_error + def _prepare_filename(self, info_dict, *, outtmpl=None, tmpl_type=None): + assert None in (outtmpl, tmpl_type), 'outtmpl and tmpl_type are mutually exclusive' + if outtmpl is None: + outtmpl = self.params['outtmpl'].get(tmpl_type or 'default', self.params['outtmpl']['default']) + try: + outtmpl = self._outtmpl_expandpath(outtmpl) + filename = self.evaluate_outtmpl(outtmpl, info_dict, True) + if not filename: + return None + + if tmpl_type in ('', 'temp'): + final_ext, ext = self.params.get('final_ext'), info_dict.get('ext') + if final_ext and ext and final_ext != ext and filename.endswith(f'.{final_ext}'): + filename = replace_extension(filename, ext, final_ext) + elif tmpl_type: + force_ext = OUTTMPL_TYPES[tmpl_type] + if force_ext: + filename = replace_extension(filename, force_ext, info_dict.get('ext')) + + # https://github.com/blackjack4494/youtube-dlc/issues/85 + trim_file_name = self.params.get('trim_file_name', False) + if trim_file_name: + no_ext, *ext = filename.rsplit('.', 2) + filename = join_nonempty(no_ext[:trim_file_name], *ext, delim='.') + + return filename + except ValueError as err: + self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')') + return None + + def prepare_filename(self, info_dict, dir_type='', *, outtmpl=None, warn=False): + """Generate the output filename""" + if outtmpl: + assert not dir_type, 'outtmpl and dir_type are mutually exclusive' + dir_type = None + filename = self._prepare_filename(info_dict, tmpl_type=dir_type, outtmpl=outtmpl) + if not filename and dir_type not in ('', 'temp'): + return '' + + if warn: + if not self.params.get('paths'): + pass + elif filename == '-': + self.report_warning('--paths is ignored when an outputting to stdout', only_once=True) + elif os.path.isabs(filename): + self.report_warning('--paths is ignored since an absolute path is given in output template', only_once=True) + if filename == '-' or not filename: + return filename + + return self.get_output_path(dir_type, filename) + + def _match_entry(self, info_dict, incomplete=False, silent=False): + """Returns None if the file should be downloaded""" + _type = 'video' if 'playlist-match-filter' in self.params['compat_opts'] else info_dict.get('_type', 'video') + assert incomplete or _type == 'video', 'Only video result can be considered complete' + + video_title = info_dict.get('title', info_dict.get('id', 'entry')) + + def check_filter(): + if _type in ('playlist', 'multi_video'): + return + elif _type in ('url', 'url_transparent') and not try_call( + lambda: self.get_info_extractor(info_dict['ie_key']).is_single_video(info_dict['url'])): + return + + if 'title' in info_dict: + # This can happen when we're just evaluating the playlist + title = info_dict['title'] + matchtitle = self.params.get('matchtitle', False) + if matchtitle: + if not re.search(matchtitle, title, re.IGNORECASE): + return '"' + title + '" title did not match pattern "' + matchtitle + '"' + rejecttitle = self.params.get('rejecttitle', False) + if rejecttitle: + if re.search(rejecttitle, title, re.IGNORECASE): + return '"' + title + '" title matched reject pattern "' + rejecttitle + '"' + + date = info_dict.get('upload_date') + if date is not None: + date_range = self.params.get('daterange', DateRange()) + if date not in date_range: + return f'{date_from_str(date).isoformat()} upload date is not in range {date_range}' + view_count = info_dict.get('view_count') + if view_count is not None: + min_views = self.params.get('min_views') + if min_views is not None and view_count < min_views: + return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views) + max_views = self.params.get('max_views') + if max_views is not None and view_count > max_views: + return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views) + if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')): + return f'Skipping "{video_title}" because it is age restricted' + + match_filter = self.params.get('match_filter') + if match_filter is None: + return None + + cancelled = None + try: + try: + ret = match_filter(info_dict, incomplete=incomplete) + except TypeError: + # For backward compatibility + ret = None if incomplete else match_filter(info_dict) + except DownloadCancelled as err: + if err.msg is not NO_DEFAULT: + raise + ret, cancelled = err.msg, err + + if ret is NO_DEFAULT: + while True: + filename = self._format_screen(self.prepare_filename(info_dict), self.Styles.FILENAME) + self.to_screen( + self._format_screen(f'Download "{filename}"? (Y/n): ', self.Styles.EMPHASIS), + skip_eol=True) + reply = input().lower().strip() + if reply in {'y', ''}: + return None + elif reply == 'n': + if cancelled: + raise type(cancelled)(f'Skipping {video_title}') + return f'Skipping {video_title}' + return ret + + if self.in_download_archive(info_dict): + reason = ''.join(( + format_field(info_dict, 'id', f'{self._format_screen("%s", self.Styles.ID)}: '), + format_field(info_dict, 'title', f'{self._format_screen("%s", self.Styles.EMPHASIS)} '), + 'has already been recorded in the archive')) + break_opt, break_err = 'break_on_existing', ExistingVideoReached + else: + try: + reason = check_filter() + except DownloadCancelled as e: + reason, break_opt, break_err = e.msg, 'match_filter', type(e) + else: + break_opt, break_err = 'break_on_reject', RejectedVideoReached + if reason is not None: + if not silent: + self.to_screen('[download] ' + reason) + if self.params.get(break_opt, False): + raise break_err() + return reason + + @staticmethod + def add_extra_info(info_dict, extra_info): + """Set the keys from extra_info in info dict if they are missing""" + for key, value in extra_info.items(): + info_dict.setdefault(key, value) + + def extract_info(self, url, download=True, ie_key=None, extra_info=None, + process=True, force_generic_extractor=False): + """ + Extract and return the information dictionary of the URL + + Arguments: + @param url URL to extract + + Keyword arguments: + @param download Whether to download videos + @param process Whether to resolve all unresolved references (URLs, playlist items). + Must be True for download to work + @param ie_key Use only the extractor with this key + + @param extra_info Dictionary containing the extra values to add to the info (For internal use only) + @force_generic_extractor Force using the generic extractor (Deprecated; use ie_key='Generic') + """ + + if extra_info is None: + extra_info = {} + + if not ie_key and force_generic_extractor: + ie_key = 'Generic' + + if ie_key: + ies = {ie_key: self._ies[ie_key]} if ie_key in self._ies else {} + else: + ies = self._ies + + for key, ie in ies.items(): + if not ie.suitable(url): + continue + + if not ie.working(): + self.report_warning('The program functionality for this site has been marked as broken, ' + 'and will probably not work.') + + temp_id = ie.get_temp_id(url) + if temp_id is not None and self.in_download_archive({'id': temp_id, 'ie_key': key}): + self.to_screen(f'[download] {self._format_screen(temp_id, self.Styles.ID)}: ' + 'has already been recorded in the archive') + if self.params.get('break_on_existing', False): + raise ExistingVideoReached + break + return self.__extract_info(url, self.get_info_extractor(key), download, extra_info, process) + else: + extractors_restricted = self.params.get('allowed_extractors') not in (None, ['default']) + self.report_error(f'No suitable extractor{format_field(ie_key, None, " (%s)")} found for URL {url}', + tb=False if extractors_restricted else None) + + def _handle_extraction_exceptions(func): + @functools.wraps(func) + def wrapper(self, *args, **kwargs): + while True: + try: + return func(self, *args, **kwargs) + except (CookieLoadError, DownloadCancelled, LazyList.IndexError, PagedList.IndexError): + raise + except ReExtractInfo as e: + if e.expected: + self.to_screen(f'{e}; Re-extracting data') + else: + self.to_stderr('\r') + self.report_warning(f'{e}; Re-extracting data') + continue + except GeoRestrictedError as e: + msg = e.msg + if e.countries: + msg += '\nThis video is available in {}.'.format(', '.join( + map(ISO3166Utils.short2full, e.countries))) + msg += '\nYou might want to use a VPN or a proxy server (with --proxy) to workaround.' + self.report_error(msg) + except ExtractorError as e: # An error we somewhat expected + self.report_error(str(e), e.format_traceback()) + except Exception as e: + if self.params.get('ignoreerrors'): + self.report_error(str(e), tb=encode_compat_str(traceback.format_exc())) + else: + raise + break + return wrapper + + def _wait_for_video(self, ie_result={}): + if (not self.params.get('wait_for_video') + or ie_result.get('_type', 'video') != 'video' + or ie_result.get('formats') or ie_result.get('url')): + return + + format_dur = lambda dur: '%02d:%02d:%02d' % timetuple_from_msec(dur * 1000)[:-1] + last_msg = '' + + def progress(msg): + nonlocal last_msg + full_msg = f'{msg}\n' + if not self.params.get('noprogress'): + full_msg = msg + ' ' * (len(last_msg) - len(msg)) + '\r' + elif last_msg: + return + self.to_screen(full_msg, skip_eol=True) + last_msg = msg + + min_wait, max_wait = self.params.get('wait_for_video') + diff = try_get(ie_result, lambda x: x['release_timestamp'] - time.time()) + if diff is None and ie_result.get('live_status') == 'is_upcoming': + diff = round(random.uniform(min_wait, max_wait) if (max_wait and min_wait) else (max_wait or min_wait), 0) + self.report_warning('Release time of video is not known') + elif ie_result and (diff or 0) <= 0: + self.report_warning('Video should already be available according to extracted info') + diff = min(max(diff or 0, min_wait or 0), max_wait or float('inf')) + self.to_screen(f'[wait] Waiting for {format_dur(diff)} - Press Ctrl+C to try now') + + wait_till = time.time() + diff + try: + while True: + diff = wait_till - time.time() + if diff <= 0: + progress('') + raise ReExtractInfo('[wait] Wait period ended', expected=True) + progress(f'[wait] Remaining time until next attempt: {self._format_screen(format_dur(diff), self.Styles.EMPHASIS)}') + time.sleep(1) + except KeyboardInterrupt: + progress('') + raise ReExtractInfo('[wait] Interrupted by user', expected=True) + except BaseException as e: + if not isinstance(e, ReExtractInfo): + self.to_screen('') + raise + + def _load_cookies(self, data, *, autoscope=True): + """Loads cookies from a `Cookie` header + + This tries to work around the security vulnerability of passing cookies to every domain. + See: https://github.com/yt-dlp/yt-dlp/security/advisories/GHSA-v8mc-9377-rwjj + + @param data The Cookie header as string to load the cookies from + @param autoscope If `False`, scope cookies using Set-Cookie syntax and error for cookie without domains + If `True`, save cookies for later to be stored in the jar with a limited scope + If a URL, save cookies in the jar with the domain of the URL + """ + for cookie in LenientSimpleCookie(data).values(): + if autoscope and any(cookie.values()): + raise ValueError('Invalid syntax in Cookie Header') + + domain = cookie.get('domain') or '' + expiry = cookie.get('expires') + if expiry == '': # 0 is valid + expiry = None + prepared_cookie = http.cookiejar.Cookie( + cookie.get('version') or 0, cookie.key, cookie.value, None, False, + domain, True, True, cookie.get('path') or '', bool(cookie.get('path')), + cookie.get('secure') or False, expiry, False, None, None, {}) + + if domain: + self.cookiejar.set_cookie(prepared_cookie) + elif autoscope is True: + self.deprecated_feature( + 'Passing cookies as a header is a potential security risk; ' + 'they will be scoped to the domain of the downloaded urls. ' + 'Please consider loading cookies from a file or browser instead.') + self.__header_cookies.append(prepared_cookie) + elif autoscope: + self.report_warning( + 'The extractor result contains an unscoped cookie as an HTTP header. ' + f'If you are using yt-dlp with an input URL{bug_reports_message(before=",")}', + only_once=True) + self._apply_header_cookies(autoscope, [prepared_cookie]) + else: + self.report_error('Unscoped cookies are not allowed; please specify some sort of scoping', + tb=False, is_error=False) + + def _apply_header_cookies(self, url, cookies=None): + """Applies stray header cookies to the provided url + + This loads header cookies and scopes them to the domain provided in `url`. + While this is not ideal, it helps reduce the risk of them being sent + to an unintended destination while mostly maintaining compatibility. + """ + parsed = urllib.parse.urlparse(url) + if not parsed.hostname: + return + + for cookie in map(copy.copy, cookies or self.__header_cookies): + cookie.domain = f'.{parsed.hostname}' + self.cookiejar.set_cookie(cookie) + + @_handle_extraction_exceptions + def __extract_info(self, url, ie, download, extra_info, process): + self._apply_header_cookies(url) + + try: + ie_result = ie.extract(url) + except UserNotLive as e: + if process: + if self.params.get('wait_for_video'): + self.report_warning(e) + self._wait_for_video() + raise + if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here) + self.report_warning(f'Extractor {ie.IE_NAME} returned nothing{bug_reports_message()}') + return + if isinstance(ie_result, list): + # Backwards compatibility: old IE result format + ie_result = { + '_type': 'compat_list', + 'entries': ie_result, + } + if extra_info.get('original_url'): + ie_result.setdefault('original_url', extra_info['original_url']) + self.add_default_extra_info(ie_result, ie, url) + if process: + self._wait_for_video(ie_result) + return self.process_ie_result(ie_result, download, extra_info) + else: + return ie_result + + def add_default_extra_info(self, ie_result, ie, url): + if url is not None: + self.add_extra_info(ie_result, { + 'webpage_url': url, + 'original_url': url, + }) + webpage_url = ie_result.get('webpage_url') + if webpage_url: + self.add_extra_info(ie_result, { + 'webpage_url_basename': url_basename(webpage_url), + 'webpage_url_domain': get_domain(webpage_url), + }) + if ie is not None: + self.add_extra_info(ie_result, { + 'extractor': ie.IE_NAME, + 'extractor_key': ie.ie_key(), + }) + + def process_ie_result(self, ie_result, download=True, extra_info=None): + """ + Take the result of the ie(may be modified) and resolve all unresolved + references (URLs, playlist items). + + It will also download the videos if 'download'. + Returns the resolved ie_result. + """ + if extra_info is None: + extra_info = {} + result_type = ie_result.get('_type', 'video') + + if result_type in ('url', 'url_transparent'): + ie_result['url'] = sanitize_url( + ie_result['url'], scheme='http' if self.params.get('prefer_insecure') else 'https') + if ie_result.get('original_url') and not extra_info.get('original_url'): + extra_info = {'original_url': ie_result['original_url'], **extra_info} + + extract_flat = self.params.get('extract_flat', False) + if ((extract_flat == 'in_playlist' and 'playlist' in extra_info) + or extract_flat is True): + info_copy = ie_result.copy() + ie = try_get(ie_result.get('ie_key'), self.get_info_extractor) + if ie and not ie_result.get('id'): + info_copy['id'] = ie.get_temp_id(ie_result['url']) + self.add_default_extra_info(info_copy, ie, ie_result['url']) + self.add_extra_info(info_copy, extra_info) + info_copy, _ = self.pre_process(info_copy) + self._fill_common_fields(info_copy, False) + self.__forced_printings(info_copy) + self._raise_pending_errors(info_copy) + if self.params.get('force_write_download_archive', False): + self.record_download_archive(info_copy) + return ie_result + + if result_type == 'video': + self.add_extra_info(ie_result, extra_info) + ie_result = self.process_video_result(ie_result, download=download) + self._raise_pending_errors(ie_result) + additional_urls = (ie_result or {}).get('additional_urls') + if additional_urls: + # TODO: Improve MetadataParserPP to allow setting a list + if isinstance(additional_urls, str): + additional_urls = [additional_urls] + self.to_screen( + '[info] {}: {} additional URL(s) requested'.format(ie_result['id'], len(additional_urls))) + self.write_debug('Additional URLs: "{}"'.format('", "'.join(additional_urls))) + ie_result['additional_entries'] = [ + self.extract_info( + url, download, extra_info=extra_info, + force_generic_extractor=self.params.get('force_generic_extractor')) + for url in additional_urls + ] + return ie_result + elif result_type == 'url': + # We have to add extra_info to the results because it may be + # contained in a playlist + return self.extract_info( + ie_result['url'], download, + ie_key=ie_result.get('ie_key'), + extra_info=extra_info) + elif result_type == 'url_transparent': + # Use the information from the embedding page + info = self.extract_info( + ie_result['url'], ie_key=ie_result.get('ie_key'), + extra_info=extra_info, download=False, process=False) + + # extract_info may return None when ignoreerrors is enabled and + # extraction failed with an error, don't crash and return early + # in this case + if not info: + return info + + exempted_fields = {'_type', 'url', 'ie_key'} + if not ie_result.get('section_end') and ie_result.get('section_start') is None: + # For video clips, the id etc of the clip extractor should be used + exempted_fields |= {'id', 'extractor', 'extractor_key'} + + new_result = info.copy() + new_result.update(filter_dict(ie_result, lambda k, v: v is not None and k not in exempted_fields)) + + # Extracted info may not be a video result (i.e. + # info.get('_type', 'video') != video) but rather an url or + # url_transparent. In such cases outer metadata (from ie_result) + # should be propagated to inner one (info). For this to happen + # _type of info should be overridden with url_transparent. This + # fixes issue from https://github.com/ytdl-org/youtube-dl/pull/11163. + if new_result.get('_type') == 'url': + new_result['_type'] = 'url_transparent' + + return self.process_ie_result( + new_result, download=download, extra_info=extra_info) + elif result_type in ('playlist', 'multi_video'): + # Protect from infinite recursion due to recursively nested playlists + # (see https://github.com/ytdl-org/youtube-dl/issues/27833) + webpage_url = ie_result.get('webpage_url') # Playlists maynot have webpage_url + if webpage_url and webpage_url in self._playlist_urls: + self.to_screen( + '[download] Skipping already downloaded playlist: {}'.format( + ie_result.get('title')) or ie_result.get('id')) + return + + self._playlist_level += 1 + self._playlist_urls.add(webpage_url) + self._fill_common_fields(ie_result, False) + self._sanitize_thumbnails(ie_result) + try: + return self.__process_playlist(ie_result, download) + finally: + self._playlist_level -= 1 + if not self._playlist_level: + self._playlist_urls.clear() + elif result_type == 'compat_list': + self.report_warning( + 'Extractor {} returned a compat_list result. ' + 'It needs to be updated.'.format(ie_result.get('extractor'))) + + def _fixup(r): + self.add_extra_info(r, { + 'extractor': ie_result['extractor'], + 'webpage_url': ie_result['webpage_url'], + 'webpage_url_basename': url_basename(ie_result['webpage_url']), + 'webpage_url_domain': get_domain(ie_result['webpage_url']), + 'extractor_key': ie_result['extractor_key'], + }) + return r + ie_result['entries'] = [ + self.process_ie_result(_fixup(r), download, extra_info) + for r in ie_result['entries'] + ] + return ie_result + else: + raise Exception(f'Invalid result type: {result_type}') + + def _ensure_dir_exists(self, path): + return make_dir(path, self.report_error) + + @staticmethod + def _playlist_infodict(ie_result, strict=False, **kwargs): + info = { + 'playlist_count': ie_result.get('playlist_count'), + 'playlist': ie_result.get('title') or ie_result.get('id'), + 'playlist_id': ie_result.get('id'), + 'playlist_title': ie_result.get('title'), + 'playlist_uploader': ie_result.get('uploader'), + 'playlist_uploader_id': ie_result.get('uploader_id'), + 'playlist_channel': ie_result.get('channel'), + 'playlist_channel_id': ie_result.get('channel_id'), + 'playlist_webpage_url': ie_result.get('webpage_url'), + **kwargs, + } + if strict: + return info + if ie_result.get('webpage_url'): + info.update({ + 'webpage_url': ie_result['webpage_url'], + 'webpage_url_basename': url_basename(ie_result['webpage_url']), + 'webpage_url_domain': get_domain(ie_result['webpage_url']), + }) + return { + **info, + 'playlist_index': 0, + '__last_playlist_index': max(ie_result.get('requested_entries') or (0, 0)), + 'extractor': ie_result['extractor'], + 'extractor_key': ie_result['extractor_key'], + } + + def __process_playlist(self, ie_result, download): + """Process each entry in the playlist""" + assert ie_result['_type'] in ('playlist', 'multi_video') + + common_info = self._playlist_infodict(ie_result, strict=True) + title = common_info.get('playlist') or '' + if self._match_entry(common_info, incomplete=True) is not None: + return + self.to_screen(f'[download] Downloading {ie_result["_type"]}: {title}') + + all_entries = PlaylistEntries(self, ie_result) + entries = orderedSet(all_entries.get_requested_items(), lazy=True) + + lazy = self.params.get('lazy_playlist') + if lazy: + resolved_entries, n_entries = [], 'N/A' + ie_result['requested_entries'], ie_result['entries'] = None, None + else: + entries = resolved_entries = list(entries) + n_entries = len(resolved_entries) + ie_result['requested_entries'], ie_result['entries'] = tuple(zip(*resolved_entries, strict=True)) or ([], []) + if not ie_result.get('playlist_count'): + # Better to do this after potentially exhausting entries + ie_result['playlist_count'] = all_entries.get_full_count() + + extra = self._playlist_infodict(ie_result, n_entries=int_or_none(n_entries)) + ie_copy = collections.ChainMap(ie_result, extra) + + _infojson_written = False + write_playlist_files = self.params.get('allow_playlist_files', True) + if write_playlist_files and self.params.get('list_thumbnails'): + self.list_thumbnails(ie_result) + if write_playlist_files and not self.params.get('simulate'): + _infojson_written = self._write_info_json( + 'playlist', ie_result, self.prepare_filename(ie_copy, 'pl_infojson')) + if _infojson_written is None: + return + if self._write_description('playlist', ie_result, + self.prepare_filename(ie_copy, 'pl_description')) is None: + return + # TODO: This should be passed to ThumbnailsConvertor if necessary + self._write_thumbnails('playlist', ie_result, self.prepare_filename(ie_copy, 'pl_thumbnail')) + + if lazy: + if self.params.get('playlistreverse') or self.params.get('playlistrandom'): + self.report_warning('playlistreverse and playlistrandom are not supported with lazy_playlist', only_once=True) + elif self.params.get('playlistreverse'): + entries.reverse() + elif self.params.get('playlistrandom'): + random.shuffle(entries) + + self.to_screen(f'[{ie_result["extractor"]}] Playlist {title}: Downloading {n_entries} items' + f'{format_field(ie_result, "playlist_count", " of %s")}') + + keep_resolved_entries = self.params.get('extract_flat') != 'discard' + if self.params.get('extract_flat') == 'discard_in_playlist': + keep_resolved_entries = ie_result['_type'] != 'playlist' + if keep_resolved_entries: + self.write_debug('The information of all playlist entries will be held in memory') + + failures = 0 + max_failures = self.params.get('skip_playlist_after_errors') or float('inf') + for i, (playlist_index, entry) in enumerate(entries): + if lazy: + resolved_entries.append((playlist_index, entry)) + if not entry: + continue + + entry['__x_forwarded_for_ip'] = ie_result.get('__x_forwarded_for_ip') + if not lazy and 'playlist-index' in self.params['compat_opts']: + playlist_index = ie_result['requested_entries'][i] + + entry_copy = collections.ChainMap(entry, { + **common_info, + 'n_entries': int_or_none(n_entries), + 'playlist_index': playlist_index, + 'playlist_autonumber': i + 1, + }) + + if self._match_entry(entry_copy, incomplete=True) is not None: + # For compatabilty with youtube-dl. See https://github.com/yt-dlp/yt-dlp/issues/4369 + resolved_entries[i] = (playlist_index, NO_DEFAULT) + continue + + self.to_screen( + f'[download] Downloading item {self._format_screen(i + 1, self.Styles.ID)} ' + f'of {self._format_screen(n_entries, self.Styles.EMPHASIS)}') + + entry_result = self.__process_iterable_entry(entry, download, collections.ChainMap({ + 'playlist_index': playlist_index, + 'playlist_autonumber': i + 1, + }, extra)) + if not entry_result: + failures += 1 + if failures >= max_failures: + self.report_error( + f'Skipping the remaining entries in playlist "{title}" since {failures} items failed extraction') + break + if keep_resolved_entries: + resolved_entries[i] = (playlist_index, entry_result) + + # Update with processed data + ie_result['entries'] = [e for _, e in resolved_entries if e is not NO_DEFAULT] + ie_result['requested_entries'] = [i for i, e in resolved_entries if e is not NO_DEFAULT] + if ie_result['requested_entries'] == try_call(lambda: list(range(1, ie_result['playlist_count'] + 1))): + # Do not set for full playlist + ie_result.pop('requested_entries') + + # Write the updated info to json + if _infojson_written is True and self._write_info_json( + 'updated playlist', ie_result, + self.prepare_filename(ie_copy, 'pl_infojson'), overwrite=True) is None: + return + + ie_result = self.run_all_pps('playlist', ie_result) + self.to_screen(f'[download] Finished downloading playlist: {title}') + return ie_result + + @_handle_extraction_exceptions + def __process_iterable_entry(self, entry, download, extra_info): + return self.process_ie_result( + entry, download=download, extra_info=extra_info) + + def _build_format_filter(self, filter_spec): + " Returns a function to filter the formats according to the filter_spec " + + OPERATORS = { + '<': operator.lt, + '<=': operator.le, + '>': operator.gt, + '>=': operator.ge, + '=': operator.eq, + '!=': operator.ne, + } + operator_rex = re.compile(r'''(?x)\s* + (?P[\w.-]+)\s* + (?P{})(?P\s*\?)?\s* + (?P[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)\s* + '''.format('|'.join(map(re.escape, OPERATORS.keys())))) + m = operator_rex.fullmatch(filter_spec) + if m: + try: + comparison_value = float(m.group('value')) + except ValueError: + comparison_value = parse_filesize(m.group('value')) + if comparison_value is None: + comparison_value = parse_filesize(m.group('value') + 'B') + if comparison_value is None: + raise ValueError( + 'Invalid value {!r} in format specification {!r}'.format( + m.group('value'), filter_spec)) + op = OPERATORS[m.group('op')] + + if not m: + STR_OPERATORS = { + '=': operator.eq, + '^=': lambda attr, value: attr.startswith(value), + '$=': lambda attr, value: attr.endswith(value), + '*=': lambda attr, value: value in attr, + '~=': lambda attr, value: value.search(attr) is not None, + } + str_operator_rex = re.compile(r'''(?x)\s* + (?P[a-zA-Z0-9._-]+)\s* + (?P!\s*)?(?P{})\s*(?P\?\s*)? + (?P["'])? + (?P(?(quote)(?:(?!(?P=quote))[^\\]|\\.)+|[\w.-]+)) + (?(quote)(?P=quote))\s* + '''.format('|'.join(map(re.escape, STR_OPERATORS.keys())))) + m = str_operator_rex.fullmatch(filter_spec) + if m: + if m.group('op') == '~=': + comparison_value = re.compile(m.group('value')) + else: + comparison_value = re.sub(r'''\\([\\"'])''', r'\1', m.group('value')) + str_op = STR_OPERATORS[m.group('op')] + if m.group('negation'): + op = lambda attr, value: not str_op(attr, value) + else: + op = str_op + + if not m: + raise SyntaxError(f'Invalid filter specification {filter_spec!r}') + + def _filter(f): + actual_value = f.get(m.group('key')) + if actual_value is None: + return m.group('none_inclusive') + return op(actual_value, comparison_value) + return _filter + + def _check_formats(self, formats, warning=True): + for f in formats: + working = f.get('__working') + if working is not None: + if working: + yield f + continue + self.to_screen('[info] Testing format {}'.format(f['format_id'])) + path = self.get_output_path('temp') + if not self._ensure_dir_exists(f'{path}/'): + continue + temp_file = tempfile.NamedTemporaryFile(suffix='.tmp', delete=False, dir=path or None) + temp_file.close() + # If FragmentFD fails when testing a fragment, it will wrongly set a non-zero return code. + # Save the actual return code for later. See https://github.com/yt-dlp/yt-dlp/issues/13750 + original_retcode = self._download_retcode + try: + success, _ = self.dl(temp_file.name, f, test=True) + except (DownloadError, OSError, ValueError, *network_exceptions): + success = False + finally: + if os.path.exists(temp_file.name): + try: + os.remove(temp_file.name) + except OSError: + self.report_warning(f'Unable to delete temporary file "{temp_file.name}"') + # Restore the actual return code + self._download_retcode = original_retcode + f['__working'] = success + if success: + f.pop('__needs_testing', None) + yield f + else: + msg = f'Unable to download format {f["format_id"]}. Skipping...' + if warning: + self.report_warning(msg) + else: + self.to_screen(f'[info] {msg}') + + def _select_formats(self, formats, selector): + return list(selector({ + 'formats': formats, + 'has_merged_format': any('none' not in (f.get('acodec'), f.get('vcodec')) for f in formats), + 'incomplete_formats': (all(f.get('vcodec') == 'none' for f in formats) # No formats with video + or all(f.get('acodec') == 'none' for f in formats)), # OR, No formats with audio + })) + + def _default_format_spec(self, info_dict): + prefer_best = ( + self.params['outtmpl']['default'] == '-' + or (info_dict.get('is_live') and not self.params.get('live_from_start'))) + + def can_merge(): + merger = FFmpegMergerPP(self) + return merger.available and merger.can_merge() + + if not prefer_best and not can_merge(): + prefer_best = True + formats = self._get_formats(info_dict) + evaluate_formats = lambda spec: self._select_formats(formats, self.build_format_selector(spec)) + if evaluate_formats('b/bv+ba') != evaluate_formats('bv*+ba/b'): + self.report_warning('ffmpeg not found. The downloaded format may not be the best available. ' + 'Installing ffmpeg is strongly recommended: https://github.com/yt-dlp/yt-dlp#dependencies') + + compat = (self.params.get('allow_multiple_audio_streams') + or 'format-spec' in self.params['compat_opts']) + + return ('best/bestvideo+bestaudio' if prefer_best + else 'bestvideo+bestaudio/best' if compat + else 'bestvideo*+bestaudio/best') + + def build_format_selector(self, format_spec): + def syntax_error(note, start): + message = ( + 'Invalid format specification: ' + '{}\n\t{}\n\t{}^'.format(note, format_spec, ' ' * start[1])) + return SyntaxError(message) + + PICKFIRST = 'PICKFIRST' + MERGE = 'MERGE' + SINGLE = 'SINGLE' + GROUP = 'GROUP' + FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters']) + + allow_multiple_streams = {'audio': self.params.get('allow_multiple_audio_streams', False), + 'video': self.params.get('allow_multiple_video_streams', False)} + + def _parse_filter(tokens): + filter_parts = [] + for type_, string_, _start, _, _ in tokens: + if type_ == tokenize.OP and string_ == ']': + return ''.join(filter_parts) + else: + filter_parts.append(string_) + + def _remove_unused_ops(tokens): + # Remove operators that we don't use and join them with the surrounding strings. + # E.g. 'mp4' '-' 'baseline' '-' '16x9' is converted to 'mp4-baseline-16x9' + ALLOWED_OPS = ('/', '+', ',', '(', ')') + last_string, last_start, last_end, last_line = None, None, None, None + for type_, string_, start, end, line in tokens: + if type_ == tokenize.OP and string_ == '[': + if last_string: + yield tokenize.NAME, last_string, last_start, last_end, last_line + last_string = None + yield type_, string_, start, end, line + # everything inside brackets will be handled by _parse_filter + for type_, string_, start, end, line in tokens: + yield type_, string_, start, end, line + if type_ == tokenize.OP and string_ == ']': + break + elif type_ == tokenize.OP and string_ in ALLOWED_OPS: + if last_string: + yield tokenize.NAME, last_string, last_start, last_end, last_line + last_string = None + yield type_, string_, start, end, line + elif type_ in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]: + if not last_string: + last_string = string_ + last_start = start + last_end = end + else: + last_string += string_ + if last_string: + yield tokenize.NAME, last_string, last_start, last_end, last_line + + def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False): + selectors = [] + current_selector = None + for type_, string_, start, _, _ in tokens: + # ENCODING is only defined in Python 3.x + if type_ == getattr(tokenize, 'ENCODING', None): + continue + elif type_ in [tokenize.NAME, tokenize.NUMBER]: + current_selector = FormatSelector(SINGLE, string_, []) + elif type_ == tokenize.OP: + if string_ == ')': + if not inside_group: + # ')' will be handled by the parentheses group + tokens.restore_last_token() + break + elif inside_merge and string_ in ['/', ',']: + tokens.restore_last_token() + break + elif inside_choice and string_ == ',': + tokens.restore_last_token() + break + elif string_ == ',': + if not current_selector: + raise syntax_error('"," must follow a format selector', start) + selectors.append(current_selector) + current_selector = None + elif string_ == '/': + if not current_selector: + raise syntax_error('"/" must follow a format selector', start) + first_choice = current_selector + second_choice = _parse_format_selection(tokens, inside_choice=True) + current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), []) + elif string_ == '[': + if not current_selector: + current_selector = FormatSelector(SINGLE, 'best', []) + format_filter = _parse_filter(tokens) + current_selector.filters.append(format_filter) + elif string_ == '(': + if current_selector: + raise syntax_error('Unexpected "("', start) + group = _parse_format_selection(tokens, inside_group=True) + current_selector = FormatSelector(GROUP, group, []) + elif string_ == '+': + if not current_selector: + raise syntax_error('Unexpected "+"', start) + selector_1 = current_selector + selector_2 = _parse_format_selection(tokens, inside_merge=True) + if not selector_2: + raise syntax_error('Expected a selector', start) + current_selector = FormatSelector(MERGE, (selector_1, selector_2), []) + else: + raise syntax_error(f'Operator not recognized: "{string_}"', start) + elif type_ == tokenize.ENDMARKER: + break + if current_selector: + selectors.append(current_selector) + return selectors + + def _merge(formats_pair): + format_1, format_2 = formats_pair + + formats_info = [] + formats_info.extend(format_1.get('requested_formats', (format_1,))) + formats_info.extend(format_2.get('requested_formats', (format_2,))) + + if not allow_multiple_streams['video'] or not allow_multiple_streams['audio']: + get_no_more = {'video': False, 'audio': False} + for (i, fmt_info) in enumerate(formats_info): + if fmt_info.get('acodec') == fmt_info.get('vcodec') == 'none': + formats_info.pop(i) + continue + for aud_vid in ['audio', 'video']: + if not allow_multiple_streams[aud_vid] and fmt_info.get(aud_vid[0] + 'codec') != 'none': + if get_no_more[aud_vid]: + formats_info.pop(i) + break + get_no_more[aud_vid] = True + + if len(formats_info) == 1: + return formats_info[0] + + video_fmts = [fmt_info for fmt_info in formats_info if fmt_info.get('vcodec') != 'none'] + audio_fmts = [fmt_info for fmt_info in formats_info if fmt_info.get('acodec') != 'none'] + + the_only_video = video_fmts[0] if len(video_fmts) == 1 else None + the_only_audio = audio_fmts[0] if len(audio_fmts) == 1 else None + + output_ext = get_compatible_ext( + vcodecs=[f.get('vcodec') for f in video_fmts], + acodecs=[f.get('acodec') for f in audio_fmts], + vexts=[f['ext'] for f in video_fmts], + aexts=[f['ext'] for f in audio_fmts], + preferences=(try_call(lambda: self.params['merge_output_format'].split('/')) + or (self.params.get('prefer_free_formats') and ('webm', 'mkv')))) + + filtered = lambda *keys: filter(None, (traverse_obj(fmt, *keys) for fmt in formats_info)) + + new_dict = { + 'requested_formats': formats_info, + 'format': '+'.join(filtered('format')), + 'format_id': '+'.join(filtered('format_id')), + 'ext': output_ext, + 'protocol': '+'.join(map(determine_protocol, formats_info)), + 'language': '+'.join(orderedSet(filtered('language'))) or None, + 'format_note': '+'.join(orderedSet(filtered('format_note'))) or None, + 'filesize_approx': sum(filtered('filesize', 'filesize_approx')) or None, + 'tbr': sum(filtered('tbr', 'vbr', 'abr')), + } + + if the_only_video: + new_dict.update({ + 'width': the_only_video.get('width'), + 'height': the_only_video.get('height'), + 'resolution': the_only_video.get('resolution') or self.format_resolution(the_only_video), + 'fps': the_only_video.get('fps'), + 'dynamic_range': the_only_video.get('dynamic_range'), + 'vcodec': the_only_video.get('vcodec'), + 'vbr': the_only_video.get('vbr'), + 'stretched_ratio': the_only_video.get('stretched_ratio'), + 'aspect_ratio': the_only_video.get('aspect_ratio'), + }) + + if the_only_audio: + new_dict.update({ + 'acodec': the_only_audio.get('acodec'), + 'abr': the_only_audio.get('abr'), + 'asr': the_only_audio.get('asr'), + 'audio_channels': the_only_audio.get('audio_channels'), + }) + + return new_dict + + def _check_formats(formats): + if self.params.get('check_formats') == 'selected': + yield from self._check_formats(formats) + return + elif (self.params.get('check_formats') is not None + or self.params.get('allow_unplayable_formats')): + yield from formats + return + + for f in formats: + if f.get('has_drm') or f.get('__needs_testing'): + yield from self._check_formats([f]) + else: + yield f + + def _build_selector_function(selector): + if isinstance(selector, list): # , + fs = [_build_selector_function(s) for s in selector] + + def selector_function(ctx): + for f in fs: + yield from f(ctx) + return selector_function + + elif selector.type == GROUP: # () + selector_function = _build_selector_function(selector.selector) + + elif selector.type == PICKFIRST: # / + fs = [_build_selector_function(s) for s in selector.selector] + + def selector_function(ctx): + for f in fs: + picked_formats = list(f(ctx)) + if picked_formats: + return picked_formats + return [] + + elif selector.type == MERGE: # + + selector_1, selector_2 = map(_build_selector_function, selector.selector) + + def selector_function(ctx): + for pair in itertools.product(selector_1(ctx), selector_2(ctx)): + yield _merge(pair) + + elif selector.type == SINGLE: # atom + format_spec = selector.selector or 'best' + + # TODO: Add allvideo, allaudio etc by generalizing the code with best/worst selector + if format_spec == 'all': + def selector_function(ctx): + yield from _check_formats(ctx['formats'][::-1]) + elif format_spec == 'mergeall': + def selector_function(ctx): + formats = list(_check_formats( + f for f in ctx['formats'] if f.get('vcodec') != 'none' or f.get('acodec') != 'none')) + if not formats: + return + merged_format = formats[-1] + for f in formats[-2::-1]: + merged_format = _merge((merged_format, f)) + yield merged_format + + else: + format_fallback, seperate_fallback, format_reverse, format_idx = False, None, True, 1 + mobj = re.match( + r'(?Pbest|worst|b|w)(?Pvideo|audio|v|a)?(?P\*)?(?:\.(?P[1-9]\d*))?$', + format_spec) + if mobj is not None: + format_idx = int_or_none(mobj.group('n'), default=1) + format_reverse = mobj.group('bw')[0] == 'b' + format_type = (mobj.group('type') or [None])[0] + not_format_type = {'v': 'a', 'a': 'v'}.get(format_type) + format_modified = mobj.group('mod') is not None + + format_fallback = not format_type and not format_modified # for b, w + _filter_f = ( + (lambda f: f.get(f'{format_type}codec') != 'none') + if format_type and format_modified # bv*, ba*, wv*, wa* + else (lambda f: f.get(f'{not_format_type}codec') == 'none') + if format_type # bv, ba, wv, wa + else (lambda f: f.get('vcodec') != 'none' and f.get('acodec') != 'none') + if not format_modified # b, w + else lambda f: True) # b*, w* + filter_f = lambda f: _filter_f(f) and ( + f.get('vcodec') != 'none' or f.get('acodec') != 'none') + else: + if format_spec in self._format_selection_exts['audio']: + filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') != 'none' + elif format_spec in self._format_selection_exts['video']: + filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') != 'none' and f.get('vcodec') != 'none' + seperate_fallback = lambda f: f.get('ext') == format_spec and f.get('vcodec') != 'none' + elif format_spec in self._format_selection_exts['storyboards']: + filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') == 'none' and f.get('vcodec') == 'none' + else: + filter_f = lambda f: f.get('format_id') == format_spec # id + + def selector_function(ctx): + formats = list(ctx['formats']) + matches = list(filter(filter_f, formats)) if filter_f is not None else formats + if not matches: + if format_fallback and ctx['incomplete_formats']: + # for extractors with incomplete formats (audio only (soundcloud) + # or video only (imgur)) best/worst will fallback to + # best/worst {video,audio}-only format + matches = list(filter(lambda f: f.get('vcodec') != 'none' or f.get('acodec') != 'none', formats)) + elif seperate_fallback and not ctx['has_merged_format']: + # for compatibility with youtube-dl when there is no pre-merged format + matches = list(filter(seperate_fallback, formats)) + matches = LazyList(_check_formats(matches[::-1 if format_reverse else 1])) + try: + yield matches[format_idx - 1] + except LazyList.IndexError: + return + + filters = [self._build_format_filter(f) for f in selector.filters] + + def final_selector(ctx): + ctx_copy = dict(ctx) + for _filter in filters: + ctx_copy['formats'] = list(filter(_filter, ctx_copy['formats'])) + return selector_function(ctx_copy) + return final_selector + + # HACK: Python 3.12 changed the underlying parser, rendering '7_a' invalid + # Prefix numbers with random letters to avoid it being classified as a number + # See: https://github.com/yt-dlp/yt-dlp/pulls/8797 + # TODO: Implement parser not reliant on tokenize.tokenize + prefix = ''.join(random.choices(string.ascii_letters, k=32)) + stream = io.BytesIO(re.sub(r'\d[_\d]*', rf'{prefix}\g<0>', format_spec).encode()) + try: + tokens = list(_remove_unused_ops( + token._replace(string=token.string.replace(prefix, '')) + for token in tokenize.tokenize(stream.readline))) + except tokenize.TokenError: + raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec))) + + class TokenIterator: + def __init__(self, tokens): + self.tokens = tokens + self.counter = 0 + + def __iter__(self): + return self + + def __next__(self): + if self.counter >= len(self.tokens): + raise StopIteration + value = self.tokens[self.counter] + self.counter += 1 + return value + + next = __next__ + + def restore_last_token(self): + self.counter -= 1 + + parsed_selector = _parse_format_selection(iter(TokenIterator(tokens))) + return _build_selector_function(parsed_selector) + + def _calc_headers(self, info_dict, load_cookies=False): + res = HTTPHeaderDict(self.params['http_headers'], info_dict.get('http_headers')) + clean_headers(res) + + if load_cookies: # For --load-info-json + self._load_cookies(res.get('Cookie'), autoscope=info_dict['url']) # compat + self._load_cookies(info_dict.get('cookies'), autoscope=False) + # The `Cookie` header is removed to prevent leaks and unscoped cookies. + # See: https://github.com/yt-dlp/yt-dlp/security/advisories/GHSA-v8mc-9377-rwjj + res.pop('Cookie', None) + cookies = self.cookiejar.get_cookies_for_url(info_dict['url']) + if cookies: + encoder = LenientSimpleCookie() + values = [] + for cookie in cookies: + _, value = encoder.value_encode(cookie.value) + values.append(f'{cookie.name}={value}') + if cookie.domain: + values.append(f'Domain={cookie.domain}') + if cookie.path: + values.append(f'Path={cookie.path}') + if cookie.secure: + values.append('Secure') + if cookie.expires: + values.append(f'Expires={cookie.expires}') + if cookie.version: + values.append(f'Version={cookie.version}') + info_dict['cookies'] = '; '.join(values) + + if 'X-Forwarded-For' not in res: + x_forwarded_for_ip = info_dict.get('__x_forwarded_for_ip') + if x_forwarded_for_ip: + res['X-Forwarded-For'] = x_forwarded_for_ip + + return res + + def _calc_cookies(self, url): + self.deprecation_warning('"YoutubeDL._calc_cookies" is deprecated and may be removed in a future version') + return self.cookiejar.get_cookie_header(url) + + def _sort_thumbnails(self, thumbnails): + thumbnails.sort(key=lambda t: ( + t.get('preference') if t.get('preference') is not None else -1, + t.get('width') if t.get('width') is not None else -1, + t.get('height') if t.get('height') is not None else -1, + t.get('id') if t.get('id') is not None else '', + t.get('url'))) + + def _sanitize_thumbnails(self, info_dict): + thumbnails = info_dict.get('thumbnails') + if thumbnails is None: + thumbnail = info_dict.get('thumbnail') + if thumbnail: + info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}] + if not thumbnails: + return + + def check_thumbnails(thumbnails): + for t in thumbnails: + self.to_screen(f'[info] Testing thumbnail {t["id"]}') + try: + self.urlopen(HEADRequest(t['url'])) + except network_exceptions as err: + self.to_screen(f'[info] Unable to connect to thumbnail {t["id"]} URL {t["url"]!r} - {err}. Skipping...') + continue + yield t + + self._sort_thumbnails(thumbnails) + for i, t in enumerate(thumbnails): + if t.get('id') is None: + t['id'] = str(i) + if t.get('width') and t.get('height'): + t['resolution'] = '%dx%d' % (t['width'], t['height']) + t['url'] = sanitize_url(t['url']) + + if self.params.get('check_formats') is True: + info_dict['thumbnails'] = LazyList(check_thumbnails(thumbnails[::-1]), reverse=True) + else: + info_dict['thumbnails'] = thumbnails + + def _fill_common_fields(self, info_dict, final=True): + # TODO: move sanitization here + if final: + title = info_dict['fulltitle'] = info_dict.get('title') + if not title: + if title == '': + self.write_debug('Extractor gave empty title. Creating a generic title') + else: + self.report_warning('Extractor failed to obtain "title". Creating a generic title instead') + info_dict['title'] = f'{info_dict["extractor"].replace(":", "-")} video #{info_dict["id"]}' + + if info_dict.get('duration') is not None: + info_dict['duration_string'] = formatSeconds(info_dict['duration']) + + for ts_key, date_key in ( + ('timestamp', 'upload_date'), + ('release_timestamp', 'release_date'), + ('modified_timestamp', 'modified_date'), + ): + if info_dict.get(date_key) is None and info_dict.get(ts_key) is not None: + info_dict[date_key] = strftime_or_none(info_dict[ts_key]) + + if not info_dict.get('release_year'): + info_dict['release_year'] = traverse_obj(info_dict, ('release_date', {lambda x: int(x[:4])})) + + live_keys = ('is_live', 'was_live') + live_status = info_dict.get('live_status') + if live_status is None: + for key in live_keys: + if info_dict.get(key) is False: + continue + if info_dict.get(key): + live_status = key + break + if all(info_dict.get(key) is False for key in live_keys): + live_status = 'not_live' + if live_status: + info_dict['live_status'] = live_status + for key in live_keys: + if info_dict.get(key) is None: + info_dict[key] = (live_status == key) + if live_status == 'post_live': + info_dict['was_live'] = True + + # Auto generate title fields corresponding to the *_number fields when missing + # in order to always have clean titles. This is very common for TV series. + for field in ('chapter', 'season', 'episode'): + if final and info_dict.get(f'{field}_number') is not None and not info_dict.get(field): + info_dict[field] = '%s %d' % (field.capitalize(), info_dict[f'{field}_number']) + + for old_key, new_key in self._deprecated_multivalue_fields.items(): + if new_key in info_dict and old_key in info_dict: + if '_version' not in info_dict: # HACK: Do not warn when using --load-info-json + self.deprecation_warning(f'Do not return {old_key!r} when {new_key!r} is present') + elif old_value := info_dict.get(old_key): + info_dict[new_key] = old_value.split(', ') + elif new_value := info_dict.get(new_key): + info_dict[old_key] = ', '.join(v.replace(',', '\N{FULLWIDTH COMMA}') for v in new_value) + + def _raise_pending_errors(self, info): + err = info.pop('__pending_error', None) + if err: + self.report_error(err, tb=False) + + def sort_formats(self, info_dict): + formats = self._get_formats(info_dict) + formats.sort(key=FormatSorter( + self, info_dict.get('_format_sort_fields') or []).calculate_preference) + + def process_video_result(self, info_dict, download=True): + assert info_dict.get('_type', 'video') == 'video' + self._num_videos += 1 + + if 'id' not in info_dict: + raise ExtractorError('Missing "id" field in extractor result', ie=info_dict['extractor']) + elif not info_dict.get('id'): + raise ExtractorError('Extractor failed to obtain "id"', ie=info_dict['extractor']) + + def report_force_conversion(field, field_not, conversion): + self.report_warning( + f'"{field}" field is not {field_not} - forcing {conversion} conversion, ' + 'there is an error in extractor') + + def sanitize_string_field(info, string_field): + field = info.get(string_field) + if field is None or isinstance(field, str): + return + report_force_conversion(string_field, 'a string', 'string') + info[string_field] = str(field) + + def sanitize_numeric_fields(info): + for numeric_field in self._NUMERIC_FIELDS: + field = info.get(numeric_field) + if field is None or isinstance(field, (int, float)): + continue + report_force_conversion(numeric_field, 'numeric', 'int') + info[numeric_field] = int_or_none(field) + + sanitize_string_field(info_dict, 'id') + sanitize_numeric_fields(info_dict) + if info_dict.get('section_end') and info_dict.get('section_start') is not None: + info_dict['duration'] = round(info_dict['section_end'] - info_dict['section_start'], 3) + if (info_dict.get('duration') or 0) <= 0 and info_dict.pop('duration', None): + self.report_warning('"duration" field is negative, there is an error in extractor') + + chapters = info_dict.get('chapters') or [] + if chapters and chapters[0].get('start_time'): + chapters.insert(0, {'start_time': 0}) + + dummy_chapter = {'end_time': 0, 'start_time': info_dict.get('duration')} + for idx, (prev, current, next_) in enumerate(zip( + (dummy_chapter, *chapters), chapters, (*chapters[1:], dummy_chapter), strict=False), 1): + if current.get('start_time') is None: + current['start_time'] = prev.get('end_time') + if not current.get('end_time'): + current['end_time'] = next_.get('start_time') + if not current.get('title'): + current['title'] = f'' + + if 'playlist' not in info_dict: + # It isn't part of a playlist + info_dict['playlist'] = None + info_dict['playlist_index'] = None + + self._sanitize_thumbnails(info_dict) + + thumbnail = info_dict.get('thumbnail') + thumbnails = info_dict.get('thumbnails') + if thumbnail: + info_dict['thumbnail'] = sanitize_url(thumbnail) + elif thumbnails: + info_dict['thumbnail'] = thumbnails[-1]['url'] + + if info_dict.get('display_id') is None and 'id' in info_dict: + info_dict['display_id'] = info_dict['id'] + + self._fill_common_fields(info_dict) + + for cc_kind in ('subtitles', 'automatic_captions'): + cc = info_dict.get(cc_kind) + if cc: + for _, subtitle in cc.items(): + for subtitle_format in subtitle: + if subtitle_format.get('url'): + subtitle_format['url'] = sanitize_url(subtitle_format['url']) + if subtitle_format.get('ext') is None: + subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower() + + automatic_captions = info_dict.get('automatic_captions') + subtitles = info_dict.get('subtitles') + + info_dict['requested_subtitles'] = self.process_subtitles( + info_dict['id'], subtitles, automatic_captions) + + formats = self._get_formats(info_dict) + + # Backward compatibility with InfoExtractor._sort_formats + field_preference = (formats or [{}])[0].pop('__sort_fields', None) + if field_preference: + info_dict['_format_sort_fields'] = field_preference + + info_dict['_has_drm'] = any( # or None ensures --clean-infojson removes it + f.get('has_drm') and f['has_drm'] != 'maybe' for f in formats) or None + if not self.params.get('allow_unplayable_formats'): + formats = [f for f in formats if not f.get('has_drm') or f['has_drm'] == 'maybe'] + + if formats and all(f.get('acodec') == f.get('vcodec') == 'none' for f in formats): + self.report_warning( + f'{"This video is DRM protected and " if info_dict["_has_drm"] else ""}' + 'only images are available for download. Use --list-formats to see them'.capitalize()) + + get_from_start = not info_dict.get('is_live') or bool(self.params.get('live_from_start')) + if not get_from_start: + info_dict['title'] += ' ' + dt.datetime.now().strftime('%Y-%m-%d %H:%M') + if info_dict.get('is_live') and formats: + formats = [f for f in formats if bool(f.get('is_from_start')) == get_from_start] + if get_from_start and not formats: + self.raise_no_formats(info_dict, msg=( + '--live-from-start is passed, but there are no formats that can be downloaded from the start. ' + 'If you want to download from the current time, use --no-live-from-start')) + + def is_wellformed(f): + url = f.get('url') + if not url: + self.report_warning( + '"url" field is missing or empty - skipping format, ' + 'there is an error in extractor') + return False + if isinstance(url, bytes): + sanitize_string_field(f, 'url') + return True + + # Filter out malformed formats for better extraction robustness + formats = list(filter(is_wellformed, formats or [])) + + if not formats: + self.raise_no_formats(info_dict) + + for fmt in formats: + sanitize_string_field(fmt, 'format_id') + sanitize_numeric_fields(fmt) + fmt['url'] = sanitize_url(fmt['url']) + FormatSorter._fill_sorting_fields(fmt) + if fmt['ext'] in ('aac', 'opus', 'mp3', 'flac', 'vorbis'): + if fmt.get('acodec') is None: + fmt['acodec'] = fmt['ext'] + if fmt.get('resolution') is None: + fmt['resolution'] = self.format_resolution(fmt, default=None) + if fmt.get('dynamic_range') is None and fmt.get('vcodec') != 'none': + fmt['dynamic_range'] = 'SDR' + if fmt.get('aspect_ratio') is None: + fmt['aspect_ratio'] = try_call(lambda: round(fmt['width'] / fmt['height'], 2)) + # For fragmented formats, "tbr" is often max bitrate and not average + if (('manifest-filesize-approx' in self.params['compat_opts'] or not fmt.get('manifest_url')) + and not fmt.get('filesize') and not fmt.get('filesize_approx')): + fmt['filesize_approx'] = filesize_from_tbr(fmt.get('tbr'), info_dict.get('duration')) + fmt['http_headers'] = self._calc_headers(collections.ChainMap(fmt, info_dict), load_cookies=True) + + # Safeguard against old/insecure infojson when using --load-info-json + if info_dict.get('http_headers'): + info_dict['http_headers'] = HTTPHeaderDict(info_dict['http_headers']) + info_dict['http_headers'].pop('Cookie', None) + + # This is copied to http_headers by the above _calc_headers and can now be removed + if '__x_forwarded_for_ip' in info_dict: + del info_dict['__x_forwarded_for_ip'] + + self.sort_formats({ + 'formats': formats, + '_format_sort_fields': info_dict.get('_format_sort_fields'), + }) + + # Sanitize and group by format_id + formats_dict = {} + for i, fmt in enumerate(formats): + if not fmt.get('format_id'): + fmt['format_id'] = str(i) + else: + # Sanitize format_id from characters used in format selector expression + fmt['format_id'] = re.sub(r'[\s,/+\[\]()]', '_', fmt['format_id']) + formats_dict.setdefault(fmt['format_id'], []).append(fmt) + + # Make sure all formats have unique format_id + common_exts = set(itertools.chain(*self._format_selection_exts.values())) + for format_id, ambiguous_formats in formats_dict.items(): + ambigious_id = len(ambiguous_formats) > 1 + for i, fmt in enumerate(ambiguous_formats): + if ambigious_id: + fmt['format_id'] = f'{format_id}-{i}' + # Ensure there is no conflict between id and ext in format selection + # See https://github.com/yt-dlp/yt-dlp/issues/1282 + if fmt['format_id'] != fmt['ext'] and fmt['format_id'] in common_exts: + fmt['format_id'] = 'f{}'.format(fmt['format_id']) + + if fmt.get('format') is None: + fmt['format'] = '{id} - {res}{note}'.format( + id=fmt['format_id'], + res=self.format_resolution(fmt), + note=format_field(fmt, 'format_note', ' (%s)'), + ) + + if self.params.get('check_formats') is True: + formats = LazyList(self._check_formats(formats[::-1], warning=False), reverse=True) + + if not formats or formats[0] is not info_dict: + # only set the 'formats' fields if the original info_dict list them + # otherwise we end up with a circular reference, the first (and unique) + # element in the 'formats' field in info_dict is info_dict itself, + # which can't be exported to json + info_dict['formats'] = formats + + info_dict, _ = self.pre_process(info_dict) + + if self._match_entry(info_dict, incomplete=self._format_fields) is not None: + return info_dict + + self.post_extract(info_dict) + info_dict, _ = self.pre_process(info_dict, 'after_filter') + + # The pre-processors may have modified the formats + formats = self._get_formats(info_dict) + + list_only = self.params.get('simulate') == 'list_only' + interactive_format_selection = not list_only and self.format_selector == '-' + if self.params.get('list_thumbnails'): + self.list_thumbnails(info_dict) + if self.params.get('listsubtitles'): + if 'automatic_captions' in info_dict: + self.list_subtitles( + info_dict['id'], automatic_captions, 'automatic captions') + self.list_subtitles(info_dict['id'], subtitles, 'subtitles') + if self.params.get('listformats') or interactive_format_selection: + self.list_formats(info_dict) + if list_only: + # Without this printing, -F --print-json will not work + self.__forced_printings(info_dict) + return info_dict + + format_selector = self.format_selector + while True: + if interactive_format_selection: + if not formats: + # Bypass interactive format selection if no formats & --ignore-no-formats-error + formats_to_download = None + break + self.to_screen(self._format_screen('\nEnter format selector ', self.Styles.EMPHASIS) + + '(Press ENTER for default, or Ctrl+C to quit)' + + self._format_screen(': ', self.Styles.EMPHASIS), skip_eol=True) + req_format = input() + try: + format_selector = self.build_format_selector(req_format) if req_format else None + except SyntaxError as err: + self.report_error(err, tb=False, is_error=False) + continue + + if format_selector is None: + req_format = self._default_format_spec(info_dict) + self.write_debug(f'Default format spec: {req_format}') + format_selector = self.build_format_selector(req_format) + + formats_to_download = self._select_formats(formats, format_selector) + if interactive_format_selection and not formats_to_download: + self.report_error('Requested format is not available', tb=False, is_error=False) + continue + break + + if not formats_to_download: + if not self.params.get('ignore_no_formats_error'): + raise ExtractorError( + 'Requested format is not available. Use --list-formats for a list of available formats', + expected=True, video_id=info_dict['id'], ie=info_dict['extractor']) + self.report_warning('Requested format is not available') + # Process what we can, even without any available formats. + formats_to_download = [{}] + + requested_ranges = tuple(self.params.get('download_ranges', lambda *_: [{}])(info_dict, self)) + best_format, downloaded_formats = formats_to_download[-1], [] + if download: + if best_format and requested_ranges: + def to_screen(*msg): + self.to_screen(f'[info] {info_dict["id"]}: {" ".join(", ".join(variadic(m)) for m in msg)}') + + to_screen(f'Downloading {len(formats_to_download)} format(s):', + (f['format_id'] for f in formats_to_download)) + if requested_ranges != ({}, ): + to_screen(f'Downloading {len(requested_ranges)} time ranges:', + (f'{c["start_time"]:.1f}-{c["end_time"]:.1f}' for c in requested_ranges)) + max_downloads_reached = False + + for fmt, chapter in itertools.product(formats_to_download, requested_ranges): + new_info = self._copy_infodict(info_dict) + new_info.update(fmt) + offset, duration = info_dict.get('section_start') or 0, info_dict.get('duration') or float('inf') + end_time = offset + min(chapter.get('end_time', duration), duration) + # duration may not be accurate. So allow deviations <1sec + if end_time == float('inf') or end_time > offset + duration + 1: + end_time = None + if chapter or offset: + new_info.update({ + 'section_start': offset + chapter.get('start_time', 0), + 'section_end': end_time, + 'section_title': chapter.get('title'), + 'section_number': chapter.get('index'), + }) + downloaded_formats.append(new_info) + try: + self.process_info(new_info) + except MaxDownloadsReached: + max_downloads_reached = True + self._raise_pending_errors(new_info) + # Remove copied info + for key, val in tuple(new_info.items()): + if info_dict.get(key) == val: + new_info.pop(key) + if max_downloads_reached: + break + + write_archive = {f.get('__write_download_archive', False) for f in downloaded_formats} + assert write_archive.issubset({True, False, 'ignore'}) + if True in write_archive and False not in write_archive: + self.record_download_archive(info_dict) + + info_dict['requested_downloads'] = downloaded_formats + info_dict = self.run_all_pps('after_video', info_dict) + if max_downloads_reached: + raise MaxDownloadsReached + + # We update the info dict with the selected best quality format (backwards compatibility) + info_dict.update(best_format) + return info_dict + + def process_subtitles(self, video_id, normal_subtitles, automatic_captions): + """Select the requested subtitles and their format""" + available_subs, normal_sub_langs = {}, [] + if normal_subtitles and self.params.get('writesubtitles'): + available_subs.update(normal_subtitles) + normal_sub_langs = tuple(normal_subtitles.keys()) + if automatic_captions and self.params.get('writeautomaticsub'): + for lang, cap_info in automatic_captions.items(): + if lang not in available_subs: + available_subs[lang] = cap_info + + if not available_subs or ( + not self.params.get('writesubtitles') + and not self.params.get('writeautomaticsub')): + return None + + all_sub_langs = tuple(available_subs.keys()) + if self.params.get('allsubtitles', False): + requested_langs = all_sub_langs + elif self.params.get('subtitleslangs', False): + try: + requested_langs = orderedSet_from_options( + self.params.get('subtitleslangs'), {'all': all_sub_langs}, use_regex=True) + except re.error as e: + raise ValueError(f'Wrong regex for subtitlelangs: {e.pattern}') + else: + requested_langs = LazyList(itertools.chain( + ['en'] if 'en' in normal_sub_langs else [], + filter(lambda f: f.startswith('en'), normal_sub_langs), + ['en'] if 'en' in all_sub_langs else [], + filter(lambda f: f.startswith('en'), all_sub_langs), + normal_sub_langs, all_sub_langs, + ))[:1] + if requested_langs: + self.to_screen(f'[info] {video_id}: Downloading subtitles: {", ".join(requested_langs)}') + + formats_query = self.params.get('subtitlesformat', 'best') + formats_preference = formats_query.split('/') if formats_query else [] + subs = {} + for lang in requested_langs: + formats = available_subs.get(lang) + if formats is None: + self.report_warning(f'{lang} subtitles not available for {video_id}') + continue + for ext in formats_preference: + if ext == 'best': + f = formats[-1] + break + matches = list(filter(lambda f: f['ext'] == ext, formats)) + if matches: + f = matches[-1] + break + else: + f = formats[-1] + self.report_warning( + 'No subtitle format found matching "{}" for language {}, ' + 'using {}. Use --list-subs for a list of available subtitles'.format(formats_query, lang, f['ext'])) + subs[lang] = f + return subs + + def _forceprint(self, key, info_dict): + if info_dict is None: + return + info_copy = info_dict.copy() + info_copy.setdefault('filename', self.prepare_filename(info_dict)) + if info_dict.get('requested_formats') is not None: + # For RTMP URLs, also include the playpath + info_copy['urls'] = '\n'.join(f['url'] + f.get('play_path', '') for f in info_dict['requested_formats']) + elif info_dict.get('url'): + info_copy['urls'] = info_dict['url'] + info_dict.get('play_path', '') + info_copy['formats_table'] = self.render_formats_table(info_dict) + info_copy['thumbnails_table'] = self.render_thumbnails_table(info_dict) + info_copy['subtitles_table'] = self.render_subtitles_table(info_dict.get('id'), info_dict.get('subtitles')) + info_copy['automatic_captions_table'] = self.render_subtitles_table(info_dict.get('id'), info_dict.get('automatic_captions')) + + def format_tmpl(tmpl): + mobj = re.fullmatch(r'([\w.:,]|-\d|(?P{([\w.:,]|-\d)+}))+=?', tmpl) + if not mobj: + return tmpl + + fmt = '%({})s' + if tmpl.startswith('{'): + tmpl, fmt = f'.{tmpl}', '%({})j' + if tmpl.endswith('='): + tmpl, fmt = tmpl[:-1], '{0} = %({0})#j' + return '\n'.join(map(fmt.format, [tmpl] if mobj.group('dict') else tmpl.split(','))) + + for tmpl in self.params['forceprint'].get(key, []): + self.to_stdout(self.evaluate_outtmpl(format_tmpl(tmpl), info_copy)) + + for tmpl, file_tmpl in self.params['print_to_file'].get(key, []): + filename = self.prepare_filename(info_dict, outtmpl=file_tmpl) + tmpl = format_tmpl(tmpl) + self.to_screen(f'[info] Writing {tmpl!r} to: {filename}') + if self._ensure_dir_exists(filename): + with open(filename, 'a', encoding='utf-8', newline='') as f: + f.write(self.evaluate_outtmpl(tmpl, info_copy) + os.linesep) + + return info_copy + + def __forced_printings(self, info_dict, filename=None, incomplete=True): + if (self.params.get('forcejson') + or self.params['forceprint'].get('video') + or self.params['print_to_file'].get('video')): + self.post_extract(info_dict) + if filename: + info_dict['filename'] = filename + info_copy = self._forceprint('video', info_dict) + + def print_field(field, actual_field=None, optional=False): + if actual_field is None: + actual_field = field + if self.params.get(f'force{field}') and ( + info_copy.get(field) is not None or (not optional and not incomplete)): + self.to_stdout(info_copy[actual_field]) + + print_field('title') + print_field('id') + print_field('url', 'urls') + print_field('thumbnail', optional=True) + print_field('description', optional=True) + print_field('filename') + if self.params.get('forceduration') and info_copy.get('duration') is not None: + self.to_stdout(formatSeconds(info_copy['duration'])) + print_field('format') + + if self.params.get('forcejson'): + self.to_stdout(json.dumps(self.sanitize_info(info_dict))) + + def dl(self, name, info, subtitle=False, test=False): + if not info.get('url'): + self.raise_no_formats(info, True) + + if test: + verbose = self.params.get('verbose') + quiet = self.params.get('quiet') or not verbose + params = { + 'test': True, + 'quiet': quiet, + 'verbose': verbose, + 'noprogress': quiet, + 'nopart': True, + 'skip_unavailable_fragments': False, + 'keep_fragments': False, + 'overwrites': True, + '_no_ytdl_file': True, + } + else: + params = self.params + + fd = get_suitable_downloader(info, params, to_stdout=(name == '-'))(self, params) + if not test: + for ph in self._progress_hooks: + fd.add_progress_hook(ph) + urls = '", "'.join( + (f['url'].split(',')[0] + ',' if f['url'].startswith('data:') else f['url']) + for f in info.get('requested_formats', []) or [info]) + self.write_debug(f'Invoking {fd.FD_NAME} downloader on "{urls}"') + + # Note: Ideally info should be a deep-copied so that hooks cannot modify it. + # But it may contain objects that are not deep-copyable + new_info = self._copy_infodict(info) + if new_info.get('http_headers') is None: + new_info['http_headers'] = self._calc_headers(new_info) + return fd.download(name, new_info, subtitle) + + def existing_file(self, filepaths, *, default_overwrite=True): + existing_files = list(filter(os.path.exists, orderedSet(filepaths))) + if existing_files and not self.params.get('overwrites', default_overwrite): + return existing_files[0] + + for file in existing_files: + self.report_file_delete(file) + os.remove(file) + return None + + @_catch_unsafe_extension_error + def process_info(self, info_dict): + """Process a single resolved IE result. (Modifies it in-place)""" + + assert info_dict.get('_type', 'video') == 'video' + original_infodict = info_dict + + if 'format' not in info_dict and 'ext' in info_dict: + info_dict['format'] = info_dict['ext'] + + if self._match_entry(info_dict) is not None: + info_dict['__write_download_archive'] = 'ignore' + return + + # Does nothing under normal operation - for backward compatibility of process_info + self.post_extract(info_dict) + + def replace_info_dict(new_info): + nonlocal info_dict + if new_info == info_dict: + return + info_dict.clear() + info_dict.update(new_info) + + new_info, _ = self.pre_process(info_dict, 'video') + replace_info_dict(new_info) + self._num_downloads += 1 + + # info_dict['_filename'] needs to be set for backward compatibility + info_dict['_filename'] = full_filename = self.prepare_filename(info_dict, warn=True) + temp_filename = self.prepare_filename(info_dict, 'temp') + files_to_move = {} + + # Forced printings + self.__forced_printings(info_dict, full_filename, incomplete=('format' not in info_dict)) + + def check_max_downloads(): + if self._num_downloads >= float(self.params.get('max_downloads') or 'inf'): + raise MaxDownloadsReached + + if self.params.get('simulate'): + info_dict['__write_download_archive'] = self.params.get('force_write_download_archive') + check_max_downloads() + return + + if full_filename is None: + return + if not self._ensure_dir_exists(full_filename): + return + if not self._ensure_dir_exists(temp_filename): + return + + if self._write_description('video', info_dict, + self.prepare_filename(info_dict, 'description')) is None: + return + + sub_files = self._write_subtitles(info_dict, temp_filename) + if sub_files is None: + return + files_to_move.update(dict(sub_files)) + + thumb_files = self._write_thumbnails( + 'video', info_dict, temp_filename, self.prepare_filename(info_dict, 'thumbnail')) + if thumb_files is None: + return + files_to_move.update(dict(thumb_files)) + + infofn = self.prepare_filename(info_dict, 'infojson') + _infojson_written = self._write_info_json('video', info_dict, infofn) + if _infojson_written: + info_dict['infojson_filename'] = infofn + # For backward compatibility, even though it was a private field + info_dict['__infojson_filename'] = infofn + elif _infojson_written is None: + return + + # Write internet shortcut files + def _write_link_file(link_type): + url = try_get(info_dict['webpage_url'], iri_to_uri) + if not url: + self.report_warning( + f'Cannot write internet shortcut file because the actual URL of "{info_dict["webpage_url"]}" is unknown') + return True + linkfn = replace_extension(self.prepare_filename(info_dict, 'link'), link_type, info_dict.get('ext')) + if not self._ensure_dir_exists(linkfn): + return False + if self.params.get('overwrites', True) and os.path.exists(linkfn): + self.to_screen(f'[info] Internet shortcut (.{link_type}) is already present') + return True + try: + self.to_screen(f'[info] Writing internet shortcut (.{link_type}) to: {linkfn}') + with open(to_high_limit_path(linkfn), 'w', encoding='utf-8', + newline='\r\n' if link_type == 'url' else '\n') as linkfile: + template_vars = {'url': url} + if link_type == 'desktop': + template_vars['filename'] = linkfn[:-(len(link_type) + 1)] + linkfile.write(LINK_TEMPLATES[link_type] % template_vars) + except OSError: + self.report_error(f'Cannot write internet shortcut {linkfn}') + return False + return True + + write_links = { + 'url': self.params.get('writeurllink'), + 'webloc': self.params.get('writewebloclink'), + 'desktop': self.params.get('writedesktoplink'), + } + if self.params.get('writelink'): + link_type = ('webloc' if sys.platform == 'darwin' + else 'desktop' if sys.platform.startswith('linux') + else 'url') + write_links[link_type] = True + + if any(should_write and not _write_link_file(link_type) + for link_type, should_write in write_links.items()): + return + + new_info, files_to_move = self.pre_process(info_dict, 'before_dl', files_to_move) + replace_info_dict(new_info) + + if self.params.get('skip_download'): + info_dict['filepath'] = temp_filename + info_dict['__finaldir'] = os.path.dirname(os.path.abspath(full_filename)) + info_dict['__files_to_move'] = files_to_move + replace_info_dict(self.run_pp(MoveFilesAfterDownloadPP(self, False), info_dict)) + info_dict['__write_download_archive'] = self.params.get('force_write_download_archive') + else: + # Download + info_dict.setdefault('__postprocessors', []) + try: + + def existing_video_file(*filepaths): + ext = info_dict.get('ext') + converted = lambda file: replace_extension(file, self.params.get('final_ext') or ext, ext) + file = self.existing_file(itertools.chain(*zip(map(converted, filepaths), filepaths, strict=True)), + default_overwrite=False) + if file: + info_dict['ext'] = os.path.splitext(file)[1][1:] + return file + + fd, success = None, True + if info_dict.get('protocol') or info_dict.get('url'): + fd = get_suitable_downloader(info_dict, self.params, to_stdout=temp_filename == '-') + if fd != FFmpegFD and 'no-direct-merge' not in self.params['compat_opts'] and ( + info_dict.get('section_start') or info_dict.get('section_end')): + msg = ('This format cannot be partially downloaded' if FFmpegFD.available() + else 'You have requested downloading the video partially, but ffmpeg is not installed') + self.report_error(f'{msg}. Aborting') + return + + if info_dict.get('requested_formats') is not None: + old_ext = info_dict['ext'] + if self.params.get('merge_output_format') is None: + if (info_dict['ext'] == 'webm' + and info_dict.get('thumbnails') + # check with type instead of pp_key, __name__, or isinstance + # since we dont want any custom PPs to trigger this + and any(type(pp) == EmbedThumbnailPP for pp in self._pps['post_process'])): # noqa: E721 + info_dict['ext'] = 'mkv' + self.report_warning( + 'webm doesn\'t support embedding a thumbnail, mkv will be used') + new_ext = info_dict['ext'] + + def correct_ext(filename, ext=new_ext): + if filename == '-': + return filename + filename_real_ext = os.path.splitext(filename)[1][1:] + filename_wo_ext = ( + os.path.splitext(filename)[0] + if filename_real_ext in (old_ext, new_ext) + else filename) + return f'{filename_wo_ext}.{ext}' + + # Ensure filename always has a correct extension for successful merge + full_filename = correct_ext(full_filename) + temp_filename = correct_ext(temp_filename) + dl_filename = existing_video_file(full_filename, temp_filename) + + info_dict['__real_download'] = False + # NOTE: Copy so that original format dicts are not modified + info_dict['requested_formats'] = list(map(dict, info_dict['requested_formats'])) + + merger = FFmpegMergerPP(self) + downloaded = [] + if dl_filename is not None: + self.report_file_already_downloaded(dl_filename) + elif fd: + if fd != FFmpegFD and temp_filename != '-': + for f in info_dict['requested_formats']: + f['filepath'] = fname = prepend_extension( + correct_ext(temp_filename, info_dict['ext']), + 'f{}'.format(f['format_id']), info_dict['ext']) + downloaded.append(fname) + info_dict['url'] = '\n'.join(f['url'] for f in info_dict['requested_formats']) + success, real_download = self.dl(temp_filename, info_dict) + info_dict['__real_download'] = real_download + else: + if self.params.get('allow_unplayable_formats'): + self.report_warning( + 'You have requested merging of multiple formats ' + 'while also allowing unplayable formats to be downloaded. ' + 'The formats won\'t be merged to prevent data corruption.') + elif not merger.available: + msg = 'You have requested merging of multiple formats but ffmpeg is not installed' + if not self.params.get('ignoreerrors'): + self.report_error(f'{msg}. Aborting due to --abort-on-error') + return + self.report_warning(f'{msg}. The formats won\'t be merged') + + if temp_filename == '-': + reason = ('using a downloader other than ffmpeg' if FFmpegFD.can_merge_formats(info_dict, self.params) + else 'but the formats are incompatible for simultaneous download' if merger.available + else 'but ffmpeg is not installed') + self.report_warning( + f'You have requested downloading multiple formats to stdout {reason}. ' + 'The formats will be streamed one after the other') + fname = temp_filename + for f in info_dict['requested_formats']: + new_info = dict(info_dict) + del new_info['requested_formats'] + new_info.update(f) + if temp_filename != '-': + fname = prepend_extension( + correct_ext(temp_filename, new_info['ext']), + 'f{}'.format(f['format_id']), new_info['ext']) + if not self._ensure_dir_exists(fname): + return + f['filepath'] = fname + downloaded.append(fname) + partial_success, real_download = self.dl(fname, new_info) + info_dict['__real_download'] = info_dict['__real_download'] or real_download + success = success and partial_success + + if downloaded and merger.available and not self.params.get('allow_unplayable_formats'): + info_dict['__postprocessors'].append(merger) + info_dict['__files_to_merge'] = downloaded + # Even if there were no downloads, it is being merged only now + info_dict['__real_download'] = True + else: + for file in downloaded: + files_to_move[file] = None + else: + # Just a single file + dl_filename = existing_video_file(full_filename, temp_filename) + if dl_filename is None or dl_filename == temp_filename: + # dl_filename == temp_filename could mean that the file was partially downloaded with --no-part. + # So we should try to resume the download + success, real_download = self.dl(temp_filename, info_dict) + info_dict['__real_download'] = real_download + else: + self.report_file_already_downloaded(dl_filename) + + dl_filename = dl_filename or temp_filename + info_dict['__finaldir'] = os.path.dirname(os.path.abspath(full_filename)) + + except network_exceptions as err: + self.report_error(f'unable to download video data: {err}') + return + except OSError as err: + raise UnavailableVideoError(err) + except ContentTooShortError as err: + self.report_error(f'content too short (expected {err.expected} bytes and served {err.downloaded})') + return + + self._raise_pending_errors(info_dict) + if success and full_filename != '-': + + def fixup(): + do_fixup = True + fixup_policy = self.params.get('fixup') + vid = info_dict['id'] + + if fixup_policy in ('ignore', 'never'): + return + elif fixup_policy == 'warn': + do_fixup = 'warn' + elif fixup_policy != 'force': + assert fixup_policy in ('detect_or_warn', None) + if not info_dict.get('__real_download'): + do_fixup = False + + def ffmpeg_fixup(cndn, msg, cls): + if not (do_fixup and cndn): + return + elif do_fixup == 'warn': + self.report_warning(f'{vid}: {msg}') + return + pp = cls(self) + if pp.available: + info_dict['__postprocessors'].append(pp) + else: + self.report_warning(f'{vid}: {msg}. Install ffmpeg to fix this automatically') + + stretched_ratio = info_dict.get('stretched_ratio') + ffmpeg_fixup(stretched_ratio not in (1, None), + f'Non-uniform pixel ratio {stretched_ratio}', + FFmpegFixupStretchedPP) + + downloader = get_suitable_downloader(info_dict, self.params) if 'protocol' in info_dict else None + downloader = downloader.FD_NAME if downloader else None + + ext = info_dict.get('ext') + postprocessed_by_ffmpeg = info_dict.get('requested_formats') or any(( + isinstance(pp, FFmpegVideoConvertorPP) + and resolve_recode_mapping(ext, pp.mapping)[0] not in (ext, None) + ) for pp in self._pps['post_process']) + + if not postprocessed_by_ffmpeg: + ffmpeg_fixup(fd != FFmpegFD and ext == 'm4a' + and info_dict.get('container') == 'm4a_dash', + 'writing DASH m4a. Only some players support this container', + FFmpegFixupM4aPP) + ffmpeg_fixup((downloader == 'hlsnative' and not self.params.get('hls_use_mpegts')) + or (info_dict.get('is_live') and self.params.get('hls_use_mpegts') is None), + 'Possible MPEG-TS in MP4 container or malformed AAC timestamps', + FFmpegFixupM3u8PP) + ffmpeg_fixup(downloader == 'dashsegments' + and (info_dict.get('is_live') or info_dict.get('is_dash_periods')), + 'Possible duplicate MOOV atoms', FFmpegFixupDuplicateMoovPP) + + ffmpeg_fixup(downloader == 'web_socket_fragment', 'Malformed timestamps detected', FFmpegFixupTimestampPP) + ffmpeg_fixup(downloader == 'web_socket_fragment', 'Malformed duration detected', FFmpegFixupDurationPP) + + fixup() + try: + replace_info_dict(self.post_process(dl_filename, info_dict, files_to_move)) + except PostProcessingError as err: + self.report_error(f'Postprocessing: {err}') + return + try: + for ph in self._post_hooks: + ph(info_dict['filepath']) + except Exception as err: + self.report_error(f'post hooks: {err}') + return + info_dict['__write_download_archive'] = True + + assert info_dict is original_infodict # Make sure the info_dict was modified in-place + if self.params.get('force_write_download_archive'): + info_dict['__write_download_archive'] = True + check_max_downloads() + + def __download_wrapper(self, func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + try: + res = func(*args, **kwargs) + except CookieLoadError: + raise + except UnavailableVideoError as e: + self.report_error(e) + except DownloadCancelled as e: + self.to_screen(f'[info] {e}') + if not self.params.get('break_per_url'): + raise + self._num_downloads = 0 + else: + if self.params.get('dump_single_json', False): + self.post_extract(res) + self.to_stdout(json.dumps(self.sanitize_info(res))) + return wrapper + + def download(self, url_list): + """Download a given list of URLs.""" + url_list = variadic(url_list) # Passing a single URL is a common mistake + outtmpl = self.params['outtmpl']['default'] + if (len(url_list) > 1 + and outtmpl != '-' + and '%' not in outtmpl + and self.params.get('max_downloads') != 1): + raise SameFileError(outtmpl) + + for url in url_list: + self.__download_wrapper(self.extract_info)( + url, force_generic_extractor=self.params.get('force_generic_extractor', False)) + + return self._download_retcode + + def download_with_info_file(self, info_filename): + with contextlib.closing(fileinput.FileInput( + [info_filename], mode='r', + openhook=fileinput.hook_encoded('utf-8'))) as f: + # FileInput doesn't have a read method, we can't call json.load + infos = [self.sanitize_info(info, self.params.get('clean_infojson', True)) + for info in variadic(json.loads('\n'.join(f)))] + for info in infos: + try: + self.__download_wrapper(self.process_ie_result)(info, download=True) + except (DownloadError, EntryNotInPlaylist, ReExtractInfo) as e: + if not isinstance(e, EntryNotInPlaylist): + self.to_stderr('\r') + webpage_url = info.get('webpage_url') + if webpage_url is None: + raise + self.report_warning(f'The info failed to download: {e}; trying with URL {webpage_url}') + self.download([webpage_url]) + except ExtractorError as e: + self.report_error(e) + return self._download_retcode + + @staticmethod + def sanitize_info(info_dict, remove_private_keys=False): + """ Sanitize the infodict for converting to json """ + if info_dict is None: + return info_dict + info_dict.setdefault('epoch', int(time.time())) + info_dict.setdefault('_type', 'video') + info_dict.setdefault('_version', { + 'version': __version__, + 'current_git_head': current_git_head(), + 'release_git_head': RELEASE_GIT_HEAD, + 'repository': ORIGIN, + }) + + if remove_private_keys: + reject = lambda k, v: v is None or k.startswith('__') or k in { + 'requested_downloads', 'requested_formats', 'requested_subtitles', 'requested_entries', + 'entries', 'filepath', '_filename', 'filename', 'infojson_filename', 'original_url', + 'playlist_autonumber', + } + else: + reject = lambda k, v: False + + def filter_fn(obj): + if isinstance(obj, dict): + return {k: filter_fn(v) for k, v in obj.items() if not reject(k, v)} + elif isinstance(obj, (list, tuple, set, LazyList)): + return list(map(filter_fn, obj)) + elif isinstance(obj, ImpersonateTarget): + return str(obj) + elif obj is None or isinstance(obj, (str, int, float, bool)): + return obj + else: + return repr(obj) + + return filter_fn(info_dict) + + @staticmethod + def filter_requested_info(info_dict, actually_filter=True): + """ Alias of sanitize_info for backward compatibility """ + return YoutubeDL.sanitize_info(info_dict, actually_filter) + + def _delete_downloaded_files(self, *files_to_delete, info={}, msg=None): + for filename in set(filter(None, files_to_delete)): + if msg: + self.to_screen(msg % filename) + try: + os.remove(filename) + except OSError: + self.report_warning(f'Unable to delete file {filename}') + if filename in info.get('__files_to_move', []): # NB: Delete even if None + del info['__files_to_move'][filename] + + @staticmethod + def post_extract(info_dict): + def actual_post_extract(info_dict): + if info_dict.get('_type') in ('playlist', 'multi_video'): + for video_dict in info_dict.get('entries', {}): + actual_post_extract(video_dict or {}) + return + + post_extractor = info_dict.pop('__post_extractor', None) or dict + info_dict.update(post_extractor()) + + actual_post_extract(info_dict or {}) + + def run_pp(self, pp, infodict): + files_to_delete = [] + if '__files_to_move' not in infodict: + infodict['__files_to_move'] = {} + try: + files_to_delete, infodict = pp.run(infodict) + except PostProcessingError as e: + # Must be True and not 'only_download' + if self.params.get('ignoreerrors') is True: + self.report_error(e) + return infodict + raise + + if not files_to_delete: + return infodict + if self.params.get('keepvideo', False): + for f in files_to_delete: + infodict['__files_to_move'].setdefault(f, '') + else: + self._delete_downloaded_files( + *files_to_delete, info=infodict, msg='Deleting original file %s (pass -k to keep)') + return infodict + + def run_all_pps(self, key, info, *, additional_pps=None): + if key != 'video': + self._forceprint(key, info) + for pp in (additional_pps or []) + self._pps[key]: + info = self.run_pp(pp, info) + return info + + def pre_process(self, ie_info, key='pre_process', files_to_move=None): + info = dict(ie_info) + info['__files_to_move'] = files_to_move or {} + try: + info = self.run_all_pps(key, info) + except PostProcessingError as err: + msg = f'Preprocessing: {err}' + info.setdefault('__pending_error', msg) + self.report_error(msg, is_error=False) + return info, info.pop('__files_to_move', None) + + def post_process(self, filename, info, files_to_move=None): + """Run all the postprocessors on the given file.""" + info['filepath'] = filename + info['__files_to_move'] = files_to_move or {} + info = self.run_all_pps('post_process', info, additional_pps=info.get('__postprocessors')) + info = self.run_pp(MoveFilesAfterDownloadPP(self), info) + del info['__files_to_move'] + return self.run_all_pps('after_move', info) + + def _make_archive_id(self, info_dict): + video_id = info_dict.get('id') + if not video_id: + return + # Future-proof against any change in case + # and backwards compatibility with prior versions + extractor = info_dict.get('extractor_key') or info_dict.get('ie_key') # key in a playlist + if extractor is None: + url = str_or_none(info_dict.get('url')) + if not url: + return + # Try to find matching extractor for the URL and take its ie_key + for ie_key, ie in self._ies.items(): + if ie.suitable(url): + extractor = ie_key + break + else: + return + return make_archive_id(extractor, video_id) + + def in_download_archive(self, info_dict): + if not self.archive: + return False + + vid_ids = [self._make_archive_id(info_dict)] + vid_ids.extend(info_dict.get('_old_archive_ids') or []) + return any(id_ in self.archive for id_ in vid_ids) + + def record_download_archive(self, info_dict): + fn = self.params.get('download_archive') + if fn is None: + return + vid_id = self._make_archive_id(info_dict) + assert vid_id + + self.write_debug(f'Adding to archive: {vid_id}') + if is_path_like(fn): + with locked_file(fn, 'a', encoding='utf-8') as archive_file: + archive_file.write(vid_id + '\n') + self.archive.add(vid_id) + + @staticmethod + def format_resolution(format, default='unknown'): + if format.get('vcodec') == 'none' and format.get('acodec') != 'none': + return 'audio only' + if format.get('resolution') is not None: + return format['resolution'] + if format.get('width') and format.get('height'): + return '%dx%d' % (format['width'], format['height']) + elif format.get('height'): + return '{}p'.format(format['height']) + elif format.get('width'): + return '%dx?' % format['width'] + return default + + def _list_format_headers(self, *headers): + if self.params.get('listformats_table', True) is not False: + return [self._format_out(header, self.Styles.HEADERS) for header in headers] + return headers + + def _format_note(self, fdict): + res = '' + if fdict.get('ext') in ['f4f', 'f4m']: + res += '(unsupported)' + if fdict.get('language'): + if res: + res += ' ' + res += '[{}]'.format(fdict['language']) + if fdict.get('format_note') is not None: + if res: + res += ' ' + res += fdict['format_note'] + if fdict.get('tbr') is not None: + if res: + res += ', ' + res += '%4dk' % fdict['tbr'] + if fdict.get('container') is not None: + if res: + res += ', ' + res += '{} container'.format(fdict['container']) + if (fdict.get('vcodec') is not None + and fdict.get('vcodec') != 'none'): + if res: + res += ', ' + res += fdict['vcodec'] + if fdict.get('vbr') is not None: + res += '@' + elif fdict.get('vbr') is not None and fdict.get('abr') is not None: + res += 'video@' + if fdict.get('vbr') is not None: + res += '%4dk' % fdict['vbr'] + if fdict.get('fps') is not None: + if res: + res += ', ' + res += '{}fps'.format(fdict['fps']) + if fdict.get('acodec') is not None: + if res: + res += ', ' + if fdict['acodec'] == 'none': + res += 'video only' + else: + res += '%-5s' % fdict['acodec'] + elif fdict.get('abr') is not None: + if res: + res += ', ' + res += 'audio' + if fdict.get('abr') is not None: + res += '@%3dk' % fdict['abr'] + if fdict.get('asr') is not None: + res += ' (%5dHz)' % fdict['asr'] + if fdict.get('filesize') is not None: + if res: + res += ', ' + res += format_bytes(fdict['filesize']) + elif fdict.get('filesize_approx') is not None: + if res: + res += ', ' + res += '~' + format_bytes(fdict['filesize_approx']) + return res + + def _get_formats(self, info_dict): + if info_dict.get('formats') is None: + if info_dict.get('url') and info_dict.get('_type', 'video') == 'video': + return [info_dict] + return [] + return info_dict['formats'] + + def render_formats_table(self, info_dict): + formats = self._get_formats(info_dict) + if not formats: + return + if not self.params.get('listformats_table', True) is not False: + table = [ + [ + format_field(f, 'format_id'), + format_field(f, 'ext'), + self.format_resolution(f), + self._format_note(f), + ] for f in formats if (f.get('preference') or 0) >= -1000] + return render_table(['format code', 'extension', 'resolution', 'note'], table, extra_gap=1) + + def simplified_codec(f, field): + assert field in ('acodec', 'vcodec') + codec = f.get(field) + if not codec: + return 'unknown' + elif codec != 'none': + return '.'.join(codec.split('.')[:4]) + + if field == 'vcodec' and f.get('acodec') == 'none': + return 'images' + elif field == 'acodec' and f.get('vcodec') == 'none': + return '' + return self._format_out('audio only' if field == 'vcodec' else 'video only', + self.Styles.SUPPRESS) + + delim = self._format_out('\u2502', self.Styles.DELIM, '|', test_encoding=True) + table = [ + [ + self._format_out(format_field(f, 'format_id'), self.Styles.ID), + format_field(f, 'ext'), + format_field(f, func=self.format_resolution, ignore=('audio only', 'images')), + format_field(f, 'fps', '\t%d', func=round), + format_field(f, 'dynamic_range', '%s', ignore=(None, 'SDR')).replace('HDR', ''), + format_field(f, 'audio_channels', '\t%s'), + delim, ( + format_field(f, 'filesize', ' \t%s', func=format_bytes) + or format_field(f, 'filesize_approx', '≈\t%s', func=format_bytes) + or format_field(filesize_from_tbr(f.get('tbr'), info_dict.get('duration')), None, + self._format_out('~\t%s', self.Styles.SUPPRESS), func=format_bytes)), + format_field(f, 'tbr', '\t%dk', func=round), + shorten_protocol_name(f.get('protocol', '')), + delim, + simplified_codec(f, 'vcodec'), + format_field(f, 'vbr', '\t%dk', func=round), + simplified_codec(f, 'acodec'), + format_field(f, 'abr', '\t%dk', func=round), + format_field(f, 'asr', '\t%s', func=format_decimal_suffix), + join_nonempty(format_field(f, 'language', '[%s]'), join_nonempty( + self._format_out('UNSUPPORTED', self.Styles.BAD_FORMAT) if f.get('ext') in ('f4f', 'f4m') else None, + (self._format_out('Maybe DRM', self.Styles.WARNING) if f.get('has_drm') == 'maybe' + else self._format_out('DRM', self.Styles.BAD_FORMAT) if f.get('has_drm') else None), + self._format_out('Untested', self.Styles.WARNING) if f.get('__needs_testing') else None, + format_field(f, 'format_note'), + format_field(f, 'container', ignore=(None, f.get('ext'))), + delim=', '), delim=' '), + ] for f in formats if f.get('preference') is None or f['preference'] >= -1000] + header_line = self._list_format_headers( + 'ID', 'EXT', 'RESOLUTION', '\tFPS', 'HDR', 'CH', delim, '\tFILESIZE', '\tTBR', 'PROTO', + delim, 'VCODEC', '\tVBR', 'ACODEC', '\tABR', '\tASR', 'MORE INFO') + + return render_table( + header_line, table, hide_empty=True, + delim=self._format_out('\u2500', self.Styles.DELIM, '-', test_encoding=True)) + + def render_thumbnails_table(self, info_dict): + thumbnails = list(info_dict.get('thumbnails') or []) + if not thumbnails: + return None + return render_table( + self._list_format_headers('ID', 'Width', 'Height', 'URL'), + [[t.get('id'), t.get('width') or 'unknown', t.get('height') or 'unknown', t['url']] for t in thumbnails]) + + def render_subtitles_table(self, video_id, subtitles): + def _row(lang, formats): + exts, names = zip(*((f['ext'], f.get('name') or 'unknown') for f in reversed(formats)), strict=True) + if len(set(names)) == 1: + names = [] if names[0] == 'unknown' else names[:1] + return [lang, ', '.join(names), ', '.join(exts)] + + if not subtitles: + return None + return render_table( + self._list_format_headers('Language', 'Name', 'Formats'), + [_row(lang, formats) for lang, formats in subtitles.items()], + hide_empty=True) + + def __list_table(self, video_id, name, func, *args): + table = func(*args) + if not table: + self.to_screen(f'{video_id} has no {name}') + return + self.to_screen(f'[info] Available {name} for {video_id}:') + self.to_stdout(table) + + def list_formats(self, info_dict): + self.__list_table(info_dict['id'], 'formats', self.render_formats_table, info_dict) + + def list_thumbnails(self, info_dict): + self.__list_table(info_dict['id'], 'thumbnails', self.render_thumbnails_table, info_dict) + + def list_subtitles(self, video_id, subtitles, name='subtitles'): + self.__list_table(video_id, name, self.render_subtitles_table, video_id, subtitles) + + def print_debug_header(self): + if not self.params.get('verbose'): + return + + def get_encoding(stream): + ret = str(getattr(stream, 'encoding', f'missing ({type(stream).__name__})')) + additional_info = [] + if os.environ.get('TERM', '').lower() == 'dumb': + additional_info.append('dumb') + if not supports_terminal_sequences(stream): + additional_info.append('No VT' if WINDOWS_VT_MODE.value is False else 'No ANSI') + if additional_info: + ret = f'{ret} ({",".join(additional_info)})' + return ret + + encoding_str = 'Encodings: locale {}, fs {}, pref {}, {}'.format( + locale.getpreferredencoding(), + sys.getfilesystemencoding(), + self.get_encoding(), + ', '.join( + f'{key} {get_encoding(stream)}' for key, stream in self._out_files.items_ + if stream is not None and key != 'console'), + ) + + logger = self.params.get('logger') + if logger: + write_debug = lambda msg: logger.debug(f'[debug] {msg}') + write_debug(encoding_str) + else: + write_string(f'[debug] {encoding_str}\n', encoding=None) + write_debug = lambda msg: self._write_string(f'[debug] {msg}\n') + + source = detect_variant() + if VARIANT not in (None, 'pip'): + source += '*' + klass = type(self) + write_debug(join_nonempty( + f'{REPOSITORY.rpartition("/")[2]} version', + _make_label(ORIGIN, CHANNEL.partition('@')[2] or __version__, __version__), + f'[{RELEASE_GIT_HEAD[:9]}]' if RELEASE_GIT_HEAD else '', + '' if source == 'unknown' else f'({source})', + '' if IN_CLI.value else 'API' if klass == YoutubeDL else f'API:{self.__module__}.{klass.__qualname__}', + delim=' ')) + + if not IN_CLI.value: + write_debug(f'params: {self.params}') + + import_extractors() + lazy_extractors = LAZY_EXTRACTORS.value + if lazy_extractors is None: + write_debug('Lazy loading extractors is disabled') + elif not lazy_extractors: + write_debug('Lazy loading extractors is forcibly disabled') + if self.params['compat_opts']: + write_debug('Compatibility options: {}'.format(', '.join(self.params['compat_opts']))) + + if current_git_head(): + write_debug(f'Git HEAD: {current_git_head()}') + write_debug(system_identifier()) + + exe_versions, ffmpeg_features = FFmpegPostProcessor.get_versions_and_features(self) + ffmpeg_features = {key for key, val in ffmpeg_features.items() if val} + if ffmpeg_features: + exe_versions['ffmpeg'] += ' ({})'.format(','.join(sorted(ffmpeg_features))) + + exe_versions['rtmpdump'] = rtmpdump_version() + exe_versions['phantomjs'] = PhantomJSwrapper._version() + exe_str = ', '.join( + f'{exe} {v}' for exe, v in sorted(exe_versions.items()) if v + ) or 'none' + write_debug(f'exe versions: {exe_str}') + + from .compat.compat_utils import get_package_info + from .dependencies import available_dependencies + + write_debug('Optional libraries: %s' % (', '.join(sorted({ + join_nonempty(*get_package_info(m)) for m in available_dependencies.values() + })) or 'none')) + + if not self.params.get('js_runtimes'): + write_debug('JS runtimes: none (disabled)') + else: + write_debug('JS runtimes: %s' % (', '.join(sorted( + f'{name} (unknown)' if runtime is None + else join_nonempty( + runtime.info.name, + runtime.info.version + (' (unsupported)' if runtime.info.supported is False else ''), + ) + for name, runtime in self._js_runtimes.items() if runtime is None or runtime.info is not None + )) or 'none')) + + write_debug(f'Proxy map: {self.proxies}') + write_debug(f'Request Handlers: {", ".join(rh.RH_NAME for rh in self._request_director.handlers.values())}') + + for plugin_type, plugins in (('Extractor', plugin_ies), ('Post-Processor', plugin_pps)): + display_list = [ + klass.__name__ if klass.__name__ == name else f'{klass.__name__} as {name}' + for name, klass in plugins.value.items()] + if plugin_type == 'Extractor': + display_list.extend(f'{plugins[-1].IE_NAME.partition("+")[2]} ({parent.__name__})' + for parent, plugins in plugin_ies_overrides.value.items()) + if not display_list: + continue + write_debug(f'{plugin_type} Plugins: {", ".join(sorted(display_list))}') + + plugin_dirs_msg = 'none' + if not plugin_dirs.value: + plugin_dirs_msg = 'none (disabled)' + else: + found_plugin_directories = plugin_directories() + if found_plugin_directories: + plugin_dirs_msg = ', '.join(found_plugin_directories) + + write_debug(f'Plugin directories: {plugin_dirs_msg}') + + @functools.cached_property + def proxies(self): + """Global proxy configuration""" + opts_proxy = self.params.get('proxy') + if opts_proxy is not None: + if opts_proxy == '': + opts_proxy = '__noproxy__' + proxies = {'all': opts_proxy} + else: + proxies = urllib.request.getproxies() + # compat. Set HTTPS_PROXY to __noproxy__ to revert + if 'http' in proxies and 'https' not in proxies: + proxies['https'] = proxies['http'] + + return proxies + + @functools.cached_property + def cookiejar(self): + """Global cookiejar instance""" + try: + return load_cookies( + self.params.get('cookiefile'), self.params.get('cookiesfrombrowser'), self) + except CookieLoadError as error: + cause = error.__context__ + self.report_error(str(cause), tb=''.join(traceback.format_exception(cause))) + raise + + @property + def _opener(self): + """ + Get a urllib OpenerDirector from the Urllib handler (deprecated). + """ + self.deprecation_warning('YoutubeDL._opener is deprecated, use YoutubeDL.urlopen()') + handler = self._request_director.handlers['Urllib'] + return handler._get_instance(cookiejar=self.cookiejar, proxies=self.proxies) + + def _get_available_impersonate_targets(self): + # TODO(future): make available as public API + return [ + (target, rh.RH_NAME) + for rh in self._request_director.handlers.values() + if isinstance(rh, ImpersonateRequestHandler) + for target in reversed(rh.supported_targets) + ] + + def _impersonate_target_available(self, target): + # TODO(future): make available as public API + return any( + rh.is_supported_target(target) + for rh in self._request_director.handlers.values() + if isinstance(rh, ImpersonateRequestHandler)) + + def _parse_impersonate_targets(self, impersonate): + if impersonate in (True, ''): + impersonate = ImpersonateTarget() + + requested_targets = [ + t if isinstance(t, ImpersonateTarget) else ImpersonateTarget.from_str(t) + for t in variadic(impersonate) + ] if impersonate else [] + + available_target = next(filter(self._impersonate_target_available, requested_targets), None) + + return available_target, requested_targets + + @staticmethod + def _unavailable_targets_message(requested_targets, note=None, is_error=False): + note = note or 'The extractor specified to use impersonation for this download' + specific_targets = ', '.join(filter(None, map(str, requested_targets))) + message = ( + 'no impersonate target is available' if not specific_targets + else f'none of these impersonate targets are available: {specific_targets}') + return ( + f'{note}, but {message}. {"See" if is_error else "If you encounter errors, then see"}' + f' https://github.com/yt-dlp/yt-dlp#impersonation ' + f'for information on installing the required dependencies') + + def urlopen(self, req): + """ Start an HTTP download """ + if isinstance(req, str): + req = Request(req) + elif isinstance(req, urllib.request.Request): + self.deprecation_warning( + 'Passing a urllib.request.Request object to YoutubeDL.urlopen() is deprecated. ' + 'Use yt_dlp.networking.common.Request instead.') + req = urllib_req_to_req(req) + assert isinstance(req, Request) + + # compat: Assume user:pass url params are basic auth + url, basic_auth_header = extract_basic_auth(req.url) + if basic_auth_header: + req.headers['Authorization'] = basic_auth_header + req.url = sanitize_url(url) + + clean_proxies(proxies=req.proxies, headers=req.headers) + clean_headers(req.headers) + + try: + return self._request_director.send(req) + except NoSupportingHandlers as e: + for ue in e.unsupported_errors: + # FIXME: This depends on the order of errors. + if not (ue.handler and ue.msg): + continue + if ue.handler.RH_KEY == 'Urllib' and 'unsupported url scheme: "file"' in ue.msg.lower(): + raise RequestError( + 'file:// URLs are disabled by default in yt-dlp for security reasons. ' + 'Use --enable-file-urls to enable at your own risk.', cause=ue) from ue + if ( + 'unsupported proxy type: "https"' in ue.msg.lower() + and 'requests' not in self._request_director.handlers + and 'curl_cffi' not in self._request_director.handlers + ): + raise RequestError( + 'To use an HTTPS proxy for this request, one of the following dependencies needs to be installed: requests, curl_cffi') + + elif ( + re.match(r'unsupported url scheme: "wss?"', ue.msg.lower()) + and 'websockets' not in self._request_director.handlers + ): + raise RequestError( + 'This request requires WebSocket support. ' + 'Ensure one of the following dependencies are installed: websockets', + cause=ue) from ue + + elif re.match(r'unsupported (?:extensions: impersonate|impersonate target)', ue.msg.lower()): + raise RequestError( + f'Impersonate target "{req.extensions["impersonate"]}" is not available.' + f' See --list-impersonate-targets for available targets.' + f' This request requires browser impersonation, however you may be missing dependencies' + f' required to support this target.') + raise + except SSLError as e: + if 'UNSAFE_LEGACY_RENEGOTIATION_DISABLED' in str(e): + raise RequestError('UNSAFE_LEGACY_RENEGOTIATION_DISABLED: Try using --legacy-server-connect', cause=e) from e + elif 'SSLV3_ALERT_HANDSHAKE_FAILURE' in str(e): + raise RequestError( + 'SSLV3_ALERT_HANDSHAKE_FAILURE: The server may not support the current cipher list. ' + 'Try using --legacy-server-connect', cause=e) from e + raise + + def build_request_director(self, handlers, preferences=None): + logger = _YDLLogger(self) + headers = self.params['http_headers'].copy() + proxies = self.proxies.copy() + clean_headers(headers) + clean_proxies(proxies, headers) + + director = RequestDirector(logger=logger, verbose=self.params.get('debug_printtraffic')) + for handler in handlers: + director.add_handler(handler( + logger=logger, + headers=headers, + cookiejar=self.cookiejar, + proxies=proxies, + prefer_system_certs='no-certifi' in self.params['compat_opts'], + verify=not self.params.get('nocheckcertificate'), + **traverse_obj(self.params, { + 'verbose': 'debug_printtraffic', + 'source_address': 'source_address', + 'timeout': 'socket_timeout', + 'legacy_ssl_support': 'legacyserverconnect', + 'enable_file_urls': 'enable_file_urls', + 'impersonate': 'impersonate', + 'client_cert': { + 'client_certificate': 'client_certificate', + 'client_certificate_key': 'client_certificate_key', + 'client_certificate_password': 'client_certificate_password', + }, + }), + )) + director.preferences.update(preferences or []) + if 'prefer-legacy-http-handler' in self.params['compat_opts']: + director.preferences.add(lambda rh, _: 500 if rh.RH_KEY == 'Urllib' else 0) + return director + + @functools.cached_property + def _request_director(self): + return self.build_request_director(_REQUEST_HANDLERS.values(), _RH_PREFERENCES) + + def encode(self, s): + if isinstance(s, bytes): + return s # Already encoded + + try: + return s.encode(self.get_encoding()) + except UnicodeEncodeError as err: + err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.' + raise + + def get_encoding(self): + encoding = self.params.get('encoding') + if encoding is None: + encoding = preferredencoding() + return encoding + + def _write_info_json(self, label, ie_result, infofn, overwrite=None): + """ Write infojson and returns True = written, 'exists' = Already exists, False = skip, None = error """ + if overwrite is None: + overwrite = self.params.get('overwrites', True) + if not self.params.get('writeinfojson'): + return False + elif not infofn: + self.write_debug(f'Skipping writing {label} infojson') + return False + elif not self._ensure_dir_exists(infofn): + return None + elif not overwrite and os.path.exists(infofn): + self.to_screen(f'[info] {label.title()} metadata is already present') + return 'exists' + + self.to_screen(f'[info] Writing {label} metadata as JSON to: {infofn}') + try: + write_json_file(self.sanitize_info(ie_result, self.params.get('clean_infojson', True)), infofn) + return True + except OSError: + self.report_error(f'Cannot write {label} metadata to JSON file {infofn}') + return None + + def _write_description(self, label, ie_result, descfn): + """ Write description and returns True = written, False = skip, None = error """ + if not self.params.get('writedescription'): + return False + elif not descfn: + self.write_debug(f'Skipping writing {label} description') + return False + elif not self._ensure_dir_exists(descfn): + return None + elif not self.params.get('overwrites', True) and os.path.exists(descfn): + self.to_screen(f'[info] {label.title()} description is already present') + elif ie_result.get('description') is None: + self.to_screen(f'[info] There\'s no {label} description to write') + return False + else: + try: + self.to_screen(f'[info] Writing {label} description to: {descfn}') + with open(descfn, 'w', encoding='utf-8') as descfile: + descfile.write(ie_result['description']) + except OSError: + self.report_error(f'Cannot write {label} description file {descfn}') + return None + return True + + def _write_subtitles(self, info_dict, filename): + """ Write subtitles to file and return list of (sub_filename, final_sub_filename); or None if error""" + ret = [] + subtitles = info_dict.get('requested_subtitles') + if not (self.params.get('writesubtitles') or self.params.get('writeautomaticsub')): + # subtitles download errors are already managed as troubles in relevant IE + # that way it will silently go on when used with unsupporting IE + return ret + elif not subtitles: + self.to_screen('[info] There are no subtitles for the requested languages') + return ret + sub_filename_base = self.prepare_filename(info_dict, 'subtitle') + if not sub_filename_base: + self.to_screen('[info] Skipping writing video subtitles') + return ret + + for sub_lang, sub_info in subtitles.items(): + sub_format = sub_info['ext'] + sub_filename = subtitles_filename(filename, sub_lang, sub_format, info_dict.get('ext')) + sub_filename_final = subtitles_filename(sub_filename_base, sub_lang, sub_format, info_dict.get('ext')) + existing_sub = self.existing_file((sub_filename_final, sub_filename)) + if existing_sub: + self.to_screen(f'[info] Video subtitle {sub_lang}.{sub_format} is already present') + sub_info['filepath'] = existing_sub + ret.append((existing_sub, sub_filename_final)) + continue + + self.to_screen(f'[info] Writing video subtitles to: {sub_filename}') + if sub_info.get('data') is not None: + try: + # Use newline='' to prevent conversion of newline characters + # See https://github.com/ytdl-org/youtube-dl/issues/10268 + with open(sub_filename, 'w', encoding='utf-8', newline='') as subfile: + subfile.write(sub_info['data']) + sub_info['filepath'] = sub_filename + ret.append((sub_filename, sub_filename_final)) + continue + except OSError: + self.report_error(f'Cannot write video subtitles file {sub_filename}') + return None + + try: + sub_copy = sub_info.copy() + sub_copy.setdefault('http_headers', info_dict.get('http_headers')) + self.dl(sub_filename, sub_copy, subtitle=True) + sub_info['filepath'] = sub_filename + ret.append((sub_filename, sub_filename_final)) + except (DownloadError, ExtractorError, OSError, ValueError, *network_exceptions) as err: + msg = f'Unable to download video subtitles for {sub_lang!r}: {err}' + if self.params.get('ignoreerrors') is not True: # False or 'only_download' + if not self.params.get('ignoreerrors'): + self.report_error(msg) + raise DownloadError(msg) + self.report_warning(msg) + return ret + + def _write_thumbnails(self, label, info_dict, filename, thumb_filename_base=None): + """ Write thumbnails to file and return list of (thumb_filename, final_thumb_filename); or None if error """ + write_all = self.params.get('write_all_thumbnails', False) + thumbnails, ret = [], [] + if write_all or self.params.get('writethumbnail', False): + thumbnails = info_dict.get('thumbnails') or [] + if not thumbnails: + self.to_screen(f'[info] There are no {label} thumbnails to download') + return ret + multiple = write_all and len(thumbnails) > 1 + + if thumb_filename_base is None: + thumb_filename_base = filename + if thumbnails and not thumb_filename_base: + self.write_debug(f'Skipping writing {label} thumbnail') + return ret + + if thumbnails and not self._ensure_dir_exists(filename): + return None + + for idx, t in list(enumerate(thumbnails))[::-1]: + thumb_ext = t.get('ext') or determine_ext(t['url'], 'jpg') + if multiple: + thumb_ext = f'{t["id"]}.{thumb_ext}' + thumb_display_id = f'{label} thumbnail {t["id"]}' + thumb_filename = replace_extension(filename, thumb_ext, info_dict.get('ext')) + thumb_filename_final = replace_extension(thumb_filename_base, thumb_ext, info_dict.get('ext')) + + existing_thumb = self.existing_file((thumb_filename_final, thumb_filename)) + if existing_thumb: + self.to_screen('[info] {} is already present'.format(( + thumb_display_id if multiple else f'{label} thumbnail').capitalize())) + t['filepath'] = existing_thumb + ret.append((existing_thumb, thumb_filename_final)) + else: + self.to_screen(f'[info] Downloading {thumb_display_id} ...') + try: + uf = self.urlopen(Request(t['url'], headers=t.get('http_headers', {}))) + self.to_screen(f'[info] Writing {thumb_display_id} to: {thumb_filename}') + with open(thumb_filename, 'wb') as thumbf: + shutil.copyfileobj(uf, thumbf) + ret.append((thumb_filename, thumb_filename_final)) + t['filepath'] = thumb_filename + except network_exceptions as err: + if isinstance(err, HTTPError) and err.status == 404: + self.to_screen(f'[info] {thumb_display_id.title()} does not exist') + else: + self.report_warning(f'Unable to download {thumb_display_id}: {err}') + thumbnails.pop(idx) + if ret and not write_all: + break + return ret diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/__init__.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2f6ba478326e89ad599f25c26fa3ecee2efe9d2a --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/__init__.py @@ -0,0 +1,1113 @@ +import sys + +if sys.version_info < (3, 10): + raise ImportError( + f'You are using an unsupported version of Python. Only Python versions 3.10 and above are supported by yt-dlp') # noqa: F541 + +__license__ = 'The Unlicense' + +import collections +import getpass +import itertools +import optparse +import os +import re +import traceback + +from .cookies import SUPPORTED_BROWSERS, SUPPORTED_KEYRINGS, CookieLoadError +from .downloader.external import get_external_downloader +from .extractor import list_extractor_classes +from .extractor.adobepass import MSO_INFO +from .networking.impersonate import ImpersonateTarget +from .globals import IN_CLI, plugin_dirs +from .options import parseOpts +from .plugins import load_all_plugins as _load_all_plugins +from .postprocessor import ( + FFmpegExtractAudioPP, + FFmpegMergerPP, + FFmpegPostProcessor, + FFmpegSubtitlesConvertorPP, + FFmpegThumbnailsConvertorPP, + FFmpegVideoConvertorPP, + FFmpegVideoRemuxerPP, + MetadataFromFieldPP, + MetadataParserPP, +) +from .update import Updater +from .utils import ( + NO_DEFAULT, + POSTPROCESS_WHEN, + DateRange, + DownloadCancelled, + DownloadError, + FormatSorter, + GeoUtils, + PlaylistEntries, + SameFileError, + download_range_func, + expand_path, + float_or_none, + format_field, + int_or_none, + join_nonempty, + match_filter_func, + parse_bytes, + parse_duration, + preferredencoding, + read_batch_urls, + read_stdin, + render_table, + setproctitle, + shell_quote, + variadic, + write_string, + +) +from .utils._utils import _UnsafeExtensionError +from .utils._jsruntime import ( + BunJsRuntime as _BunJsRuntime, + DenoJsRuntime as _DenoJsRuntime, + NodeJsRuntime as _NodeJsRuntime, + QuickJsRuntime as _QuickJsRuntime, +) +from .YoutubeDL import YoutubeDL + + +def _exit(status=0, *args): + for msg in args: + sys.stderr.write(msg) + raise SystemExit(status) + + +def get_urls(urls, batchfile, verbose): + """ + @param verbose -1: quiet, 0: normal, 1: verbose + """ + batch_urls = [] + if batchfile is not None: + try: + batch_urls = read_batch_urls( + read_stdin(None if verbose == -1 else 'URLs') if batchfile == '-' + else open(expand_path(batchfile), encoding='utf-8', errors='ignore')) + if verbose == 1: + write_string('[debug] Batch file urls: ' + repr(batch_urls) + '\n') + except OSError: + _exit(f'ERROR: batch file {batchfile} could not be read') + _enc = preferredencoding() + return [ + url.strip().decode(_enc, 'ignore') if isinstance(url, bytes) else url.strip() + for url in batch_urls + urls] + + +def print_extractor_information(opts, urls): + out = '' + if opts.list_extractors: + # Importing GenericIE is currently slow since it imports YoutubeIE + from .extractor.generic import GenericIE + + urls = dict.fromkeys(urls, False) + for ie in list_extractor_classes(opts.age_limit): + out += ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie.working() else '') + '\n' + if ie == GenericIE: + matched_urls = [url for url, matched in urls.items() if not matched] + else: + matched_urls = tuple(filter(ie.suitable, urls.keys())) + urls.update(dict.fromkeys(matched_urls, True)) + out += ''.join(f' {url}\n' for url in matched_urls) + elif opts.list_extractor_descriptions: + _SEARCHES = ('cute kittens', 'slithering pythons', 'falling cat', 'angry poodle', 'purple fish', 'running tortoise', 'sleeping bunny', 'burping cow') + out = '\n'.join( + ie.description(markdown=False, search_examples=_SEARCHES) + for ie in list_extractor_classes(opts.age_limit) if ie.working() and ie.IE_DESC is not False) + elif opts.ap_list_mso: + out = 'Supported TV Providers:\n{}\n'.format(render_table( + ['mso', 'mso name'], + [[mso_id, mso_info['name']] for mso_id, mso_info in MSO_INFO.items()])) + else: + return False + write_string(out, out=sys.stdout) + return True + + +def set_compat_opts(opts): + def _unused_compat_opt(name): + if name not in opts.compat_opts: + return False + opts.compat_opts.discard(name) + opts.compat_opts.update([f'*{name}']) + return True + + def set_default_compat(compat_name, opt_name, default=True, remove_compat=True): + attr = getattr(opts, opt_name) + if compat_name in opts.compat_opts: + if attr is None: + setattr(opts, opt_name, not default) + return True + else: + if remove_compat: + _unused_compat_opt(compat_name) + return False + elif attr is None: + setattr(opts, opt_name, default) + return None + + set_default_compat('abort-on-error', 'ignoreerrors', 'only_download') + set_default_compat('no-playlist-metafiles', 'allow_playlist_files') + set_default_compat('no-clean-infojson', 'clean_infojson') + if 'no-attach-info-json' in opts.compat_opts: + if opts.embed_infojson: + _unused_compat_opt('no-attach-info-json') + else: + opts.embed_infojson = False + if 'format-sort' in opts.compat_opts: + opts.format_sort.extend(FormatSorter.ytdl_default) + elif 'prefer-vp9-sort' in opts.compat_opts: + FormatSorter.default = FormatSorter._prefer_vp9_sort + + if 'mtime-by-default' in opts.compat_opts: + if opts.updatetime is None: + opts.updatetime = True + else: + _unused_compat_opt('mtime-by-default') + + _video_multistreams_set = set_default_compat('multistreams', 'allow_multiple_video_streams', False, remove_compat=False) + _audio_multistreams_set = set_default_compat('multistreams', 'allow_multiple_audio_streams', False, remove_compat=False) + if _video_multistreams_set is False and _audio_multistreams_set is False: + _unused_compat_opt('multistreams') + if 'filename' in opts.compat_opts: + if opts.outtmpl.get('default') is None: + opts.outtmpl.update({'default': '%(title)s-%(id)s.%(ext)s'}) + else: + _unused_compat_opt('filename') + + +def validate_options(opts): + def validate(cndn, name, value=None, msg=None): + if cndn: + return True + raise ValueError((msg or 'invalid {name} "{value}" given').format(name=name, value=value)) + + def validate_in(name, value, items, msg=None): + return validate(value is None or value in items, name, value, msg) + + def validate_regex(name, value, regex): + return validate(value is None or re.match(regex, value), name, value) + + def validate_positive(name, value, strict=False): + return validate(value is None or value > 0 or (not strict and value == 0), + name, value, '{name} "{value}" must be positive' + ('' if strict else ' or 0')) + + def validate_minmax(min_val, max_val, min_name, max_name=None): + if max_val is None or min_val is None or max_val >= min_val: + return + if not max_name: + min_name, max_name = f'min {min_name}', f'max {min_name}' + raise ValueError(f'{max_name} "{max_val}" must be must be greater than or equal to {min_name} "{min_val}"') + + # Usernames and passwords + validate(sum(map(bool, (opts.usenetrc, opts.netrc_cmd, opts.username))) <= 1, '.netrc', + msg='{name}, netrc command and username/password are mutually exclusive options') + validate(opts.password is None or opts.username is not None, 'account username', msg='{name} missing') + validate(opts.ap_password is None or opts.ap_username is not None, + 'TV Provider account username', msg='{name} missing') + validate_in('TV Provider', opts.ap_mso, MSO_INFO, + 'Unsupported {name} "{value}", use --ap-list-mso to get a list of supported TV Providers') + + # Numbers + validate_positive('autonumber start', opts.autonumber_start) + validate_positive('autonumber size', opts.autonumber_size, True) + validate_positive('concurrent fragments', opts.concurrent_fragment_downloads, True) + validate_positive('playlist start', opts.playliststart, True) + if opts.playlistend != -1: + validate_minmax(opts.playliststart, opts.playlistend, 'playlist start', 'playlist end') + + # Time ranges + validate_positive('subtitles sleep interval', opts.sleep_interval_subtitles) + validate_positive('requests sleep interval', opts.sleep_interval_requests) + validate_positive('sleep interval', opts.sleep_interval) + validate_positive('max sleep interval', opts.max_sleep_interval) + if opts.sleep_interval is None: + validate( + opts.max_sleep_interval is None, 'min sleep interval', + msg='{name} must be specified; use --min-sleep-interval') + elif opts.max_sleep_interval is None: + opts.max_sleep_interval = opts.sleep_interval + else: + validate_minmax(opts.sleep_interval, opts.max_sleep_interval, 'sleep interval') + + if opts.wait_for_video is not None: + min_wait, max_wait, *_ = map(parse_duration, [*opts.wait_for_video.split('-', 1), None]) + validate(min_wait is not None and not (max_wait is None and '-' in opts.wait_for_video), + 'time range to wait for video', opts.wait_for_video) + validate_minmax(min_wait, max_wait, 'time range to wait for video') + opts.wait_for_video = (min_wait, max_wait) + + # Format sort + for f in opts.format_sort: + validate_regex('format sorting', f, FormatSorter.regex) + + # Postprocessor formats + if opts.convertsubtitles == 'none': + opts.convertsubtitles = None + if opts.convertthumbnails == 'none': + opts.convertthumbnails = None + + validate_regex('merge output format', opts.merge_output_format, + r'({0})(/({0}))*'.format('|'.join(map(re.escape, FFmpegMergerPP.SUPPORTED_EXTS)))) + validate_regex('audio format', opts.audioformat, FFmpegExtractAudioPP.FORMAT_RE) + validate_in('subtitle format', opts.convertsubtitles, FFmpegSubtitlesConvertorPP.SUPPORTED_EXTS) + validate_regex('thumbnail format', opts.convertthumbnails, FFmpegThumbnailsConvertorPP.FORMAT_RE) + validate_regex('recode video format', opts.recodevideo, FFmpegVideoConvertorPP.FORMAT_RE) + validate_regex('remux video format', opts.remuxvideo, FFmpegVideoRemuxerPP.FORMAT_RE) + if opts.audioquality: + opts.audioquality = opts.audioquality.strip('k').strip('K') + # int_or_none prevents inf, nan + validate_positive('audio quality', int_or_none(float_or_none(opts.audioquality), default=0)) + + # Retries + def parse_retries(name, value): + if value is None: + return None + elif value in ('inf', 'infinite'): + return float('inf') + try: + int_value = int(value) + except (TypeError, ValueError): + validate(False, f'{name} retry count', value) + validate_positive(f'{name} retry count', int_value) + return int_value + + opts.retries = parse_retries('download', opts.retries) + opts.fragment_retries = parse_retries('fragment', opts.fragment_retries) + opts.extractor_retries = parse_retries('extractor', opts.extractor_retries) + opts.file_access_retries = parse_retries('file access', opts.file_access_retries) + + # Retry sleep function + def parse_sleep_func(expr): + NUMBER_RE = r'\d+(?:\.\d+)?' + op, start, limit, step, *_ = (*tuple(re.fullmatch( + rf'(?:(linear|exp)=)?({NUMBER_RE})(?::({NUMBER_RE})?)?(?::({NUMBER_RE}))?', + expr.strip()).groups()), None, None) + + if op == 'exp': + return lambda n: min(float(start) * (float(step or 2) ** n), float(limit or 'inf')) + else: + default_step = start if op or limit else 0 + return lambda n: min(float(start) + float(step or default_step) * n, float(limit or 'inf')) + + for key, expr in opts.retry_sleep.items(): + if not expr: + del opts.retry_sleep[key] + continue + try: + opts.retry_sleep[key] = parse_sleep_func(expr) + except AttributeError: + raise ValueError(f'invalid {key} retry sleep expression {expr!r}') + + # Bytes + def validate_bytes(name, value, strict_positive=False): + if value is None: + return None + numeric_limit = parse_bytes(value) + validate(numeric_limit is not None, name, value) + if strict_positive: + validate_positive(name, numeric_limit, True) + return numeric_limit + + opts.ratelimit = validate_bytes('rate limit', opts.ratelimit, True) + opts.throttledratelimit = validate_bytes('throttled rate limit', opts.throttledratelimit) + opts.min_filesize = validate_bytes('min filesize', opts.min_filesize) + opts.max_filesize = validate_bytes('max filesize', opts.max_filesize) + opts.buffersize = validate_bytes('buffer size', opts.buffersize, True) + opts.http_chunk_size = validate_bytes('http chunk size', opts.http_chunk_size) + + # Output templates + def validate_outtmpl(tmpl, msg): + err = YoutubeDL.validate_outtmpl(tmpl) + if err: + raise ValueError(f'invalid {msg} "{tmpl}": {err}') + + for k, tmpl in opts.outtmpl.items(): + validate_outtmpl(tmpl, f'{k} output template') + for type_, tmpl_list in opts.forceprint.items(): + for tmpl in tmpl_list: + validate_outtmpl(tmpl, f'{type_} print template') + for type_, tmpl_list in opts.print_to_file.items(): + for tmpl, file in tmpl_list: + validate_outtmpl(tmpl, f'{type_} print to file template') + validate_outtmpl(file, f'{type_} print to file filename') + validate_outtmpl(opts.sponsorblock_chapter_title, 'SponsorBlock chapter title') + for k, tmpl in opts.progress_template.items(): + k = f'{k[:-6]} console title' if '-title' in k else f'{k} progress' + validate_outtmpl(tmpl, f'{k} template') + + outtmpl_default = opts.outtmpl.get('default') + if outtmpl_default == '': + opts.skip_download = None + del opts.outtmpl['default'] + + def parse_chapters(name, value, advanced=False): + parse_timestamp = lambda x: float('inf') if x in ('inf', 'infinite') else parse_duration(x) + TIMESTAMP_RE = r'''(?x)(?: + (?P-?)(?P[^-]+) + )?\s*-\s*(?: + (?P-?)(?P[^-]+) + )?''' + + chapters, ranges, from_url = [], [], False + for regex in value or []: + if advanced and regex == '*from-url': + from_url = True + continue + elif not regex.startswith('*'): + try: + chapters.append(re.compile(regex)) + except re.error as err: + raise ValueError(f'invalid {name} regex "{regex}" - {err}') + continue + + for range_ in map(str.strip, regex[1:].split(',')): + mobj = range_ != '-' and re.fullmatch(TIMESTAMP_RE, range_) + dur = mobj and [parse_timestamp(mobj.group('start') or '0'), parse_timestamp(mobj.group('end') or 'inf')] + signs = mobj and (mobj.group('start_sign'), mobj.group('end_sign')) + + err = None + if None in (dur or [None]): + err = 'Must be of the form "*start-end"' + elif not advanced and any(signs): + err = 'Negative timestamps are not allowed' + else: + dur[0] *= -1 if signs[0] else 1 + dur[1] *= -1 if signs[1] else 1 + if dur[1] == float('-inf'): + err = '"-inf" is not a valid end' + if err: + raise ValueError(f'invalid {name} time range "{regex}". {err}') + ranges.append(dur) + + return chapters, ranges, from_url + + opts.remove_chapters, opts.remove_ranges, _ = parse_chapters('--remove-chapters', opts.remove_chapters) + opts.download_ranges = download_range_func(*parse_chapters('--download-sections', opts.download_ranges, True)) + + # Cookies from browser + if opts.cookiesfrombrowser: + container = None + mobj = re.fullmatch(r'''(?x) + (?P[^+:]+) + (?:\s*\+\s*(?P[^:]+))? + (?:\s*:\s*(?!:)(?P.+?))? + (?:\s*::\s*(?P.+))? + ''', opts.cookiesfrombrowser) + if mobj is None: + raise ValueError(f'invalid cookies from browser arguments: {opts.cookiesfrombrowser}') + browser_name, keyring, profile, container = mobj.group('name', 'keyring', 'profile', 'container') + browser_name = browser_name.lower() + if browser_name not in SUPPORTED_BROWSERS: + raise ValueError(f'unsupported browser specified for cookies: "{browser_name}". ' + f'Supported browsers are: {", ".join(sorted(SUPPORTED_BROWSERS))}') + if keyring is not None: + keyring = keyring.upper() + if keyring not in SUPPORTED_KEYRINGS: + raise ValueError(f'unsupported keyring specified for cookies: "{keyring}". ' + f'Supported keyrings are: {", ".join(sorted(SUPPORTED_KEYRINGS))}') + opts.cookiesfrombrowser = (browser_name, profile, keyring, container) + + if opts.impersonate is not None: + opts.impersonate = ImpersonateTarget.from_str(opts.impersonate.lower()) + + # MetadataParser + def metadataparser_actions(f): + if isinstance(f, str): + cmd = f'--parse-metadata {shell_quote(f)}' + try: + actions = [MetadataFromFieldPP.to_action(f)] + except Exception as err: + raise ValueError(f'{cmd} is invalid; {err}') + else: + cmd = f'--replace-in-metadata {shell_quote(f)}' + actions = ((MetadataParserPP.Actions.REPLACE, x, *f[1:]) for x in f[0].split(',')) + + for action in actions: + try: + MetadataParserPP.validate_action(*action) + except Exception as err: + raise ValueError(f'{cmd} is invalid; {err}') + yield action + + if opts.metafromtitle is not None: + opts.parse_metadata.setdefault('pre_process', []).append(f'title:{opts.metafromtitle}') + opts.parse_metadata = { + k: list(itertools.chain(*map(metadataparser_actions, v))) + for k, v in opts.parse_metadata.items() + } + + # Other options + opts.plugin_dirs = opts.plugin_dirs + if opts.plugin_dirs is None: + opts.plugin_dirs = ['default'] + + if opts.playlist_items is not None: + try: + tuple(PlaylistEntries.parse_playlist_items(opts.playlist_items)) + except Exception as err: + raise ValueError(f'Invalid playlist-items {opts.playlist_items!r}: {err}') + + opts.geo_bypass_country, opts.geo_bypass_ip_block = None, None + if opts.geo_bypass.lower() not in ('default', 'never'): + try: + GeoUtils.random_ipv4(opts.geo_bypass) + except Exception: + raise ValueError(f'Unsupported --xff "{opts.geo_bypass}"') + if len(opts.geo_bypass) == 2: + opts.geo_bypass_country = opts.geo_bypass + else: + opts.geo_bypass_ip_block = opts.geo_bypass + opts.geo_bypass = opts.geo_bypass.lower() != 'never' + + opts.match_filter = match_filter_func(opts.match_filter, opts.breaking_match_filter) + + if opts.download_archive is not None: + opts.download_archive = expand_path(opts.download_archive) + + if opts.ffmpeg_location is not None: + opts.ffmpeg_location = expand_path(opts.ffmpeg_location) + + if opts.user_agent is not None: + opts.headers.setdefault('User-Agent', opts.user_agent) + if opts.referer is not None: + opts.headers.setdefault('Referer', opts.referer) + + if opts.no_sponsorblock: + opts.sponsorblock_mark = opts.sponsorblock_remove = set() + + default_downloader = None + for proto, path in opts.external_downloader.items(): + if path == 'native': + continue + ed = get_external_downloader(path) + if ed is None: + raise ValueError( + f'No such {format_field(proto, None, "%s ", ignore="default")}external downloader "{path}"') + elif ed and proto == 'default': + default_downloader = ed.get_basename() + + for policy in opts.color.values(): + if policy not in ('always', 'auto', 'auto-tty', 'no_color', 'no_color-tty', 'never'): + raise ValueError(f'"{policy}" is not a valid color policy') + + warnings, deprecation_warnings = [], [] + + # Common mistake: -f best + if opts.format == 'best': + warnings.append('.\n '.join(( + '"-f best" selects the best pre-merged format which is often not the best option', + 'To let yt-dlp download and merge the best available formats, simply do not pass any format selection', + 'If you know what you are doing and want only the best pre-merged format, use "-f b" instead to suppress this warning'))) + + # Common mistake: -f mp4 + if opts.format == 'mp4': + warnings.append('.\n '.join(( + '"-f mp4" selects the best pre-merged mp4 format which is often not what\'s intended', + 'Pre-merged mp4 formats are not available from all sites, or may only be available in lower quality', + 'To prioritize the best h264 video and aac audio in an mp4 container, use "-t mp4" instead', + 'If you know what you are doing and want a pre-merged mp4 format, use "-f b[ext=mp4]" instead to suppress this warning'))) + + # --(postprocessor/downloader)-args without name + def report_args_compat(name, value, key1, key2=None, where=None): + if key1 in value and key2 not in value: + warnings.append(f'{name.title()} arguments given without specifying name. ' + f'The arguments will be given to {where or f"all {name}s"}') + return True + return False + + if report_args_compat('external downloader', opts.external_downloader_args, + 'default', where=default_downloader) and default_downloader: + # Compat with youtube-dl's behavior. See https://github.com/ytdl-org/youtube-dl/commit/49c5293014bc11ec8c009856cd63cffa6296c1e1 + opts.external_downloader_args.setdefault(default_downloader, opts.external_downloader_args.pop('default')) + + if report_args_compat('post-processor', opts.postprocessor_args, 'default-compat', 'default'): + opts.postprocessor_args['default'] = opts.postprocessor_args.pop('default-compat') + + def report_conflict(arg1, opt1, arg2='--allow-unplayable-formats', opt2='allow_unplayable_formats', + val1=NO_DEFAULT, val2=NO_DEFAULT, default=False): + if val2 is NO_DEFAULT: + val2 = getattr(opts, opt2) + if not val2: + return + + if val1 is NO_DEFAULT: + val1 = getattr(opts, opt1) + if val1: + warnings.append(f'{arg1} is ignored since {arg2} was given') + setattr(opts, opt1, default) + + # Conflicting options + report_conflict('--playlist-reverse', 'playlist_reverse', '--playlist-random', 'playlist_random') + report_conflict('--playlist-reverse', 'playlist_reverse', '--lazy-playlist', 'lazy_playlist') + report_conflict('--playlist-random', 'playlist_random', '--lazy-playlist', 'lazy_playlist') + report_conflict('--dateafter', 'dateafter', '--date', 'date', default=None) + report_conflict('--datebefore', 'datebefore', '--date', 'date', default=None) + report_conflict('--exec-before-download', 'exec_before_dl_cmd', + '"--exec before_dl:"', 'exec_cmd', val2=opts.exec_cmd.get('before_dl')) + report_conflict('--id', 'useid', '--output', 'outtmpl', val2=opts.outtmpl.get('default')) + report_conflict('--remux-video', 'remuxvideo', '--recode-video', 'recodevideo') + + # Conflicts with --allow-unplayable-formats + report_conflict('--embed-metadata', 'addmetadata') + report_conflict('--embed-chapters', 'addchapters') + report_conflict('--embed-info-json', 'embed_infojson') + report_conflict('--embed-subs', 'embedsubtitles') + report_conflict('--embed-thumbnail', 'embedthumbnail') + report_conflict('--extract-audio', 'extractaudio') + report_conflict('--fixup', 'fixup', val1=opts.fixup not in (None, 'never', 'ignore'), default='never') + report_conflict('--recode-video', 'recodevideo') + report_conflict('--remove-chapters', 'remove_chapters', default=[]) + report_conflict('--remux-video', 'remuxvideo') + report_conflict('--sponsorblock-remove', 'sponsorblock_remove', default=set()) + report_conflict('--xattrs', 'xattrs') + + if hasattr(opts, '_deprecated_options'): + deprecation_warnings.append( + f'The following options have been deprecated: {", ".join(opts._deprecated_options)}\n' + 'Please remove them from your command/configuration to avoid future errors.\n' + 'See https://github.com/yt-dlp/yt-dlp/issues/14198 for more details') + del opts._deprecated_options + + # Dependent options + opts.date = DateRange.day(opts.date) if opts.date else DateRange(opts.dateafter, opts.datebefore) + + if opts.exec_before_dl_cmd: + opts.exec_cmd['before_dl'] = opts.exec_before_dl_cmd + + if opts.useid: # --id is not deprecated in youtube-dl + opts.outtmpl['default'] = '%(id)s.%(ext)s' + + if opts.overwrites: # --force-overwrites implies --no-continue + opts.continue_dl = False + + if (opts.addmetadata or opts.sponsorblock_mark) and opts.addchapters is None: + # Add chapters when adding metadata or marking sponsors + opts.addchapters = True + + if opts.extractaudio and not opts.keepvideo and opts.format is None: + # Do not unnecessarily download audio + opts.format = 'bestaudio/best' + + if opts.getcomments and opts.writeinfojson is None and not opts.embed_infojson: + # If JSON is not printed anywhere, but comments are requested, save it to file + if not opts.dumpjson or opts.print_json or opts.dump_single_json: + opts.writeinfojson = True + + if opts.allsubtitles and not (opts.embedsubtitles or opts.writeautomaticsub): + # --all-sub automatically sets --write-sub if --write-auto-sub is not given + opts.writesubtitles = True + + if opts.addmetadata and opts.embed_infojson is None: + # If embedding metadata and infojson is present, embed it + opts.embed_infojson = 'if_exists' + + # Ask for passwords + if opts.username is not None and opts.password is None: + opts.password = getpass.getpass('Type account password and press [Return]: ') + if opts.ap_username is not None and opts.ap_password is None: + opts.ap_password = getpass.getpass('Type TV provider account password and press [Return]: ') + + # compat option changes global state destructively; only allow from cli + if 'allow-unsafe-ext' in opts.compat_opts: + warnings.append( + 'Using allow-unsafe-ext opens you up to potential attacks. ' + 'Use with great care!') + _UnsafeExtensionError.sanitize_extension = lambda x, prepend=False: x + + return warnings, deprecation_warnings + + +def get_postprocessors(opts): + yield from opts.add_postprocessors + + for when, actions in opts.parse_metadata.items(): + yield { + 'key': 'MetadataParser', + 'actions': actions, + 'when': when, + } + sponsorblock_query = opts.sponsorblock_mark | opts.sponsorblock_remove + if sponsorblock_query: + yield { + 'key': 'SponsorBlock', + 'categories': sponsorblock_query, + 'api': opts.sponsorblock_api, + 'when': 'after_filter', + } + if opts.convertsubtitles: + yield { + 'key': 'FFmpegSubtitlesConvertor', + 'format': opts.convertsubtitles, + 'when': 'before_dl', + } + if opts.convertthumbnails: + yield { + 'key': 'FFmpegThumbnailsConvertor', + 'format': opts.convertthumbnails, + 'when': 'before_dl', + } + if opts.extractaudio: + yield { + 'key': 'FFmpegExtractAudio', + 'preferredcodec': opts.audioformat, + 'preferredquality': opts.audioquality, + 'nopostoverwrites': opts.nopostoverwrites, + } + if opts.remuxvideo: + yield { + 'key': 'FFmpegVideoRemuxer', + 'preferedformat': opts.remuxvideo, + } + if opts.recodevideo: + yield { + 'key': 'FFmpegVideoConvertor', + 'preferedformat': opts.recodevideo, + } + # If ModifyChapters is going to remove chapters, subtitles must already be in the container. + if opts.embedsubtitles: + keep_subs = 'no-keep-subs' not in opts.compat_opts + yield { + 'key': 'FFmpegEmbedSubtitle', + # already_have_subtitle = True prevents the file from being deleted after embedding + 'already_have_subtitle': opts.writesubtitles and keep_subs, + } + if not opts.writeautomaticsub and keep_subs: + opts.writesubtitles = True + + # ModifyChapters must run before FFmpegMetadataPP + if opts.remove_chapters or sponsorblock_query: + yield { + 'key': 'ModifyChapters', + 'remove_chapters_patterns': opts.remove_chapters, + 'remove_sponsor_segments': opts.sponsorblock_remove, + 'remove_ranges': opts.remove_ranges, + 'sponsorblock_chapter_title': opts.sponsorblock_chapter_title, + 'force_keyframes': opts.force_keyframes_at_cuts, + } + # FFmpegMetadataPP should be run after FFmpegVideoConvertorPP and + # FFmpegExtractAudioPP as containers before conversion may not support + # metadata (3gp, webm, etc.) + # By default ffmpeg preserves metadata applicable for both + # source and target containers. From this point the container won't change, + # so metadata can be added here. + if opts.addmetadata or opts.addchapters or opts.embed_infojson: + yield { + 'key': 'FFmpegMetadata', + 'add_chapters': opts.addchapters, + 'add_metadata': opts.addmetadata, + 'add_infojson': opts.embed_infojson, + } + if opts.embedthumbnail: + yield { + 'key': 'EmbedThumbnail', + # already_have_thumbnail = True prevents the file from being deleted after embedding + 'already_have_thumbnail': opts.writethumbnail, + } + if not opts.writethumbnail: + opts.writethumbnail = True + opts.outtmpl['pl_thumbnail'] = '' + if opts.split_chapters: + yield { + 'key': 'FFmpegSplitChapters', + 'force_keyframes': opts.force_keyframes_at_cuts, + } + # XAttrMetadataPP should be run after post-processors that may change file contents + if opts.xattrs: + yield {'key': 'XAttrMetadata'} + if opts.concat_playlist != 'never': + yield { + 'key': 'FFmpegConcat', + 'only_multi_video': opts.concat_playlist != 'always', + 'when': 'playlist', + } + # Exec must be the last PP of each category + for when, exec_cmd in opts.exec_cmd.items(): + yield { + 'key': 'Exec', + 'exec_cmd': exec_cmd, + 'when': when, + } + + +ParsedOptions = collections.namedtuple('ParsedOptions', ('parser', 'options', 'urls', 'ydl_opts')) + + +def parse_options(argv=None): + """@returns ParsedOptions(parser, opts, urls, ydl_opts)""" + parser, opts, urls = parseOpts(argv) + urls = get_urls(urls, opts.batchfile, -1 if opts.quiet and not opts.verbose else opts.verbose) + + set_compat_opts(opts) + try: + warnings, deprecation_warnings = validate_options(opts) + except ValueError as err: + parser.error(f'{err}\n') + + postprocessors = list(get_postprocessors(opts)) + + print_only = bool(opts.forceprint) and all(k not in opts.forceprint for k in POSTPROCESS_WHEN[3:]) + any_getting = any(getattr(opts, k) for k in ( + 'dumpjson', 'dump_single_json', 'getdescription', 'getduration', 'getfilename', + 'getformat', 'getid', 'getthumbnail', 'gettitle', 'geturl', + )) + if opts.quiet is None: + opts.quiet = any_getting or opts.print_json or bool(opts.forceprint) + + playlist_pps = [pp for pp in postprocessors if pp.get('when') == 'playlist'] + write_playlist_infojson = (opts.writeinfojson and not opts.clean_infojson + and opts.allow_playlist_files and opts.outtmpl.get('pl_infojson') != '') + if not any(( + opts.extract_flat, + opts.dump_single_json, + opts.forceprint.get('playlist'), + opts.print_to_file.get('playlist'), + write_playlist_infojson, + )): + if not playlist_pps: + opts.extract_flat = 'discard' + elif playlist_pps == [{'key': 'FFmpegConcat', 'only_multi_video': True, 'when': 'playlist'}]: + opts.extract_flat = 'discard_in_playlist' + + final_ext = ( + opts.recodevideo if opts.recodevideo in FFmpegVideoConvertorPP.SUPPORTED_EXTS + else opts.remuxvideo if opts.remuxvideo in FFmpegVideoRemuxerPP.SUPPORTED_EXTS + else opts.audioformat if (opts.extractaudio and opts.audioformat in FFmpegExtractAudioPP.SUPPORTED_EXTS) + else None) + + js_runtimes = { + runtime.lower(): {'path': path} for runtime, path in ( + [*arg.split(':', 1), None][:2] for arg in opts.js_runtimes)} + + return ParsedOptions(parser, opts, urls, { + 'usenetrc': opts.usenetrc, + 'netrc_location': opts.netrc_location, + 'netrc_cmd': opts.netrc_cmd, + 'username': opts.username, + 'password': opts.password, + 'twofactor': opts.twofactor, + 'videopassword': opts.videopassword, + 'ap_mso': opts.ap_mso, + 'ap_username': opts.ap_username, + 'ap_password': opts.ap_password, + 'client_certificate': opts.client_certificate, + 'client_certificate_key': opts.client_certificate_key, + 'client_certificate_password': opts.client_certificate_password, + 'quiet': opts.quiet, + 'no_warnings': opts.no_warnings, + 'forceurl': opts.geturl, + 'forcetitle': opts.gettitle, + 'forceid': opts.getid, + 'forcethumbnail': opts.getthumbnail, + 'forcedescription': opts.getdescription, + 'forceduration': opts.getduration, + 'forcefilename': opts.getfilename, + 'forceformat': opts.getformat, + 'forceprint': opts.forceprint, + 'print_to_file': opts.print_to_file, + 'forcejson': opts.dumpjson or opts.print_json, + 'dump_single_json': opts.dump_single_json, + 'force_write_download_archive': opts.force_write_download_archive, + 'simulate': (print_only or any_getting or None) if opts.simulate is None else opts.simulate, + 'skip_download': opts.skip_download, + 'format': opts.format, + 'allow_unplayable_formats': opts.allow_unplayable_formats, + 'ignore_no_formats_error': opts.ignore_no_formats_error, + 'format_sort': opts.format_sort, + 'format_sort_force': opts.format_sort_force, + 'allow_multiple_video_streams': opts.allow_multiple_video_streams, + 'allow_multiple_audio_streams': opts.allow_multiple_audio_streams, + 'check_formats': opts.check_formats, + 'listformats': opts.listformats, + 'listformats_table': opts.listformats_table, + 'outtmpl': opts.outtmpl, + 'outtmpl_na_placeholder': opts.outtmpl_na_placeholder, + 'paths': opts.paths, + 'autonumber_size': opts.autonumber_size, + 'autonumber_start': opts.autonumber_start, + 'restrictfilenames': opts.restrictfilenames, + 'windowsfilenames': opts.windowsfilenames, + 'ignoreerrors': opts.ignoreerrors, + 'force_generic_extractor': opts.force_generic_extractor, + 'allowed_extractors': opts.allowed_extractors or ['default'], + 'ratelimit': opts.ratelimit, + 'throttledratelimit': opts.throttledratelimit, + 'overwrites': opts.overwrites, + 'retries': opts.retries, + 'file_access_retries': opts.file_access_retries, + 'fragment_retries': opts.fragment_retries, + 'extractor_retries': opts.extractor_retries, + 'retry_sleep_functions': opts.retry_sleep, + 'skip_unavailable_fragments': opts.skip_unavailable_fragments, + 'keep_fragments': opts.keep_fragments, + 'concurrent_fragment_downloads': opts.concurrent_fragment_downloads, + 'buffersize': opts.buffersize, + 'noresizebuffer': opts.noresizebuffer, + 'http_chunk_size': opts.http_chunk_size, + 'continuedl': opts.continue_dl, + 'noprogress': opts.quiet if opts.noprogress is None else opts.noprogress, + 'progress_with_newline': opts.progress_with_newline, + 'progress_template': opts.progress_template, + 'progress_delta': opts.progress_delta, + 'playliststart': opts.playliststart, + 'playlistend': opts.playlistend, + 'playlistreverse': opts.playlist_reverse, + 'playlistrandom': opts.playlist_random, + 'lazy_playlist': opts.lazy_playlist, + 'noplaylist': opts.noplaylist, + 'logtostderr': opts.outtmpl.get('default') == '-', + 'consoletitle': opts.consoletitle, + 'nopart': opts.nopart, + 'updatetime': opts.updatetime, + 'writedescription': opts.writedescription, + 'writeinfojson': opts.writeinfojson, + 'allow_playlist_files': opts.allow_playlist_files, + 'clean_infojson': opts.clean_infojson, + 'getcomments': opts.getcomments, + 'writethumbnail': opts.writethumbnail is True, + 'write_all_thumbnails': opts.writethumbnail == 'all', + 'writelink': opts.writelink, + 'writeurllink': opts.writeurllink, + 'writewebloclink': opts.writewebloclink, + 'writedesktoplink': opts.writedesktoplink, + 'writesubtitles': opts.writesubtitles, + 'writeautomaticsub': opts.writeautomaticsub, + 'allsubtitles': opts.allsubtitles, + 'listsubtitles': opts.listsubtitles, + 'subtitlesformat': opts.subtitlesformat, + 'subtitleslangs': opts.subtitleslangs, + 'matchtitle': opts.matchtitle, + 'rejecttitle': opts.rejecttitle, + 'max_downloads': opts.max_downloads, + 'prefer_free_formats': opts.prefer_free_formats, + 'trim_file_name': opts.trim_file_name, + 'verbose': opts.verbose, + 'dump_intermediate_pages': opts.dump_intermediate_pages, + 'write_pages': opts.write_pages, + 'load_pages': opts.load_pages, + 'test': opts.test, + 'keepvideo': opts.keepvideo, + 'min_filesize': opts.min_filesize, + 'max_filesize': opts.max_filesize, + 'min_views': opts.min_views, + 'max_views': opts.max_views, + 'daterange': opts.date, + 'cachedir': opts.cachedir, + 'age_limit': opts.age_limit, + 'download_archive': opts.download_archive, + 'break_on_existing': opts.break_on_existing, + 'break_on_reject': opts.break_on_reject, + 'break_per_url': opts.break_per_url, + 'skip_playlist_after_errors': opts.skip_playlist_after_errors, + 'cookiefile': opts.cookiefile, + 'cookiesfrombrowser': opts.cookiesfrombrowser, + 'legacyserverconnect': opts.legacy_server_connect, + 'nocheckcertificate': opts.no_check_certificate, + 'prefer_insecure': opts.prefer_insecure, + 'enable_file_urls': opts.enable_file_urls, + 'http_headers': opts.headers, + 'proxy': opts.proxy, + 'socket_timeout': opts.socket_timeout, + 'bidi_workaround': opts.bidi_workaround, + 'debug_printtraffic': opts.debug_printtraffic, + 'default_search': opts.default_search, + 'dynamic_mpd': opts.dynamic_mpd, + 'extractor_args': opts.extractor_args, + 'encoding': opts.encoding, + 'extract_flat': opts.extract_flat, + 'live_from_start': opts.live_from_start, + 'wait_for_video': opts.wait_for_video, + 'mark_watched': opts.mark_watched, + 'merge_output_format': opts.merge_output_format, + 'final_ext': final_ext, + 'postprocessors': postprocessors, + 'fixup': opts.fixup, + 'source_address': opts.source_address, + 'impersonate': opts.impersonate, + 'sleep_interval_requests': opts.sleep_interval_requests, + 'sleep_interval': opts.sleep_interval, + 'max_sleep_interval': opts.max_sleep_interval, + 'sleep_interval_subtitles': opts.sleep_interval_subtitles, + 'external_downloader': opts.external_downloader, + 'download_ranges': opts.download_ranges, + 'force_keyframes_at_cuts': opts.force_keyframes_at_cuts, + 'list_thumbnails': opts.list_thumbnails, + 'playlist_items': opts.playlist_items, + 'match_filter': opts.match_filter, + 'color': opts.color, + 'ffmpeg_location': opts.ffmpeg_location, + 'hls_prefer_native': opts.hls_prefer_native, + 'hls_use_mpegts': opts.hls_use_mpegts, + 'hls_split_discontinuity': opts.hls_split_discontinuity, + 'external_downloader_args': opts.external_downloader_args, + 'postprocessor_args': opts.postprocessor_args, + 'geo_verification_proxy': opts.geo_verification_proxy, + 'geo_bypass': opts.geo_bypass, + 'geo_bypass_country': opts.geo_bypass_country, + 'geo_bypass_ip_block': opts.geo_bypass_ip_block, + 'useid': opts.useid or None, + 'js_runtimes': js_runtimes, + 'remote_components': opts.remote_components, + 'warn_when_outdated': opts.update_self is None, + '_warnings': warnings, + '_deprecation_warnings': deprecation_warnings, + 'compat_opts': opts.compat_opts, + }) + + +def _real_main(argv=None): + setproctitle('yt-dlp') + + parser, opts, all_urls, ydl_opts = parse_options(argv) + + if print_extractor_information(opts, all_urls): + return + + # We may need ffmpeg_location without having access to the YoutubeDL instance + # See https://github.com/yt-dlp/yt-dlp/issues/2191 + if opts.ffmpeg_location: + FFmpegPostProcessor._ffmpeg_location.set(opts.ffmpeg_location) + + # load all plugins into the global lookup + plugin_dirs.value = opts.plugin_dirs + if plugin_dirs.value: + _load_all_plugins() + + with YoutubeDL(ydl_opts) as ydl: + pre_process = opts.update_self or opts.rm_cachedir + actual_use = all_urls or opts.load_info_filename + + if opts.rm_cachedir: + ydl.cache.remove() + + try: + updater = Updater(ydl, opts.update_self) + if opts.update_self and updater.update() and actual_use and updater.cmd: + return updater.restart() + except Exception: + traceback.print_exc() + ydl._download_retcode = 100 + + if opts.list_impersonate_targets: + + known_targets = [ + # List of simplified targets we know are supported, + # to help users know what dependencies may be required. + (ImpersonateTarget('chrome'), 'curl_cffi'), + (ImpersonateTarget('safari'), 'curl_cffi'), + (ImpersonateTarget('firefox'), 'curl_cffi>=0.10'), + (ImpersonateTarget('edge'), 'curl_cffi'), + (ImpersonateTarget('tor'), 'curl_cffi>=0.11'), + ] + + available_targets = ydl._get_available_impersonate_targets() + + def make_row(target, handler): + return [ + join_nonempty(target.client.title(), target.version, delim='-') or '-', + join_nonempty((target.os or '').title(), target.os_version, delim='-') or '-', + handler, + ] + + rows = [make_row(target, handler) for target, handler in available_targets] + + for known_target, known_handler in known_targets: + if not any( + known_target in target and known_handler.startswith(handler) + for target, handler in available_targets + ): + rows.insert(0, [ + ydl._format_out(text, ydl.Styles.SUPPRESS) + for text in make_row(known_target, f'{known_handler} (unavailable)') + ]) + + ydl.to_screen('[info] Available impersonate targets') + ydl.to_stdout(render_table(['Client', 'OS', 'Source'], rows, extra_gap=2, delim='-')) + return + + if not actual_use: + if pre_process: + return ydl._download_retcode + + args = sys.argv[1:] if argv is None else argv + ydl.warn_if_short_id(args) + + # Show a useful error message and wait for keypress if not launched from shell on Windows + if not args and os.name == 'nt' and getattr(sys, 'frozen', False): + import ctypes.wintypes + import msvcrt + + kernel32 = ctypes.WinDLL('Kernel32') + + buffer = (1 * ctypes.wintypes.DWORD)() + attached_processes = kernel32.GetConsoleProcessList(buffer, 1) + # If we only have a single process attached, then the executable was double clicked + # When using `pyinstaller` with `--onefile`, two processes get attached + is_onefile = hasattr(sys, '_MEIPASS') and os.path.basename(sys._MEIPASS).startswith('_MEI') + if attached_processes == 1 or (is_onefile and attached_processes == 2): + print(parser._generate_error_message( + 'Do not double-click the executable, instead call it from a command line.\n' + 'Please read the README for further information on how to use yt-dlp: ' + 'https://github.com/yt-dlp/yt-dlp#readme')) + msvcrt.getch() + _exit(2) + parser.error( + 'You must provide at least one URL.\n' + 'Type yt-dlp --help to see a list of all options.') + + parser.destroy() + try: + if opts.load_info_filename is not None: + if all_urls: + ydl.report_warning('URLs are ignored due to --load-info-json') + return ydl.download_with_info_file(expand_path(opts.load_info_filename)) + else: + return ydl.download(all_urls) + except DownloadCancelled: + ydl.to_screen('Aborting remaining downloads') + return 101 + + +def main(argv=None): + IN_CLI.value = True + try: + _exit(*variadic(_real_main(argv))) + except (CookieLoadError, DownloadError): + _exit(1) + except SameFileError as e: + _exit(f'ERROR: {e}') + except KeyboardInterrupt: + _exit('\nERROR: Interrupted by user') + except BrokenPipeError as e: + # https://docs.python.org/3/library/signal.html#note-on-sigpipe + devnull = os.open(os.devnull, os.O_WRONLY) + os.dup2(devnull, sys.stdout.fileno()) + _exit(f'\nERROR: {e}') + except optparse.OptParseError as e: + _exit(2, f'\n{e}') + + +from .extractor import gen_extractors, list_extractors + +# Register JS runtimes and remote components +from .globals import supported_js_runtimes, supported_remote_components +supported_js_runtimes.value['deno'] = _DenoJsRuntime +supported_js_runtimes.value['node'] = _NodeJsRuntime +supported_js_runtimes.value['bun'] = _BunJsRuntime +supported_js_runtimes.value['quickjs'] = _QuickJsRuntime + +supported_remote_components.value.append('ejs:github') +supported_remote_components.value.append('ejs:npm') + +__all__ = [ + 'YoutubeDL', + 'gen_extractors', + 'list_extractors', + 'main', + 'parse_options', +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/__main__.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..06c392039bd3e5c35c43988793ba80f2174e1bf2 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/__main__.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 + +# Execute with +# $ python3 -m yt_dlp + +import sys + +if __package__ is None and not getattr(sys, 'frozen', False): + # direct call of __main__.py + import os.path + path = os.path.realpath(os.path.abspath(__file__)) + sys.path.insert(0, os.path.dirname(os.path.dirname(path))) + +import yt_dlp + +if __name__ == '__main__': + yt_dlp.main() diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/aes.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/aes.py new file mode 100644 index 0000000000000000000000000000000000000000..e5a2e67cff79359162483e2651e5735abde14f7b --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/aes.py @@ -0,0 +1,552 @@ +import base64 +from math import ceil + +from .compat import compat_ord +from .dependencies import Cryptodome + +if Cryptodome.AES: + def aes_cbc_decrypt_bytes(data, key, iv): + """ Decrypt bytes with AES-CBC using pycryptodome """ + return Cryptodome.AES.new(key, Cryptodome.AES.MODE_CBC, iv).decrypt(data) + + def aes_gcm_decrypt_and_verify_bytes(data, key, tag, nonce): + """ Decrypt bytes with AES-GCM using pycryptodome """ + return Cryptodome.AES.new(key, Cryptodome.AES.MODE_GCM, nonce).decrypt_and_verify(data, tag) + +else: + def aes_cbc_decrypt_bytes(data, key, iv): + """ Decrypt bytes with AES-CBC using native implementation since pycryptodome is unavailable """ + return bytes(aes_cbc_decrypt(*map(list, (data, key, iv)))) + + def aes_gcm_decrypt_and_verify_bytes(data, key, tag, nonce): + """ Decrypt bytes with AES-GCM using native implementation since pycryptodome is unavailable """ + return bytes(aes_gcm_decrypt_and_verify(*map(list, (data, key, tag, nonce)))) + + +def aes_cbc_encrypt_bytes(data, key, iv, **kwargs): + return bytes(aes_cbc_encrypt(*map(list, (data, key, iv)), **kwargs)) + + +BLOCK_SIZE_BYTES = 16 + + +def unpad_pkcs7(data): + return data[:-compat_ord(data[-1])] + + +def pkcs7_padding(data): + """ + PKCS#7 padding + + @param {int[]} data cleartext + @returns {int[]} padding data + """ + + remaining_length = BLOCK_SIZE_BYTES - len(data) % BLOCK_SIZE_BYTES + return data + [remaining_length] * remaining_length + + +def pad_block(block, padding_mode): + """ + Pad a block with the given padding mode + @param {int[]} block block to pad + @param padding_mode padding mode + """ + padding_size = BLOCK_SIZE_BYTES - len(block) + + PADDING_BYTE = { + 'pkcs7': padding_size, + 'iso7816': 0x0, + 'whitespace': 0x20, + 'zero': 0x0, + } + + if padding_size < 0: + raise ValueError('Block size exceeded') + elif padding_mode not in PADDING_BYTE: + raise NotImplementedError(f'Padding mode {padding_mode} is not implemented') + + if padding_mode == 'iso7816' and padding_size: + block = [*block, 0x80] # NB: += mutates list + padding_size -= 1 + + return block + [PADDING_BYTE[padding_mode]] * padding_size + + +def aes_ecb_encrypt(data, key, iv=None): + """ + Encrypt with aes in ECB mode. Using PKCS#7 padding + + @param {int[]} data cleartext + @param {int[]} key 16/24/32-Byte cipher key + @param {int[]} iv Unused for this mode + @returns {int[]} encrypted data + """ + expanded_key = key_expansion(key) + block_count = ceil(len(data) / BLOCK_SIZE_BYTES) + + encrypted_data = [] + for i in range(block_count): + block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES] + encrypted_data += aes_encrypt(pkcs7_padding(block), expanded_key) + + return encrypted_data + + +def aes_ecb_decrypt(data, key, iv=None): + """ + Decrypt with aes in ECB mode + + @param {int[]} data cleartext + @param {int[]} key 16/24/32-Byte cipher key + @param {int[]} iv Unused for this mode + @returns {int[]} decrypted data + """ + expanded_key = key_expansion(key) + block_count = ceil(len(data) / BLOCK_SIZE_BYTES) + + encrypted_data = [] + for i in range(block_count): + block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES] + encrypted_data += aes_decrypt(block, expanded_key) + return encrypted_data[:len(data)] + + +def aes_ctr_decrypt(data, key, iv): + """ + Decrypt with aes in counter mode + + @param {int[]} data cipher + @param {int[]} key 16/24/32-Byte cipher key + @param {int[]} iv 16-Byte initialization vector + @returns {int[]} decrypted data + """ + return aes_ctr_encrypt(data, key, iv) + + +def aes_ctr_encrypt(data, key, iv): + """ + Encrypt with aes in counter mode + + @param {int[]} data cleartext + @param {int[]} key 16/24/32-Byte cipher key + @param {int[]} iv 16-Byte initialization vector + @returns {int[]} encrypted data + """ + expanded_key = key_expansion(key) + block_count = ceil(len(data) / BLOCK_SIZE_BYTES) + counter = iter_vector(iv) + + encrypted_data = [] + for i in range(block_count): + counter_block = next(counter) + block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES] + block += [0] * (BLOCK_SIZE_BYTES - len(block)) + + cipher_counter_block = aes_encrypt(counter_block, expanded_key) + encrypted_data += xor(block, cipher_counter_block) + return encrypted_data[:len(data)] + + +def aes_cbc_decrypt(data, key, iv): + """ + Decrypt with aes in CBC mode + + @param {int[]} data cipher + @param {int[]} key 16/24/32-Byte cipher key + @param {int[]} iv 16-Byte IV + @returns {int[]} decrypted data + """ + expanded_key = key_expansion(key) + block_count = ceil(len(data) / BLOCK_SIZE_BYTES) + + decrypted_data = [] + previous_cipher_block = iv + for i in range(block_count): + block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES] + block += [0] * (BLOCK_SIZE_BYTES - len(block)) + + decrypted_block = aes_decrypt(block, expanded_key) + decrypted_data += xor(decrypted_block, previous_cipher_block) + previous_cipher_block = block + return decrypted_data[:len(data)] + + +def aes_cbc_encrypt(data, key, iv, *, padding_mode='pkcs7'): + """ + Encrypt with aes in CBC mode + + @param {int[]} data cleartext + @param {int[]} key 16/24/32-Byte cipher key + @param {int[]} iv 16-Byte IV + @param padding_mode Padding mode to use + @returns {int[]} encrypted data + """ + expanded_key = key_expansion(key) + block_count = ceil(len(data) / BLOCK_SIZE_BYTES) + + encrypted_data = [] + previous_cipher_block = iv + for i in range(block_count): + block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES] + block = pad_block(block, padding_mode) + + mixed_block = xor(block, previous_cipher_block) + + encrypted_block = aes_encrypt(mixed_block, expanded_key) + encrypted_data += encrypted_block + + previous_cipher_block = encrypted_block + + return encrypted_data + + +def aes_gcm_decrypt_and_verify(data, key, tag, nonce): + """ + Decrypt with aes in GBM mode and checks authenticity using tag + + @param {int[]} data cipher + @param {int[]} key 16-Byte cipher key + @param {int[]} tag authentication tag + @param {int[]} nonce IV (recommended 12-Byte) + @returns {int[]} decrypted data + """ + + # XXX: check aes, gcm param + + hash_subkey = aes_encrypt([0] * BLOCK_SIZE_BYTES, key_expansion(key)) + + if len(nonce) == 12: + j0 = [*nonce, 0, 0, 0, 1] + else: + fill = (BLOCK_SIZE_BYTES - (len(nonce) % BLOCK_SIZE_BYTES)) % BLOCK_SIZE_BYTES + 8 + ghash_in = nonce + [0] * fill + list((8 * len(nonce)).to_bytes(8, 'big')) + j0 = ghash(hash_subkey, ghash_in) + + # TODO: add nonce support to aes_ctr_decrypt + + # nonce_ctr = j0[:12] + iv_ctr = inc(j0) + + decrypted_data = aes_ctr_decrypt(data, key, iv_ctr + [0] * (BLOCK_SIZE_BYTES - len(iv_ctr))) + pad_len = (BLOCK_SIZE_BYTES - (len(data) % BLOCK_SIZE_BYTES)) % BLOCK_SIZE_BYTES + s_tag = ghash( + hash_subkey, + data + + [0] * pad_len # pad + + list((0 * 8).to_bytes(8, 'big') # length of associated data + + ((len(data) * 8).to_bytes(8, 'big'))), # length of data + ) + + if tag != aes_ctr_encrypt(s_tag, key, j0): + raise ValueError('Mismatching authentication tag') + + return decrypted_data + + +def aes_encrypt(data, expanded_key): + """ + Encrypt one block with aes + + @param {int[]} data 16-Byte state + @param {int[]} expanded_key 176/208/240-Byte expanded key + @returns {int[]} 16-Byte cipher + """ + rounds = len(expanded_key) // BLOCK_SIZE_BYTES - 1 + + data = xor(data, expanded_key[:BLOCK_SIZE_BYTES]) + for i in range(1, rounds + 1): + data = sub_bytes(data) + data = shift_rows(data) + if i != rounds: + data = list(iter_mix_columns(data, MIX_COLUMN_MATRIX)) + data = xor(data, expanded_key[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES]) + + return data + + +def aes_decrypt(data, expanded_key): + """ + Decrypt one block with aes + + @param {int[]} data 16-Byte cipher + @param {int[]} expanded_key 176/208/240-Byte expanded key + @returns {int[]} 16-Byte state + """ + rounds = len(expanded_key) // BLOCK_SIZE_BYTES - 1 + + for i in range(rounds, 0, -1): + data = xor(data, expanded_key[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES]) + if i != rounds: + data = list(iter_mix_columns(data, MIX_COLUMN_MATRIX_INV)) + data = shift_rows_inv(data) + data = sub_bytes_inv(data) + return xor(data, expanded_key[:BLOCK_SIZE_BYTES]) + + +def aes_decrypt_text(data, password, key_size_bytes): + """ + Decrypt text + - The first 8 Bytes of decoded 'data' are the 8 high Bytes of the counter + - The cipher key is retrieved by encrypting the first 16 Byte of 'password' + with the first 'key_size_bytes' Bytes from 'password' (if necessary filled with 0's) + - Mode of operation is 'counter' + + @param {str} data Base64 encoded string + @param {str,unicode} password Password (will be encoded with utf-8) + @param {int} key_size_bytes Possible values: 16 for 128-Bit, 24 for 192-Bit or 32 for 256-Bit + @returns {str} Decrypted data + """ + NONCE_LENGTH_BYTES = 8 + + data = list(base64.b64decode(data)) + password = list(password.encode()) + + key = password[:key_size_bytes] + [0] * (key_size_bytes - len(password)) + key = aes_encrypt(key[:BLOCK_SIZE_BYTES], key_expansion(key)) * (key_size_bytes // BLOCK_SIZE_BYTES) + + nonce = data[:NONCE_LENGTH_BYTES] + cipher = data[NONCE_LENGTH_BYTES:] + + decrypted_data = aes_ctr_decrypt(cipher, key, nonce + [0] * (BLOCK_SIZE_BYTES - NONCE_LENGTH_BYTES)) + return bytes(decrypted_data) + + +RCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36) +SBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, + 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, + 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, + 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, + 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, + 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, + 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, + 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, + 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, + 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, + 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, + 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, + 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, + 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, + 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, + 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16) +SBOX_INV = (0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, + 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, + 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, + 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, + 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, + 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, + 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, + 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, + 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, + 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, + 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, + 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, + 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, + 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, + 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, + 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d) +MIX_COLUMN_MATRIX = ((0x2, 0x3, 0x1, 0x1), + (0x1, 0x2, 0x3, 0x1), + (0x1, 0x1, 0x2, 0x3), + (0x3, 0x1, 0x1, 0x2)) +MIX_COLUMN_MATRIX_INV = ((0xE, 0xB, 0xD, 0x9), + (0x9, 0xE, 0xB, 0xD), + (0xD, 0x9, 0xE, 0xB), + (0xB, 0xD, 0x9, 0xE)) +RIJNDAEL_EXP_TABLE = (0x01, 0x03, 0x05, 0x0F, 0x11, 0x33, 0x55, 0xFF, 0x1A, 0x2E, 0x72, 0x96, 0xA1, 0xF8, 0x13, 0x35, + 0x5F, 0xE1, 0x38, 0x48, 0xD8, 0x73, 0x95, 0xA4, 0xF7, 0x02, 0x06, 0x0A, 0x1E, 0x22, 0x66, 0xAA, + 0xE5, 0x34, 0x5C, 0xE4, 0x37, 0x59, 0xEB, 0x26, 0x6A, 0xBE, 0xD9, 0x70, 0x90, 0xAB, 0xE6, 0x31, + 0x53, 0xF5, 0x04, 0x0C, 0x14, 0x3C, 0x44, 0xCC, 0x4F, 0xD1, 0x68, 0xB8, 0xD3, 0x6E, 0xB2, 0xCD, + 0x4C, 0xD4, 0x67, 0xA9, 0xE0, 0x3B, 0x4D, 0xD7, 0x62, 0xA6, 0xF1, 0x08, 0x18, 0x28, 0x78, 0x88, + 0x83, 0x9E, 0xB9, 0xD0, 0x6B, 0xBD, 0xDC, 0x7F, 0x81, 0x98, 0xB3, 0xCE, 0x49, 0xDB, 0x76, 0x9A, + 0xB5, 0xC4, 0x57, 0xF9, 0x10, 0x30, 0x50, 0xF0, 0x0B, 0x1D, 0x27, 0x69, 0xBB, 0xD6, 0x61, 0xA3, + 0xFE, 0x19, 0x2B, 0x7D, 0x87, 0x92, 0xAD, 0xEC, 0x2F, 0x71, 0x93, 0xAE, 0xE9, 0x20, 0x60, 0xA0, + 0xFB, 0x16, 0x3A, 0x4E, 0xD2, 0x6D, 0xB7, 0xC2, 0x5D, 0xE7, 0x32, 0x56, 0xFA, 0x15, 0x3F, 0x41, + 0xC3, 0x5E, 0xE2, 0x3D, 0x47, 0xC9, 0x40, 0xC0, 0x5B, 0xED, 0x2C, 0x74, 0x9C, 0xBF, 0xDA, 0x75, + 0x9F, 0xBA, 0xD5, 0x64, 0xAC, 0xEF, 0x2A, 0x7E, 0x82, 0x9D, 0xBC, 0xDF, 0x7A, 0x8E, 0x89, 0x80, + 0x9B, 0xB6, 0xC1, 0x58, 0xE8, 0x23, 0x65, 0xAF, 0xEA, 0x25, 0x6F, 0xB1, 0xC8, 0x43, 0xC5, 0x54, + 0xFC, 0x1F, 0x21, 0x63, 0xA5, 0xF4, 0x07, 0x09, 0x1B, 0x2D, 0x77, 0x99, 0xB0, 0xCB, 0x46, 0xCA, + 0x45, 0xCF, 0x4A, 0xDE, 0x79, 0x8B, 0x86, 0x91, 0xA8, 0xE3, 0x3E, 0x42, 0xC6, 0x51, 0xF3, 0x0E, + 0x12, 0x36, 0x5A, 0xEE, 0x29, 0x7B, 0x8D, 0x8C, 0x8F, 0x8A, 0x85, 0x94, 0xA7, 0xF2, 0x0D, 0x17, + 0x39, 0x4B, 0xDD, 0x7C, 0x84, 0x97, 0xA2, 0xFD, 0x1C, 0x24, 0x6C, 0xB4, 0xC7, 0x52, 0xF6, 0x01) +RIJNDAEL_LOG_TABLE = (0x00, 0x00, 0x19, 0x01, 0x32, 0x02, 0x1a, 0xc6, 0x4b, 0xc7, 0x1b, 0x68, 0x33, 0xee, 0xdf, 0x03, + 0x64, 0x04, 0xe0, 0x0e, 0x34, 0x8d, 0x81, 0xef, 0x4c, 0x71, 0x08, 0xc8, 0xf8, 0x69, 0x1c, 0xc1, + 0x7d, 0xc2, 0x1d, 0xb5, 0xf9, 0xb9, 0x27, 0x6a, 0x4d, 0xe4, 0xa6, 0x72, 0x9a, 0xc9, 0x09, 0x78, + 0x65, 0x2f, 0x8a, 0x05, 0x21, 0x0f, 0xe1, 0x24, 0x12, 0xf0, 0x82, 0x45, 0x35, 0x93, 0xda, 0x8e, + 0x96, 0x8f, 0xdb, 0xbd, 0x36, 0xd0, 0xce, 0x94, 0x13, 0x5c, 0xd2, 0xf1, 0x40, 0x46, 0x83, 0x38, + 0x66, 0xdd, 0xfd, 0x30, 0xbf, 0x06, 0x8b, 0x62, 0xb3, 0x25, 0xe2, 0x98, 0x22, 0x88, 0x91, 0x10, + 0x7e, 0x6e, 0x48, 0xc3, 0xa3, 0xb6, 0x1e, 0x42, 0x3a, 0x6b, 0x28, 0x54, 0xfa, 0x85, 0x3d, 0xba, + 0x2b, 0x79, 0x0a, 0x15, 0x9b, 0x9f, 0x5e, 0xca, 0x4e, 0xd4, 0xac, 0xe5, 0xf3, 0x73, 0xa7, 0x57, + 0xaf, 0x58, 0xa8, 0x50, 0xf4, 0xea, 0xd6, 0x74, 0x4f, 0xae, 0xe9, 0xd5, 0xe7, 0xe6, 0xad, 0xe8, + 0x2c, 0xd7, 0x75, 0x7a, 0xeb, 0x16, 0x0b, 0xf5, 0x59, 0xcb, 0x5f, 0xb0, 0x9c, 0xa9, 0x51, 0xa0, + 0x7f, 0x0c, 0xf6, 0x6f, 0x17, 0xc4, 0x49, 0xec, 0xd8, 0x43, 0x1f, 0x2d, 0xa4, 0x76, 0x7b, 0xb7, + 0xcc, 0xbb, 0x3e, 0x5a, 0xfb, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d, + 0x97, 0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1, + 0x53, 0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab, + 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5, + 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07) + + +def key_expansion(data): + """ + Generate key schedule + + @param {int[]} data 16/24/32-Byte cipher key + @returns {int[]} 176/208/240-Byte expanded key + """ + data = data[:] # copy + rcon_iteration = 1 + key_size_bytes = len(data) + expanded_key_size_bytes = (key_size_bytes // 4 + 7) * BLOCK_SIZE_BYTES + + while len(data) < expanded_key_size_bytes: + temp = data[-4:] + temp = key_schedule_core(temp, rcon_iteration) + rcon_iteration += 1 + data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes]) + + for _ in range(3): + temp = data[-4:] + data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes]) + + if key_size_bytes == 32: + temp = data[-4:] + temp = sub_bytes(temp) + data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes]) + + for _ in range(3 if key_size_bytes == 32 else 2 if key_size_bytes == 24 else 0): + temp = data[-4:] + data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes]) + return data[:expanded_key_size_bytes] + + +def iter_vector(iv): + while True: + yield iv + iv = inc(iv) + + +def sub_bytes(data): + return [SBOX[x] for x in data] + + +def sub_bytes_inv(data): + return [SBOX_INV[x] for x in data] + + +def rotate(data): + return [*data[1:], data[0]] + + +def key_schedule_core(data, rcon_iteration): + data = rotate(data) + data = sub_bytes(data) + data[0] = data[0] ^ RCON[rcon_iteration] + + return data + + +def xor(data1, data2): + return [x ^ y for x, y in zip(data1, data2, strict=False)] + + +def iter_mix_columns(data, matrix): + for i in (0, 4, 8, 12): + for row in matrix: + mixed = 0 + for j in range(4): + # xor is (+) and (-) + mixed ^= (0 if data[i:i + 4][j] == 0 or row[j] == 0 else + RIJNDAEL_EXP_TABLE[(RIJNDAEL_LOG_TABLE[data[i + j]] + RIJNDAEL_LOG_TABLE[row[j]]) % 0xFF]) + yield mixed + + +def shift_rows(data): + return [data[((column + row) & 0b11) * 4 + row] for column in range(4) for row in range(4)] + + +def shift_rows_inv(data): + return [data[((column - row) & 0b11) * 4 + row] for column in range(4) for row in range(4)] + + +def shift_block(data): + data_shifted = [] + + bit = 0 + for n in data: + if bit: + n |= 0x100 + bit = n & 1 + n >>= 1 + data_shifted.append(n) + + return data_shifted + + +def inc(data): + data = data[:] # copy + for i in range(len(data) - 1, -1, -1): + if data[i] == 255: + data[i] = 0 + else: + data[i] = data[i] + 1 + break + return data + + +def block_product(block_x, block_y): + # NIST SP 800-38D, Algorithm 1 + + if len(block_x) != BLOCK_SIZE_BYTES or len(block_y) != BLOCK_SIZE_BYTES: + raise ValueError(f'Length of blocks need to be {BLOCK_SIZE_BYTES} bytes') + + block_r = [0xE1] + [0] * (BLOCK_SIZE_BYTES - 1) + block_v = block_y[:] + block_z = [0] * BLOCK_SIZE_BYTES + + for i in block_x: + for bit in range(7, -1, -1): + if i & (1 << bit): + block_z = xor(block_z, block_v) + + do_xor = block_v[-1] & 1 + block_v = shift_block(block_v) + if do_xor: + block_v = xor(block_v, block_r) + + return block_z + + +def ghash(subkey, data): + # NIST SP 800-38D, Algorithm 2 + + if len(data) % BLOCK_SIZE_BYTES: + raise ValueError(f'Length of data should be {BLOCK_SIZE_BYTES} bytes') + + last_y = [0] * BLOCK_SIZE_BYTES + for i in range(0, len(data), BLOCK_SIZE_BYTES): + block = data[i: i + BLOCK_SIZE_BYTES] + last_y = block_product(xor(last_y, block), subkey) + + return last_y + + +__all__ = [ + 'aes_cbc_decrypt', + 'aes_cbc_decrypt_bytes', + 'aes_cbc_encrypt', + 'aes_cbc_encrypt_bytes', + 'aes_ctr_decrypt', + 'aes_ctr_encrypt', + 'aes_decrypt', + 'aes_decrypt_text', + 'aes_ecb_decrypt', + 'aes_ecb_encrypt', + 'aes_encrypt', + 'aes_gcm_decrypt_and_verify', + 'aes_gcm_decrypt_and_verify_bytes', + 'key_expansion', + 'pad_block', + 'pkcs7_padding', + 'unpad_pkcs7', +] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/cache.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..71dca82b3584f9aa5d9120070825b9726bd9f96f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/cache.py @@ -0,0 +1,91 @@ +import contextlib +import json +import os +import re +import shutil +import traceback +import urllib.parse + +from .utils import expand_path, traverse_obj, version_tuple, write_json_file +from .version import __version__ + + +class Cache: + def __init__(self, ydl): + self._ydl = ydl + + def _get_root_dir(self): + res = self._ydl.params.get('cachedir') + if res is None: + cache_root = os.getenv('XDG_CACHE_HOME', '~/.cache') + res = os.path.join(cache_root, 'yt-dlp') + return expand_path(res) + + def _get_cache_fn(self, section, key, dtype): + assert re.match(r'^[\w.-]+$', section), f'invalid section {section!r}' + key = urllib.parse.quote(key, safe='').replace('%', ',') # encode non-ascii characters + return os.path.join(self._get_root_dir(), section, f'{key}.{dtype}') + + @property + def enabled(self): + return self._ydl.params.get('cachedir') is not False + + def store(self, section, key, data, dtype='json'): + assert dtype in ('json',) + + if not self.enabled: + return + + fn = self._get_cache_fn(section, key, dtype) + try: + os.makedirs(os.path.dirname(fn), exist_ok=True) + self._ydl.write_debug(f'Saving {section}.{key} to cache') + write_json_file({'yt-dlp_version': __version__, 'data': data}, fn) + except Exception: + tb = traceback.format_exc() + self._ydl.report_warning(f'Writing cache to {fn!r} failed: {tb}') + + def _validate(self, data, min_ver): + version = traverse_obj(data, 'yt-dlp_version') + if not version: # Backward compatibility + data, version = {'data': data}, '2022.08.19' + if not min_ver or version_tuple(version) >= version_tuple(min_ver): + return data['data'] + self._ydl.write_debug(f'Discarding old cache from version {version} (needs {min_ver})') + + def load(self, section, key, dtype='json', default=None, *, min_ver=None): + assert dtype in ('json',) + + if not self.enabled: + return default + + cache_fn = self._get_cache_fn(section, key, dtype) + with contextlib.suppress(OSError): + try: + with open(cache_fn, encoding='utf-8') as cachef: + self._ydl.write_debug(f'Loading {section}.{key} from cache') + return self._validate(json.load(cachef), min_ver) + except (ValueError, KeyError): + try: + file_size = os.path.getsize(cache_fn) + except OSError as oe: + file_size = str(oe) + self._ydl.report_warning(f'Cache retrieval from {cache_fn} failed ({file_size})') + + return default + + def remove(self): + if not self.enabled: + self._ydl.to_screen('Cache is disabled (Did you combine --no-cache-dir and --rm-cache-dir?)') + return + + cachedir = self._get_root_dir() + if not any((term in cachedir) for term in ('cache', 'tmp')): + raise Exception(f'Not removing directory {cachedir} - this does not look like a cache dir') + + self._ydl.to_screen( + f'Removing cache dir {cachedir} .', skip_eol=True) + if os.path.exists(cachedir): + self._ydl.to_screen('.', skip_eol=True) + shutil.rmtree(cachedir) + self._ydl.to_screen('.') diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/cookies.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/cookies.py new file mode 100644 index 0000000000000000000000000000000000000000..831b3a2c8bdeb88c07a3e1e4f682b0cdc6ce8fa2 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/cookies.py @@ -0,0 +1,1420 @@ +import base64 +import collections +import contextlib +import datetime as dt +import functools +import glob +import hashlib +import http.cookiejar +import http.cookies +import io +import json +import os +import re +import shutil +import struct +import subprocess +import sys +import tempfile +import time +import urllib.request +from enum import Enum, auto + +from .aes import ( + aes_cbc_decrypt_bytes, + aes_gcm_decrypt_and_verify_bytes, + unpad_pkcs7, +) +from .dependencies import ( + _SECRETSTORAGE_UNAVAILABLE_REASON, + secretstorage, + sqlite3, +) +from .minicurses import MultilinePrinter, QuietMultilinePrinter +from .utils import ( + DownloadError, + YoutubeDLError, + Popen, + error_to_str, + expand_path, + is_path_like, + sanitize_url, + str_or_none, + try_call, + write_string, +) +from .utils._utils import _YDLLogger +from .utils.networking import normalize_url + +CHROMIUM_BASED_BROWSERS = {'brave', 'chrome', 'chromium', 'edge', 'opera', 'vivaldi', 'whale'} +SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'} + + +class YDLLogger(_YDLLogger): + def warning(self, message, only_once=False): # compat + return super().warning(message, once=only_once) + + class ProgressBar(MultilinePrinter): + _DELAY, _timer = 0.1, 0 + + def print(self, message): + if time.time() - self._timer > self._DELAY: + self.print_at_line(f'[Cookies] {message}', 0) + self._timer = time.time() + + def progress_bar(self): + """Return a context manager with a print method. (Optional)""" + # Do not print to files/pipes, loggers, or when --no-progress is used + if not self._ydl or self._ydl.params.get('noprogress') or self._ydl.params.get('logger'): + return + file = self._ydl._out_files.error + try: + if not file.isatty(): + return + except BaseException: + return + return self.ProgressBar(file, preserve_output=False) + + +def _create_progress_bar(logger): + if hasattr(logger, 'progress_bar'): + printer = logger.progress_bar() + if printer: + return printer + printer = QuietMultilinePrinter() + printer.print = lambda _: None + return printer + + +class CookieLoadError(YoutubeDLError): + pass + + +def load_cookies(cookie_file, browser_specification, ydl): + try: + cookie_jars = [] + if browser_specification is not None: + browser_name, profile, keyring, container = _parse_browser_specification(*browser_specification) + cookie_jars.append( + extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl), keyring=keyring, container=container)) + + if cookie_file is not None: + is_filename = is_path_like(cookie_file) + if is_filename: + cookie_file = expand_path(cookie_file) + + jar = YoutubeDLCookieJar(cookie_file) + if not is_filename or os.access(cookie_file, os.R_OK): + jar.load() + cookie_jars.append(jar) + + return _merge_cookie_jars(cookie_jars) + except Exception: + raise CookieLoadError('failed to load cookies') + + +def extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(), *, keyring=None, container=None): + if browser_name == 'firefox': + return _extract_firefox_cookies(profile, container, logger) + elif browser_name == 'safari': + return _extract_safari_cookies(profile, logger) + elif browser_name in CHROMIUM_BASED_BROWSERS: + return _extract_chrome_cookies(browser_name, profile, keyring, logger) + else: + raise ValueError(f'unknown browser: {browser_name}') + + +def _extract_firefox_cookies(profile, container, logger): + MAX_SUPPORTED_DB_SCHEMA_VERSION = 17 + + logger.info('Extracting cookies from firefox') + if not sqlite3: + logger.warning('Cannot extract cookies from firefox without sqlite3 support. ' + 'Please use a Python interpreter compiled with sqlite3 support') + return YoutubeDLCookieJar() + + if profile is None: + search_roots = list(_firefox_browser_dirs()) + elif _is_path(profile): + search_roots = [profile] + else: + search_roots = [os.path.join(path, profile) for path in _firefox_browser_dirs()] + search_root = ', '.join(map(repr, search_roots)) + + cookie_database_path = _newest(_firefox_cookie_dbs(search_roots)) + if cookie_database_path is None: + raise FileNotFoundError(f'could not find firefox cookies database in {search_root}') + logger.debug(f'Extracting cookies from: "{cookie_database_path}"') + + container_id = None + if container not in (None, 'none'): + containers_path = os.path.join(os.path.dirname(cookie_database_path), 'containers.json') + if not os.path.isfile(containers_path) or not os.access(containers_path, os.R_OK): + raise FileNotFoundError(f'could not read containers.json in {search_root}') + with open(containers_path, encoding='utf8') as containers: + identities = json.load(containers).get('identities', []) + container_id = next((context.get('userContextId') for context in identities if container in ( + context.get('name'), + try_call(lambda: re.fullmatch(r'userContext([^\.]+)\.label', context['l10nID']).group()), + )), None) + if not isinstance(container_id, int): + raise ValueError(f'could not find firefox container "{container}" in containers.json') + + with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: + cursor = _open_database_copy(cookie_database_path, tmpdir) + with contextlib.closing(cursor.connection): + db_schema_version = cursor.execute('PRAGMA user_version;').fetchone()[0] + if db_schema_version > MAX_SUPPORTED_DB_SCHEMA_VERSION: + logger.warning(f'Possibly unsupported firefox cookies database version: {db_schema_version}') + else: + logger.debug(f'Firefox cookies database version: {db_schema_version}') + if isinstance(container_id, int): + logger.debug( + f'Only loading cookies from firefox container "{container}", ID {container_id}') + cursor.execute( + 'SELECT host, name, value, path, expiry, isSecure FROM moz_cookies WHERE originAttributes LIKE ? OR originAttributes LIKE ?', + (f'%userContextId={container_id}', f'%userContextId={container_id}&%')) + elif container == 'none': + logger.debug('Only loading cookies not belonging to any container') + cursor.execute( + 'SELECT host, name, value, path, expiry, isSecure FROM moz_cookies WHERE NOT INSTR(originAttributes,"userContextId=")') + else: + cursor.execute('SELECT host, name, value, path, expiry, isSecure FROM moz_cookies') + jar = YoutubeDLCookieJar() + with _create_progress_bar(logger) as progress_bar: + table = cursor.fetchall() + total_cookie_count = len(table) + for i, (host, name, value, path, expiry, is_secure) in enumerate(table): + progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') + # FF142 upgraded cookies DB to schema version 16 and started using milliseconds for cookie expiry + # Ref: https://github.com/mozilla-firefox/firefox/commit/5869af852cd20425165837f6c2d9971f3efba83d + if db_schema_version >= 16 and expiry is not None: + expiry /= 1000 + cookie = http.cookiejar.Cookie( + version=0, name=name, value=value, port=None, port_specified=False, + domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'), + path=path, path_specified=bool(path), secure=is_secure, expires=expiry, discard=False, + comment=None, comment_url=None, rest={}) + jar.set_cookie(cookie) + logger.info(f'Extracted {len(jar)} cookies from firefox') + return jar + + +def _firefox_browser_dirs(): + if sys.platform in ('cygwin', 'win32'): + yield from map(os.path.expandvars, ( + R'%APPDATA%\Mozilla\Firefox\Profiles', + R'%LOCALAPPDATA%\Packages\Mozilla.Firefox_n80bbvh6b1yt2\LocalCache\Roaming\Mozilla\Firefox\Profiles', + )) + + elif sys.platform == 'darwin': + yield os.path.expanduser('~/Library/Application Support/Firefox/Profiles') + + else: + yield from map(os.path.expanduser, ( + # New installations of FF147+ respect the XDG base directory specification + # Ref: https://bugzilla.mozilla.org/show_bug.cgi?id=259356 + os.path.join(_config_home(), 'mozilla/firefox'), + # Existing FF version<=146 installations + '~/.mozilla/firefox', + # Flatpak XDG: https://docs.flatpak.org/en/latest/conventions.html#xdg-base-directories + '~/.var/app/org.mozilla.firefox/config/mozilla/firefox', + '~/.var/app/org.mozilla.firefox/.mozilla/firefox', + # Snap installations do not respect the XDG base directory specification + '~/snap/firefox/common/.mozilla/firefox', + )) + + +def _firefox_cookie_dbs(roots): + for root in map(os.path.abspath, roots): + for pattern in ('', '*/', 'Profiles/*/'): + yield from glob.iglob(os.path.join(root, pattern, 'cookies.sqlite')) + + +def _get_chromium_based_browser_settings(browser_name): + # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md + if sys.platform in ('cygwin', 'win32'): + appdata_local = os.path.expandvars('%LOCALAPPDATA%') + appdata_roaming = os.path.expandvars('%APPDATA%') + browser_dir = { + 'brave': os.path.join(appdata_local, R'BraveSoftware\Brave-Browser\User Data'), + 'chrome': os.path.join(appdata_local, R'Google\Chrome\User Data'), + 'chromium': os.path.join(appdata_local, R'Chromium\User Data'), + 'edge': os.path.join(appdata_local, R'Microsoft\Edge\User Data'), + 'opera': os.path.join(appdata_roaming, R'Opera Software\Opera Stable'), + 'vivaldi': os.path.join(appdata_local, R'Vivaldi\User Data'), + 'whale': os.path.join(appdata_local, R'Naver\Naver Whale\User Data'), + }[browser_name] + + elif sys.platform == 'darwin': + appdata = os.path.expanduser('~/Library/Application Support') + browser_dir = { + 'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'), + 'chrome': os.path.join(appdata, 'Google/Chrome'), + 'chromium': os.path.join(appdata, 'Chromium'), + 'edge': os.path.join(appdata, 'Microsoft Edge'), + 'opera': os.path.join(appdata, 'com.operasoftware.Opera'), + 'vivaldi': os.path.join(appdata, 'Vivaldi'), + 'whale': os.path.join(appdata, 'Naver/Whale'), + }[browser_name] + + else: + config = _config_home() + browser_dir = { + 'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'), + 'chrome': os.path.join(config, 'google-chrome'), + 'chromium': os.path.join(config, 'chromium'), + 'edge': os.path.join(config, 'microsoft-edge'), + 'opera': os.path.join(config, 'opera'), + 'vivaldi': os.path.join(config, 'vivaldi'), + 'whale': os.path.join(config, 'naver-whale'), + }[browser_name] + + # Linux keyring names can be determined by snooping on dbus while opening the browser in KDE: + # dbus-monitor "interface='org.kde.KWallet'" "type=method_return" + keyring_name = { + 'brave': 'Brave', + 'chrome': 'Chrome', + 'chromium': 'Chromium', + 'edge': 'Microsoft Edge' if sys.platform == 'darwin' else 'Chromium', + 'opera': 'Opera' if sys.platform == 'darwin' else 'Chromium', + 'vivaldi': 'Vivaldi' if sys.platform == 'darwin' else 'Chrome', + 'whale': 'Whale', + }[browser_name] + + browsers_without_profiles = {'opera'} + + return { + 'browser_dir': browser_dir, + 'keyring_name': keyring_name, + 'supports_profiles': browser_name not in browsers_without_profiles, + } + + +def _extract_chrome_cookies(browser_name, profile, keyring, logger): + logger.info(f'Extracting cookies from {browser_name}') + + if not sqlite3: + logger.warning(f'Cannot extract cookies from {browser_name} without sqlite3 support. ' + 'Please use a Python interpreter compiled with sqlite3 support') + return YoutubeDLCookieJar() + + config = _get_chromium_based_browser_settings(browser_name) + + if profile is None: + search_root = config['browser_dir'] + elif _is_path(profile): + search_root = profile + config['browser_dir'] = os.path.dirname(profile) if config['supports_profiles'] else profile + else: + if config['supports_profiles']: + search_root = os.path.join(config['browser_dir'], profile) + else: + logger.error(f'{browser_name} does not support profiles') + search_root = config['browser_dir'] + + cookie_database_path = _newest(_find_files(search_root, 'Cookies', logger)) + if cookie_database_path is None: + raise FileNotFoundError(f'could not find {browser_name} cookies database in "{search_root}"') + logger.debug(f'Extracting cookies from: "{cookie_database_path}"') + + with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: + cursor = None + try: + cursor = _open_database_copy(cookie_database_path, tmpdir) + + # meta_version is necessary to determine if we need to trim the hash prefix from the cookies + # Ref: https://chromium.googlesource.com/chromium/src/+/b02dcebd7cafab92770734dc2bc317bd07f1d891/net/extras/sqlite/sqlite_persistent_cookie_store.cc#223 + meta_version = int(cursor.execute('SELECT value FROM meta WHERE key = "version"').fetchone()[0]) + decryptor = get_cookie_decryptor( + config['browser_dir'], config['keyring_name'], logger, + keyring=keyring, meta_version=meta_version) + + cursor.connection.text_factory = bytes + column_names = _get_column_names(cursor, 'cookies') + secure_column = 'is_secure' if 'is_secure' in column_names else 'secure' + cursor.execute(f'SELECT host_key, name, value, encrypted_value, path, expires_utc, {secure_column} FROM cookies') + jar = YoutubeDLCookieJar() + failed_cookies = 0 + unencrypted_cookies = 0 + with _create_progress_bar(logger) as progress_bar: + table = cursor.fetchall() + total_cookie_count = len(table) + for i, line in enumerate(table): + progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') + is_encrypted, cookie = _process_chrome_cookie(decryptor, *line) + if not cookie: + failed_cookies += 1 + continue + elif not is_encrypted: + unencrypted_cookies += 1 + jar.set_cookie(cookie) + if failed_cookies > 0: + failed_message = f' ({failed_cookies} could not be decrypted)' + else: + failed_message = '' + logger.info(f'Extracted {len(jar)} cookies from {browser_name}{failed_message}') + counts = decryptor._cookie_counts.copy() + counts['unencrypted'] = unencrypted_cookies + logger.debug(f'cookie version breakdown: {counts}') + return jar + except PermissionError as error: + if os.name == 'nt' and error.errno == 13: + message = 'Could not copy Chrome cookie database. See https://github.com/yt-dlp/yt-dlp/issues/7271 for more info' + logger.error(message) + raise DownloadError(message) # force exit + raise + finally: + if cursor is not None: + cursor.connection.close() + + +def _process_chrome_cookie(decryptor, host_key, name, value, encrypted_value, path, expires_utc, is_secure): + host_key = host_key.decode() + name = name.decode() + value = value.decode() + path = path.decode() + is_encrypted = not value and encrypted_value + + if is_encrypted: + value = decryptor.decrypt(encrypted_value) + if value is None: + return is_encrypted, None + + # In chrome, session cookies have expires_utc set to 0 + # In our cookie-store, cookies that do not expire should have expires set to None + if not expires_utc: + expires_utc = None + + return is_encrypted, http.cookiejar.Cookie( + version=0, name=name, value=value, port=None, port_specified=False, + domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'), + path=path, path_specified=bool(path), secure=is_secure, expires=expires_utc, discard=False, + comment=None, comment_url=None, rest={}) + + +class ChromeCookieDecryptor: + """ + Overview: + + Linux: + - cookies are either v10 or v11 + - v10: AES-CBC encrypted with a fixed key + - also attempts empty password if decryption fails + - v11: AES-CBC encrypted with an OS protected key (keyring) + - also attempts empty password if decryption fails + - v11 keys can be stored in various places depending on the activate desktop environment [2] + + Mac: + - cookies are either v10 or not v10 + - v10: AES-CBC encrypted with an OS protected key (keyring) and more key derivation iterations than linux + - not v10: 'old data' stored as plaintext + + Windows: + - cookies are either v10 or not v10 + - v10: AES-GCM encrypted with a key which is encrypted with DPAPI + - not v10: encrypted with DPAPI + + Sources: + - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ + - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/key_storage_linux.cc + - KeyStorageLinux::CreateService + """ + + _cookie_counts = {} + + def decrypt(self, encrypted_value): + raise NotImplementedError('Must be implemented by sub classes') + + +def get_cookie_decryptor(browser_root, browser_keyring_name, logger, *, keyring=None, meta_version=None): + if sys.platform == 'darwin': + return MacChromeCookieDecryptor(browser_keyring_name, logger, meta_version=meta_version) + elif sys.platform in ('win32', 'cygwin'): + return WindowsChromeCookieDecryptor(browser_root, logger, meta_version=meta_version) + return LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring, meta_version=meta_version) + + +class LinuxChromeCookieDecryptor(ChromeCookieDecryptor): + def __init__(self, browser_keyring_name, logger, *, keyring=None, meta_version=None): + self._logger = logger + self._v10_key = self.derive_key(b'peanuts') + self._empty_key = self.derive_key(b'') + self._cookie_counts = {'v10': 0, 'v11': 0, 'other': 0} + self._browser_keyring_name = browser_keyring_name + self._keyring = keyring + self._meta_version = meta_version or 0 + + @functools.cached_property + def _v11_key(self): + password = _get_linux_keyring_password(self._browser_keyring_name, self._keyring, self._logger) + return None if password is None else self.derive_key(password) + + @staticmethod + def derive_key(password): + # values from + # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_linux.cc + return pbkdf2_sha1(password, salt=b'saltysalt', iterations=1, key_length=16) + + def decrypt(self, encrypted_value): + """ + + following the same approach as the fix in [1]: if cookies fail to decrypt then attempt to decrypt + with an empty password. The failure detection is not the same as what chromium uses so the + results won't be perfect + + References: + - [1] https://chromium.googlesource.com/chromium/src/+/bbd54702284caca1f92d656fdcadf2ccca6f4165%5E%21/ + - a bugfix to try an empty password as a fallback + """ + version = encrypted_value[:3] + ciphertext = encrypted_value[3:] + + if version == b'v10': + self._cookie_counts['v10'] += 1 + return _decrypt_aes_cbc_multi( + ciphertext, (self._v10_key, self._empty_key), self._logger, + hash_prefix=self._meta_version >= 24) + + elif version == b'v11': + self._cookie_counts['v11'] += 1 + if self._v11_key is None: + self._logger.warning('cannot decrypt v11 cookies: no key found', only_once=True) + return None + return _decrypt_aes_cbc_multi( + ciphertext, (self._v11_key, self._empty_key), self._logger, + hash_prefix=self._meta_version >= 24) + + else: + self._logger.warning(f'unknown cookie version: "{version}"', only_once=True) + self._cookie_counts['other'] += 1 + return None + + +class MacChromeCookieDecryptor(ChromeCookieDecryptor): + def __init__(self, browser_keyring_name, logger, meta_version=None): + self._logger = logger + password = _get_mac_keyring_password(browser_keyring_name, logger) + self._v10_key = None if password is None else self.derive_key(password) + self._cookie_counts = {'v10': 0, 'other': 0} + self._meta_version = meta_version or 0 + + @staticmethod + def derive_key(password): + # values from + # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_mac.mm + return pbkdf2_sha1(password, salt=b'saltysalt', iterations=1003, key_length=16) + + def decrypt(self, encrypted_value): + version = encrypted_value[:3] + ciphertext = encrypted_value[3:] + + if version == b'v10': + self._cookie_counts['v10'] += 1 + if self._v10_key is None: + self._logger.warning('cannot decrypt v10 cookies: no key found', only_once=True) + return None + + return _decrypt_aes_cbc_multi( + ciphertext, (self._v10_key,), self._logger, hash_prefix=self._meta_version >= 24) + + else: + self._cookie_counts['other'] += 1 + # other prefixes are considered 'old data' which were stored as plaintext + # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_mac.mm + return encrypted_value + + +class WindowsChromeCookieDecryptor(ChromeCookieDecryptor): + def __init__(self, browser_root, logger, meta_version=None): + self._logger = logger + self._v10_key = _get_windows_v10_key(browser_root, logger) + self._cookie_counts = {'v10': 0, 'other': 0} + self._meta_version = meta_version or 0 + + def decrypt(self, encrypted_value): + version = encrypted_value[:3] + ciphertext = encrypted_value[3:] + + if version == b'v10': + self._cookie_counts['v10'] += 1 + if self._v10_key is None: + self._logger.warning('cannot decrypt v10 cookies: no key found', only_once=True) + return None + + # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_win.cc + # kNonceLength + nonce_length = 96 // 8 + # boringssl + # EVP_AEAD_AES_GCM_TAG_LEN + authentication_tag_length = 16 + + raw_ciphertext = ciphertext + nonce = raw_ciphertext[:nonce_length] + ciphertext = raw_ciphertext[nonce_length:-authentication_tag_length] + authentication_tag = raw_ciphertext[-authentication_tag_length:] + + return _decrypt_aes_gcm( + ciphertext, self._v10_key, nonce, authentication_tag, self._logger, + hash_prefix=self._meta_version >= 24) + + else: + self._cookie_counts['other'] += 1 + # any other prefix means the data is DPAPI encrypted + # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_win.cc + return _decrypt_windows_dpapi(encrypted_value, self._logger).decode() + + +def _extract_safari_cookies(profile, logger): + if sys.platform not in ('darwin', 'ios'): + raise ValueError(f'unsupported platform: {sys.platform}') + + if profile: + cookies_path = os.path.expanduser(profile) + if not os.path.isfile(cookies_path): + raise FileNotFoundError('custom safari cookies database not found') + + else: + cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') + + if not os.path.isfile(cookies_path): + logger.debug('Trying secondary cookie location') + cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') + if not os.path.isfile(cookies_path): + raise FileNotFoundError('could not find safari cookies database') + + with open(cookies_path, 'rb') as f: + cookies_data = f.read() + + jar = parse_safari_cookies(cookies_data, logger=logger) + logger.info(f'Extracted {len(jar)} cookies from safari') + return jar + + +class ParserError(Exception): + pass + + +class DataParser: + def __init__(self, data, logger): + self._data = data + self.cursor = 0 + self._logger = logger + + def read_bytes(self, num_bytes): + if num_bytes < 0: + raise ParserError(f'invalid read of {num_bytes} bytes') + end = self.cursor + num_bytes + if end > len(self._data): + raise ParserError('reached end of input') + data = self._data[self.cursor:end] + self.cursor = end + return data + + def expect_bytes(self, expected_value, message): + value = self.read_bytes(len(expected_value)) + if value != expected_value: + raise ParserError(f'unexpected value: {value} != {expected_value} ({message})') + + def read_uint(self, big_endian=False): + data_format = '>I' if big_endian else ' 0: + self._logger.debug(f'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}') + elif num_bytes < 0: + raise ParserError(f'invalid skip of {num_bytes} bytes') + + def skip_to(self, offset, description='unknown'): + self.skip(offset - self.cursor, description) + + def skip_to_end(self, description='unknown'): + self.skip_to(len(self._data), description) + + +def _mac_absolute_time_to_posix(timestamp): + return int((dt.datetime(2001, 1, 1, 0, 0, tzinfo=dt.timezone.utc) + dt.timedelta(seconds=timestamp)).timestamp()) + + +def _parse_safari_cookies_header(data, logger): + p = DataParser(data, logger) + p.expect_bytes(b'cook', 'database signature') + number_of_pages = p.read_uint(big_endian=True) + page_sizes = [p.read_uint(big_endian=True) for _ in range(number_of_pages)] + return page_sizes, p.cursor + + +def _parse_safari_cookies_page(data, jar, logger): + p = DataParser(data, logger) + p.expect_bytes(b'\x00\x00\x01\x00', 'page signature') + number_of_cookies = p.read_uint() + record_offsets = [p.read_uint() for _ in range(number_of_cookies)] + if number_of_cookies == 0: + logger.debug(f'a cookies page of size {len(data)} has no cookies') + return + + p.skip_to(record_offsets[0], 'unknown page header field') + + with _create_progress_bar(logger) as progress_bar: + for i, record_offset in enumerate(record_offsets): + progress_bar.print(f'Loading cookie {i: 6d}/{number_of_cookies: 6d}') + p.skip_to(record_offset, 'space between records') + record_length = _parse_safari_cookies_record(data[record_offset:], jar, logger) + p.read_bytes(record_length) + p.skip_to_end('space in between pages') + + +def _parse_safari_cookies_record(data, jar, logger): + p = DataParser(data, logger) + record_size = p.read_uint() + p.skip(4, 'unknown record field 1') + flags = p.read_uint() + is_secure = bool(flags & 0x0001) + p.skip(4, 'unknown record field 2') + domain_offset = p.read_uint() + name_offset = p.read_uint() + path_offset = p.read_uint() + value_offset = p.read_uint() + p.skip(8, 'unknown record field 3') + expiration_date = _mac_absolute_time_to_posix(p.read_double()) + _creation_date = _mac_absolute_time_to_posix(p.read_double()) # noqa: F841 + + try: + p.skip_to(domain_offset) + domain = p.read_cstring() + + p.skip_to(name_offset) + name = p.read_cstring() + + p.skip_to(path_offset) + path = p.read_cstring() + + p.skip_to(value_offset) + value = p.read_cstring() + except UnicodeDecodeError: + logger.warning('failed to parse Safari cookie because UTF-8 decoding failed', only_once=True) + return record_size + + p.skip_to(record_size, 'space at the end of the record') + + cookie = http.cookiejar.Cookie( + version=0, name=name, value=value, port=None, port_specified=False, + domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'), + path=path, path_specified=bool(path), secure=is_secure, expires=expiration_date, discard=False, + comment=None, comment_url=None, rest={}) + jar.set_cookie(cookie) + return record_size + + +def parse_safari_cookies(data, jar=None, logger=YDLLogger()): + """ + References: + - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc + - this data appears to be out of date but the important parts of the database structure is the same + - there are a few bytes here and there which are skipped during parsing + """ + if jar is None: + jar = YoutubeDLCookieJar() + page_sizes, body_start = _parse_safari_cookies_header(data, logger) + p = DataParser(data[body_start:], logger) + for page_size in page_sizes: + _parse_safari_cookies_page(p.read_bytes(page_size), jar, logger) + p.skip_to_end('footer') + return jar + + +class _LinuxDesktopEnvironment(Enum): + """ + https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h + DesktopEnvironment + """ + OTHER = auto() + CINNAMON = auto() + DEEPIN = auto() + GNOME = auto() + KDE3 = auto() + KDE4 = auto() + KDE5 = auto() + KDE6 = auto() + PANTHEON = auto() + UKUI = auto() + UNITY = auto() + XFCE = auto() + LXQT = auto() + + +class _LinuxKeyring(Enum): + """ + https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/key_storage_util_linux.h + SelectedLinuxBackend + """ + KWALLET = auto() # KDE4 + KWALLET5 = auto() + KWALLET6 = auto() + GNOMEKEYRING = auto() + BASICTEXT = auto() + + +SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys() + + +def _get_linux_desktop_environment(env, logger): + """ + https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc + GetDesktopEnvironment + """ + xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP', None) + desktop_session = env.get('DESKTOP_SESSION', '') + if xdg_current_desktop is not None: + for part in map(str.strip, xdg_current_desktop.split(':')): + if part == 'Unity': + if 'gnome-fallback' in desktop_session: + return _LinuxDesktopEnvironment.GNOME + else: + return _LinuxDesktopEnvironment.UNITY + elif part == 'Deepin': + return _LinuxDesktopEnvironment.DEEPIN + elif part == 'GNOME': + return _LinuxDesktopEnvironment.GNOME + elif part == 'X-Cinnamon': + return _LinuxDesktopEnvironment.CINNAMON + elif part == 'KDE': + kde_version = env.get('KDE_SESSION_VERSION', None) + if kde_version == '5': + return _LinuxDesktopEnvironment.KDE5 + elif kde_version == '6': + return _LinuxDesktopEnvironment.KDE6 + elif kde_version == '4': + return _LinuxDesktopEnvironment.KDE4 + else: + logger.info(f'unknown KDE version: "{kde_version}". Assuming KDE4') + return _LinuxDesktopEnvironment.KDE4 + elif part == 'Pantheon': + return _LinuxDesktopEnvironment.PANTHEON + elif part == 'XFCE': + return _LinuxDesktopEnvironment.XFCE + elif part == 'UKUI': + return _LinuxDesktopEnvironment.UKUI + elif part == 'LXQt': + return _LinuxDesktopEnvironment.LXQT + logger.debug(f'XDG_CURRENT_DESKTOP is set to an unknown value: "{xdg_current_desktop}"') + + if desktop_session == 'deepin': + return _LinuxDesktopEnvironment.DEEPIN + elif desktop_session in ('mate', 'gnome'): + return _LinuxDesktopEnvironment.GNOME + elif desktop_session in ('kde4', 'kde-plasma'): + return _LinuxDesktopEnvironment.KDE4 + elif desktop_session == 'kde': + if 'KDE_SESSION_VERSION' in env: + return _LinuxDesktopEnvironment.KDE4 + else: + return _LinuxDesktopEnvironment.KDE3 + elif 'xfce' in desktop_session or desktop_session == 'xubuntu': + return _LinuxDesktopEnvironment.XFCE + elif desktop_session == 'ukui': + return _LinuxDesktopEnvironment.UKUI + else: + logger.debug(f'DESKTOP_SESSION is set to an unknown value: "{desktop_session}"') + + if 'GNOME_DESKTOP_SESSION_ID' in env: + return _LinuxDesktopEnvironment.GNOME + elif 'KDE_FULL_SESSION' in env: + if 'KDE_SESSION_VERSION' in env: + return _LinuxDesktopEnvironment.KDE4 + else: + return _LinuxDesktopEnvironment.KDE3 + + return _LinuxDesktopEnvironment.OTHER + + +def _choose_linux_keyring(logger): + """ + SelectBackend in [1] + + There is currently support for forcing chromium to use BASIC_TEXT by creating a file called + `Disable Local Encryption` [1] in the user data dir. The function to write this file (`WriteBackendUse()` [1]) + does not appear to be called anywhere other than in tests, so the user would have to create this file manually + and so would be aware enough to tell yt-dlp to use the BASIC_TEXT keyring. + + References: + - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/key_storage_util_linux.cc + """ + desktop_environment = _get_linux_desktop_environment(os.environ, logger) + logger.debug(f'detected desktop environment: {desktop_environment.name}') + if desktop_environment == _LinuxDesktopEnvironment.KDE4: + linux_keyring = _LinuxKeyring.KWALLET + elif desktop_environment == _LinuxDesktopEnvironment.KDE5: + linux_keyring = _LinuxKeyring.KWALLET5 + elif desktop_environment == _LinuxDesktopEnvironment.KDE6: + linux_keyring = _LinuxKeyring.KWALLET6 + elif desktop_environment in ( + _LinuxDesktopEnvironment.KDE3, _LinuxDesktopEnvironment.LXQT, _LinuxDesktopEnvironment.OTHER, + ): + linux_keyring = _LinuxKeyring.BASICTEXT + else: + linux_keyring = _LinuxKeyring.GNOMEKEYRING + return linux_keyring + + +def _get_kwallet_network_wallet(keyring, logger): + """ The name of the wallet used to store network passwords. + + https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/kwallet_dbus.cc + KWalletDBus::NetworkWallet + which does a dbus call to the following function: + https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html + Wallet::NetworkWallet + """ + default_wallet = 'kdewallet' + try: + if keyring == _LinuxKeyring.KWALLET: + service_name = 'org.kde.kwalletd' + wallet_path = '/modules/kwalletd' + elif keyring == _LinuxKeyring.KWALLET5: + service_name = 'org.kde.kwalletd5' + wallet_path = '/modules/kwalletd5' + elif keyring == _LinuxKeyring.KWALLET6: + service_name = 'org.kde.kwalletd6' + wallet_path = '/modules/kwalletd6' + else: + raise ValueError(keyring) + + stdout, _, returncode = Popen.run([ + 'dbus-send', '--session', '--print-reply=literal', + f'--dest={service_name}', + wallet_path, + 'org.kde.KWallet.networkWallet', + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + if returncode: + logger.warning('failed to read NetworkWallet') + return default_wallet + else: + logger.debug(f'NetworkWallet = "{stdout.strip()}"') + return stdout.strip() + except Exception as e: + logger.warning(f'exception while obtaining NetworkWallet: {e}') + return default_wallet + + +def _get_kwallet_password(browser_keyring_name, keyring, logger): + logger.debug(f'using kwallet-query to obtain password from {keyring.name}') + + if shutil.which('kwallet-query') is None: + logger.error('kwallet-query command not found. KWallet and kwallet-query ' + 'must be installed to read from KWallet. kwallet-query should be' + 'included in the kwallet package for your distribution') + return b'' + + network_wallet = _get_kwallet_network_wallet(keyring, logger) + + try: + stdout, _, returncode = Popen.run([ + 'kwallet-query', + '--read-password', f'{browser_keyring_name} Safe Storage', + '--folder', f'{browser_keyring_name} Keys', + network_wallet, + ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + if returncode: + logger.error(f'kwallet-query failed with return code {returncode}. ' + 'Please consult the kwallet-query man page for details') + return b'' + else: + if stdout.lower().startswith(b'failed to read'): + logger.debug('failed to read password from kwallet. Using empty string instead') + # this sometimes occurs in KDE because chrome does not check hasEntry and instead + # just tries to read the value (which kwallet returns "") whereas kwallet-query + # checks hasEntry. To verify this: + # dbus-monitor "interface='org.kde.KWallet'" "type=method_return" + # while starting chrome. + # this was identified as a bug later and fixed in + # https://chromium.googlesource.com/chromium/src/+/bbd54702284caca1f92d656fdcadf2ccca6f4165%5E%21/#F0 + # https://chromium.googlesource.com/chromium/src/+/5463af3c39d7f5b6d11db7fbd51e38cc1974d764 + return b'' + else: + logger.debug('password found') + return stdout.rstrip(b'\n') + except Exception as e: + logger.warning(f'exception running kwallet-query: {error_to_str(e)}') + return b'' + + +def _get_gnome_keyring_password(browser_keyring_name, logger): + if not secretstorage: + logger.error(f'secretstorage not available {_SECRETSTORAGE_UNAVAILABLE_REASON}') + return b'' + # the Gnome keyring does not seem to organise keys in the same way as KWallet, + # using `dbus-monitor` during startup, it can be observed that chromium lists all keys + # and presumably searches for its key in the list. It appears that we must do the same. + # https://github.com/jaraco/keyring/issues/556 + with contextlib.closing(secretstorage.dbus_init()) as con: + col = secretstorage.get_default_collection(con) + for item in col.get_all_items(): + if item.get_label() == f'{browser_keyring_name} Safe Storage': + return item.get_secret() + logger.error('failed to read from keyring') + return b'' + + +def _get_linux_keyring_password(browser_keyring_name, keyring, logger): + # note: chrome/chromium can be run with the following flags to determine which keyring backend + # it has chosen to use + # chromium --enable-logging=stderr --v=1 2>&1 | grep key_storage_ + # Chromium supports a flag: --password-store= so the automatic detection + # will not be sufficient in all cases. + + keyring = _LinuxKeyring[keyring] if keyring else _choose_linux_keyring(logger) + logger.debug(f'Chosen keyring: {keyring.name}') + + if keyring in (_LinuxKeyring.KWALLET, _LinuxKeyring.KWALLET5, _LinuxKeyring.KWALLET6): + return _get_kwallet_password(browser_keyring_name, keyring, logger) + elif keyring == _LinuxKeyring.GNOMEKEYRING: + return _get_gnome_keyring_password(browser_keyring_name, logger) + elif keyring == _LinuxKeyring.BASICTEXT: + # when basic text is chosen, all cookies are stored as v10 (so no keyring password is required) + return None + assert False, f'Unknown keyring {keyring}' + + +def _get_mac_keyring_password(browser_keyring_name, logger): + logger.debug('using find-generic-password to obtain password from OSX keychain') + try: + stdout, _, returncode = Popen.run( + ['security', 'find-generic-password', + '-w', # write password to stdout + '-a', browser_keyring_name, # match 'account' + '-s', f'{browser_keyring_name} Safe Storage'], # match 'service' + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + if returncode: + logger.warning('find-generic-password failed') + return None + return stdout.rstrip(b'\n') + except Exception as e: + logger.warning(f'exception running find-generic-password: {error_to_str(e)}') + return None + + +def _get_windows_v10_key(browser_root, logger): + """ + References: + - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_win.cc + """ + path = _newest(_find_files(browser_root, 'Local State', logger)) + if path is None: + logger.error('could not find local state file') + return None + logger.debug(f'Found local state file at "{path}"') + with open(path, encoding='utf8') as f: + data = json.load(f) + try: + # kOsCryptEncryptedKeyPrefName in [1] + base64_key = data['os_crypt']['encrypted_key'] + except KeyError: + logger.error('no encrypted key in Local State') + return None + encrypted_key = base64.b64decode(base64_key) + # kDPAPIKeyPrefix in [1] + prefix = b'DPAPI' + if not encrypted_key.startswith(prefix): + logger.error('invalid key') + return None + return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger) + + +def pbkdf2_sha1(password, salt, iterations, key_length): + return hashlib.pbkdf2_hmac('sha1', password, salt, iterations, key_length) + + +def _decrypt_aes_cbc_multi(ciphertext, keys, logger, initialization_vector=b' ' * 16, hash_prefix=False): + for key in keys: + plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector)) + try: + if hash_prefix: + return plaintext[32:].decode() + return plaintext.decode() + except UnicodeDecodeError: + pass + logger.warning('failed to decrypt cookie (AES-CBC) because UTF-8 decoding failed. Possibly the key is wrong?', only_once=True) + return None + + +def _decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag, logger, hash_prefix=False): + try: + plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag, nonce) + except ValueError: + logger.warning('failed to decrypt cookie (AES-GCM) because the MAC check failed. Possibly the key is wrong?', only_once=True) + return None + + try: + if hash_prefix: + return plaintext[32:].decode() + return plaintext.decode() + except UnicodeDecodeError: + logger.warning('failed to decrypt cookie (AES-GCM) because UTF-8 decoding failed. Possibly the key is wrong?', only_once=True) + return None + + +def _decrypt_windows_dpapi(ciphertext, logger): + """ + References: + - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata + """ + + import ctypes + import ctypes.wintypes + + class DATA_BLOB(ctypes.Structure): + _fields_ = [('cbData', ctypes.wintypes.DWORD), + ('pbData', ctypes.POINTER(ctypes.c_char))] + + buffer = ctypes.create_string_buffer(ciphertext) + blob_in = DATA_BLOB(ctypes.sizeof(buffer), buffer) + blob_out = DATA_BLOB() + ret = ctypes.windll.crypt32.CryptUnprotectData( + ctypes.byref(blob_in), # pDataIn + None, # ppszDataDescr: human readable description of pDataIn + None, # pOptionalEntropy: salt? + None, # pvReserved: must be NULL + None, # pPromptStruct: information about prompts to display + 0, # dwFlags + ctypes.byref(blob_out), # pDataOut + ) + if not ret: + message = 'Failed to decrypt with DPAPI. See https://github.com/yt-dlp/yt-dlp/issues/10927 for more info' + logger.error(message) + raise DownloadError(message) # force exit + + result = ctypes.string_at(blob_out.pbData, blob_out.cbData) + ctypes.windll.kernel32.LocalFree(blob_out.pbData) + return result + + +def _config_home(): + return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) + + +def _open_database_copy(database_path, tmpdir): + # cannot open sqlite databases if they are already in use (e.g. by the browser) + database_copy_path = os.path.join(tmpdir, 'temporary.sqlite') + shutil.copy(database_path, database_copy_path) + conn = sqlite3.connect(database_copy_path) + return conn.cursor() + + +def _get_column_names(cursor, table_name): + table_info = cursor.execute(f'PRAGMA table_info({table_name})').fetchall() + return [row[1].decode() for row in table_info] + + +def _newest(files): + return max(files, key=lambda path: os.lstat(path).st_mtime, default=None) + + +def _find_files(root, filename, logger): + # if there are multiple browser profiles, take the most recently used one + i = 0 + with _create_progress_bar(logger) as progress_bar: + for curr_root, _, files in os.walk(root): + for file in files: + i += 1 + progress_bar.print(f'Searching for "{filename}": {i: 6d} files searched') + if file == filename: + yield os.path.join(curr_root, file) + + +def _merge_cookie_jars(jars): + output_jar = YoutubeDLCookieJar() + for jar in jars: + for cookie in jar: + output_jar.set_cookie(cookie) + if jar.filename is not None: + output_jar.filename = jar.filename + return output_jar + + +def _is_path(value): + return any(sep in value for sep in (os.path.sep, os.path.altsep) if sep) + + +def _parse_browser_specification(browser_name, profile=None, keyring=None, container=None): + if browser_name not in SUPPORTED_BROWSERS: + raise ValueError(f'unsupported browser: "{browser_name}"') + if keyring not in (None, *SUPPORTED_KEYRINGS): + raise ValueError(f'unsupported keyring: "{keyring}"') + if profile is not None and _is_path(expand_path(profile)): + profile = expand_path(profile) + return browser_name, profile, keyring, container + + +class LenientSimpleCookie(http.cookies.SimpleCookie): + """More lenient version of http.cookies.SimpleCookie""" + # From https://github.com/python/cpython/blob/v3.10.7/Lib/http/cookies.py + # We use Morsel's legal key chars to avoid errors on setting values + _LEGAL_KEY_CHARS = r'\w\d' + re.escape('!#$%&\'*+-.:^_`|~') + _LEGAL_VALUE_CHARS = _LEGAL_KEY_CHARS + re.escape('(),/<=>?@[]{}') + _LEGAL_KEY_RE = re.compile(rf'[{_LEGAL_KEY_CHARS}]+', re.ASCII) + + _RESERVED = { + 'expires', + 'path', + 'comment', + 'domain', + 'max-age', + 'secure', + 'httponly', + 'version', + 'samesite', + } + + _FLAGS = {'secure', 'httponly'} + + # Added 'bad' group to catch the remaining value + _COOKIE_PATTERN = re.compile(r''' + [ ]* # Optional whitespace at start of cookie + (?P # Start of group 'key' + [^ =;]+ # Match almost anything here for now and validate later + ) # End of group 'key' + ( # Optional group: there may not be a value. + [ ]*=[ ]* # Equal Sign + ( # Start of potential value + (?P # Start of group 'val' + "(?:[^\\"]|\\.)*" # Any doublequoted string + | # or + \w{3},\ [\w\d -]{9,11}\ [\d:]{8}\ GMT # Special case for "expires" attr + | # or + [''' + _LEGAL_VALUE_CHARS + r''']* # Any word or empty string + ) # End of group 'val' + | # or + (?P(?:\\;|[^;])*?) # 'bad' group fallback for invalid values + ) # End of potential value + )? # End of optional value group + [ ]* # Any number of spaces. + ([ ]+|;|$) # Ending either at space, semicolon, or EOS. + ''', re.ASCII | re.VERBOSE) + + # http.cookies.Morsel raises on values w/ control characters in Python 3.14.3+ & 3.13.12+ + # Ref: https://github.com/python/cpython/issues/143919 + _CONTROL_CHARACTER_RE = re.compile(r'[\x00-\x1F\x7F]') + + def load(self, data): + # Workaround for https://github.com/yt-dlp/yt-dlp/issues/4776 + if not isinstance(data, str): + return super().load(data) + + morsel = None + for match in self._COOKIE_PATTERN.finditer(data): + if match.group('bad'): + morsel = None + continue + + key, value = match.group('key', 'val') + if not self._LEGAL_KEY_RE.fullmatch(key): + morsel = None + continue + + is_attribute = False + if key.startswith('$'): + key = key[1:] + is_attribute = True + + lower_key = key.lower() + if lower_key in self._RESERVED: + if morsel is None: + continue + + if value is None: + if lower_key not in self._FLAGS: + morsel = None + continue + value = True + else: + value, _ = self.value_decode(value) + # Guard against control characters in quoted attribute values + if self._CONTROL_CHARACTER_RE.search(value): + # While discarding the entire morsel is not very lenient, + # it's better than http.cookies.Morsel raising a CookieError + # and it's probably better to err on the side of caution + self.pop(morsel.key, None) + morsel = None + continue + + morsel[key] = value + + elif is_attribute: + morsel = None + + elif value is not None: + morsel = self.get(key, http.cookies.Morsel()) + real_value, coded_value = self.value_decode(value) + # Guard against control characters in quoted cookie values + if self._CONTROL_CHARACTER_RE.search(real_value): + morsel = None + continue + morsel.set(key, real_value, coded_value) + self[key] = morsel + + else: + morsel = None + + +class YoutubeDLCookieJar(http.cookiejar.MozillaCookieJar): + """ + See [1] for cookie file format. + + 1. https://curl.haxx.se/docs/http-cookies.html + """ + _HTTPONLY_PREFIX = '#HttpOnly_' + _ENTRY_LEN = 7 + _HEADER = '''# Netscape HTTP Cookie File +# This file is generated by yt-dlp. Do not edit. + +''' + _CookieFileEntry = collections.namedtuple( + 'CookieFileEntry', + ('domain_name', 'include_subdomains', 'path', 'https_only', 'expires_at', 'name', 'value')) + + def __init__(self, filename=None, *args, **kwargs): + super().__init__(None, *args, **kwargs) + if is_path_like(filename): + filename = os.fspath(filename) + self.filename = filename + + @staticmethod + def _true_or_false(cndn): + return 'TRUE' if cndn else 'FALSE' + + @contextlib.contextmanager + def open(self, file, *, write=False): + if is_path_like(file): + with open(file, 'w' if write else 'r', encoding='utf-8') as f: + yield f + else: + if write: + file.truncate(0) + yield file + + def _really_save(self, f, ignore_discard, ignore_expires): + now = time.time() + for cookie in self: + if ((not ignore_discard and cookie.discard) + or (not ignore_expires and cookie.is_expired(now))): + continue + name, value = cookie.name, cookie.value + if value is None: + # cookies.txt regards 'Set-Cookie: foo' as a cookie + # with no name, whereas http.cookiejar regards it as a + # cookie with no value. + name, value = '', name + f.write('{}\n'.format('\t'.join(( + cookie.domain, + self._true_or_false(cookie.domain.startswith('.')), + cookie.path, + self._true_or_false(cookie.secure), + str_or_none(cookie.expires, default=''), + name, value, + )))) + + def save(self, filename=None, ignore_discard=True, ignore_expires=True): + """ + Save cookies to a file. + Code is taken from CPython 3.6 + https://github.com/python/cpython/blob/8d999cbf4adea053be6dbb612b9844635c4dfb8e/Lib/http/cookiejar.py#L2091-L2117 """ + + if filename is None: + if self.filename is not None: + filename = self.filename + else: + raise ValueError(http.cookiejar.MISSING_FILENAME_TEXT) + + # Store session cookies with `expires` set to 0 instead of an empty string + for cookie in self: + if cookie.expires is None: + cookie.expires = 0 + + with self.open(filename, write=True) as f: + f.write(self._HEADER) + self._really_save(f, ignore_discard, ignore_expires) + + def load(self, filename=None, ignore_discard=True, ignore_expires=True): + """Load cookies from a file.""" + if filename is None: + if self.filename is not None: + filename = self.filename + else: + raise ValueError(http.cookiejar.MISSING_FILENAME_TEXT) + + def prepare_line(line): + if line.startswith(self._HTTPONLY_PREFIX): + line = line[len(self._HTTPONLY_PREFIX):] + # comments and empty lines are fine + if line.startswith('#') or not line.strip(): + return line + cookie_list = line.split('\t') + if len(cookie_list) != self._ENTRY_LEN: + raise http.cookiejar.LoadError(f'invalid length {len(cookie_list)}') + cookie = self._CookieFileEntry(*cookie_list) + if cookie.expires_at and not re.fullmatch(r'[0-9]+(?:\.[0-9]+)?', cookie.expires_at): + raise http.cookiejar.LoadError(f'invalid expires at {cookie.expires_at}') + return line + + cf = io.StringIO() + with self.open(filename) as f: + for line in f: + try: + cf.write(prepare_line(line)) + except http.cookiejar.LoadError as e: + if f'{line.strip()} '[0] in '[{"': + raise http.cookiejar.LoadError( + 'Cookies file must be Netscape formatted, not JSON. See ' + 'https://github.com/yt-dlp/yt-dlp/wiki/FAQ#how-do-i-pass-cookies-to-yt-dlp') + write_string(f'WARNING: skipping cookie file entry due to {e}: {line!r}\n') + continue + cf.seek(0) + self._really_load(cf, filename, ignore_discard, ignore_expires) + # Session cookies are denoted by either `expires` field set to + # an empty string or 0. MozillaCookieJar only recognizes the former + # (see [1]). So we need force the latter to be recognized as session + # cookies on our own. + # Session cookies may be important for cookies-based authentication, + # e.g. usually, when user does not check 'Remember me' check box while + # logging in on a site, some important cookies are stored as session + # cookies so that not recognizing them will result in failed login. + # 1. https://bugs.python.org/issue17164 + for cookie in self: + # Treat `expires=0` cookies as session cookies + if cookie.expires == 0: + cookie.expires = None + cookie.discard = True + + def get_cookie_header(self, url): + """Generate a Cookie HTTP header for a given url""" + cookie_req = urllib.request.Request(normalize_url(sanitize_url(url))) + self.add_cookie_header(cookie_req) + return cookie_req.get_header('Cookie') + + def get_cookies_for_url(self, url): + """Generate a list of Cookie objects for a given url""" + # Policy `_now` attribute must be set before calling `_cookies_for_request` + # Ref: https://github.com/python/cpython/blob/3.7/Lib/http/cookiejar.py#L1360 + self._policy._now = self._now = int(time.time()) + return self._cookies_for_request(urllib.request.Request(normalize_url(sanitize_url(url)))) + + def clear(self, *args, **kwargs): + with contextlib.suppress(KeyError): + return super().clear(*args, **kwargs) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/alphaporno.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/alphaporno.py new file mode 100644 index 0000000000000000000000000000000000000000..7b74d5524d65ae15e7559947bb9008493ba8da95 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/alphaporno.py @@ -0,0 +1,75 @@ +from .common import InfoExtractor +from ..utils import ( + int_or_none, + parse_duration, + parse_filesize, + parse_iso8601, +) + + +class AlphaPornoIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?alphaporno\.com/videos/(?P[^/]+)' + _TEST = { + 'url': 'http://www.alphaporno.com/videos/sensual-striptease-porn-with-samantha-alexandra/', + 'md5': 'feb6d3bba8848cd54467a87ad34bd38e', + 'info_dict': { + 'id': '258807', + 'display_id': 'sensual-striptease-porn-with-samantha-alexandra', + 'ext': 'mp4', + 'title': 'Sensual striptease porn with Samantha Alexandra', + 'thumbnail': r're:https?://.*\.jpg$', + 'timestamp': 1418694611, + 'upload_date': '20141216', + 'duration': 387, + 'filesize_approx': 54120000, + 'tbr': 1145, + 'categories': list, + 'age_limit': 18, + }, + } + + def _real_extract(self, url): + display_id = self._match_id(url) + + webpage = self._download_webpage(url, display_id) + + video_id = self._search_regex( + r"video_id\s*:\s*'([^']+)'", webpage, 'video id', default=None) + + video_url = self._search_regex( + r"video_url\s*:\s*'([^']+)'", webpage, 'video url') + ext = self._html_search_meta( + 'encodingFormat', webpage, 'ext', default='.mp4')[1:] + + title = self._search_regex( + [r'', + r'class="title" itemprop="name">([^<]+)<'], + webpage, 'title') + thumbnail = self._html_search_meta('thumbnail', webpage, 'thumbnail') + timestamp = parse_iso8601(self._html_search_meta( + 'uploadDate', webpage, 'upload date')) + duration = parse_duration(self._html_search_meta( + 'duration', webpage, 'duration')) + filesize_approx = parse_filesize(self._html_search_meta( + 'contentSize', webpage, 'file size')) + bitrate = int_or_none(self._html_search_meta( + 'bitrate', webpage, 'bitrate')) + categories = self._html_search_meta( + 'keywords', webpage, 'categories', default='').split(',') + + age_limit = self._rta_search(webpage) + + return { + 'id': video_id, + 'display_id': display_id, + 'url': video_url, + 'ext': ext, + 'title': title, + 'thumbnail': thumbnail, + 'timestamp': timestamp, + 'duration': duration, + 'filesize_approx': filesize_approx, + 'tbr': bitrate, + 'categories': categories, + 'age_limit': age_limit, + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/alsace20tv.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/alsace20tv.py new file mode 100644 index 0000000000000000000000000000000000000000..c315e4f2170401f4f2442d05d0bba1671d2e8d6f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/alsace20tv.py @@ -0,0 +1,83 @@ +from .common import InfoExtractor +from ..utils import ( + clean_html, + dict_get, + get_element_by_class, + int_or_none, + unified_strdate, + url_or_none, +) + + +class Alsace20TVBaseIE(InfoExtractor): + def _extract_video(self, video_id, url=None): + info = self._download_json( + f'https://www.alsace20.tv/visionneuse/visio_v9_js.php?key={video_id}&habillage=0&mode=html', + video_id) or {} + title = info.get('titre') + + formats = [] + for res, fmt_url in (info.get('files') or {}).items(): + formats.extend( + self._extract_smil_formats(fmt_url, video_id, fatal=False) + if '/smil:_' in fmt_url + else self._extract_mpd_formats(fmt_url, video_id, mpd_id=res, fatal=False)) + + webpage = (url and self._download_webpage(url, video_id, fatal=False)) or '' + thumbnail = url_or_none(dict_get(info, ('image', 'preview')) or self._og_search_thumbnail(webpage)) + upload_date = self._search_regex(r'/(\d{6})_', thumbnail, 'upload_date', default=None) + upload_date = unified_strdate(f'20{upload_date[:2]}-{upload_date[2:4]}-{upload_date[4:]}') if upload_date else None + return { + 'id': video_id, + 'title': title, + 'formats': formats, + 'description': clean_html(get_element_by_class('wysiwyg', webpage)), + 'upload_date': upload_date, + 'thumbnail': thumbnail, + 'duration': int_or_none(self._og_search_property('video:duration', webpage) if webpage else None), + 'view_count': int_or_none(info.get('nb_vues')), + } + + +class Alsace20TVIE(Alsace20TVBaseIE): + _VALID_URL = r'https?://(?:www\.)?alsace20\.tv/(?:[\w-]+/)+[\w-]+-(?P[\w]+)' + _TESTS = [{ + 'url': 'https://www.alsace20.tv/VOD/Actu/JT/Votre-JT-jeudi-3-fevrier-lyNHCXpYJh.html', + 'info_dict': { + 'id': 'lyNHCXpYJh', + 'ext': 'mp4', + 'description': 'md5:fc0bc4a0692d3d2dba4524053de4c7b7', + 'title': 'Votre JT du jeudi 3 février', + 'upload_date': '20220203', + 'thumbnail': r're:https?://.+\.jpg', + 'duration': 1073, + 'view_count': int, + }, + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + return self._extract_video(video_id, url) + + +class Alsace20TVEmbedIE(Alsace20TVBaseIE): + _VALID_URL = r'https?://(?:www\.)?alsace20\.tv/emb/(?P[\w]+)' + _TESTS = [{ + 'url': 'https://www.alsace20.tv/emb/lyNHCXpYJh', + # 'md5': 'd91851bf9af73c0ad9b2cdf76c127fbb', + 'info_dict': { + 'id': 'lyNHCXpYJh', + 'ext': 'mp4', + 'title': 'Votre JT du jeudi 3 février', + 'upload_date': '20220203', + 'thumbnail': r're:https?://.+\.jpg', + 'view_count': int, + }, + 'params': { + 'format': 'bestvideo', + }, + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + return self._extract_video(video_id) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/altcensored.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/altcensored.py new file mode 100644 index 0000000000000000000000000000000000000000..bfbf6b6afdee63281273562454ff8b360176db37 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/altcensored.py @@ -0,0 +1,104 @@ +import re + +from .archiveorg import ArchiveOrgIE +from .common import InfoExtractor +from ..utils import ( + InAdvancePagedList, + clean_html, + int_or_none, + orderedSet, + str_to_int, + urljoin, +) + + +class AltCensoredIE(InfoExtractor): + IE_NAME = 'altcensored' + _VALID_URL = r'https?://(?:www\.)?altcensored\.com/(?:watch\?v=|embed/)(?P[^/?#]+)' + _TESTS = [{ + 'url': 'https://www.altcensored.com/watch?v=k0srjLSkga8', + 'info_dict': { + 'id': 'youtube-k0srjLSkga8', + 'ext': 'webm', + 'title': "QUELLES SONT LES CONSÉQUENCES DE L'HYPERSEXUALISATION DE LA SOCIÉTÉ ?", + 'display_id': 'k0srjLSkga8.webm', + 'release_date': '20180403', + 'creators': ['Virginie Vota'], + 'release_year': 2018, + 'upload_date': '20230318', + 'uploader': 'admin@altcensored.com', + 'description': 'md5:0b38a8fc04103579d5c1db10a247dc30', + 'timestamp': 1679161343, + 'track': 'k0srjLSkga8', + 'duration': 926.09, + 'thumbnail': 'https://archive.org/download/youtube-k0srjLSkga8/youtube-k0srjLSkga8.thumbs/k0srjLSkga8_000925.jpg', + 'view_count': int, + 'categories': ['News & Politics'], + }, + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + webpage = self._download_webpage(url, video_id) + category = clean_html(self._html_search_regex( + r'([^<]+)', webpage, 'category', default=None)) + + return { + '_type': 'url_transparent', + 'url': f'https://archive.org/details/youtube-{video_id}', + 'ie_key': ArchiveOrgIE.ie_key(), + 'view_count': str_to_int(self._html_search_regex( + r'YouTube Views:(?:\s| )*([\d,]+)', webpage, 'view count', default=None)), + 'categories': [category] if category else None, + } + + +class AltCensoredChannelIE(InfoExtractor): + IE_NAME = 'altcensored:channel' + _VALID_URL = r'https?://(?:www\.)?altcensored\.com/channel/(?!page|table)(?P[^/?#]+)' + _PAGE_SIZE = 24 + _TESTS = [{ + 'url': 'https://www.altcensored.com/channel/UCFPTO55xxHqFqkzRZHu4kcw', + 'info_dict': { + 'title': 'Virginie Vota', + 'id': 'UCFPTO55xxHqFqkzRZHu4kcw', + }, + 'playlist_count': 85, + }, { + 'url': 'https://altcensored.com/channel/UC9CcJ96HKMWn0LZlcxlpFTw', + 'info_dict': { + 'title': 'yukikaze775', + 'id': 'UC9CcJ96HKMWn0LZlcxlpFTw', + }, + 'playlist_count': 4, + }, { + 'url': 'https://altcensored.com/channel/UCfYbb7nga6-icsFWWgS-kWw', + 'info_dict': { + 'title': 'Mister Metokur', + 'id': 'UCfYbb7nga6-icsFWWgS-kWw', + }, + 'playlist_count': 121, + }] + + def _real_extract(self, url): + channel_id = self._match_id(url) + webpage = self._download_webpage( + url, channel_id, 'Download channel webpage', 'Unable to get channel webpage') + title = self._html_search_meta('altcen_title', webpage, 'title', fatal=False) + page_count = int_or_none(self._html_search_regex( + r']+href="/channel/[\w-]+/page/(\d+)">(?:\1)', + webpage, 'page count', default='1')) + + def page_func(page_num): + page_num += 1 + webpage = self._download_webpage( + f'https://altcensored.com/channel/{channel_id}/page/{page_num}', + channel_id, note=f'Downloading page {page_num}') + + items = re.findall(r']+href="(/watch\?v=[^"]+)', webpage) + return [self.url_result(urljoin('https://www.altcensored.com', path), AltCensoredIE) + for path in orderedSet(items)] + + return self.playlist_result( + InAdvancePagedList(page_func, page_count, self._PAGE_SIZE), + playlist_id=channel_id, playlist_title=title) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/azmedien.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/azmedien.py new file mode 100644 index 0000000000000000000000000000000000000000..9f6bd820c13362672db8f71224a26cfd9806db81 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/azmedien.py @@ -0,0 +1,63 @@ +from .common import InfoExtractor +from .kaltura import KalturaIE +from ..utils.traversal import require, traverse_obj + + +class AZMedienIE(InfoExtractor): + IE_DESC = 'AZ Medien videos' + _VALID_URL = r'''(?x) + https?:// + (?:www\.|tv\.)? + (?: + telezueri\.ch| + telebaern\.tv| + telem1\.ch| + tvo-online\.ch + )/ + [^/?#]+/ + (?P + [^/?#]+-\d+ + ) + (?: + \#video= + (?P + [_0-9a-z]+ + ) + )? + ''' + + _TESTS = [{ + 'url': 'https://tv.telezueri.ch/sonntalk/bundesrats-vakanzen-eu-rahmenabkommen-133214569', + 'info_dict': { + 'id': '1_anruz3wy', + 'ext': 'mp4', + 'title': 'Bundesrats-Vakanzen / EU-Rahmenabkommen', + 'uploader_id': 'TVOnline', + 'upload_date': '20180930', + 'timestamp': 1538328802, + 'view_count': int, + 'thumbnail': 'http://cfvod.kaltura.com/p/1719221/sp/171922100/thumbnail/entry_id/1_anruz3wy/version/100031', + 'duration': 1930, + }, + 'params': { + 'skip_download': True, + }, + }, { + 'url': 'https://www.telebaern.tv/telebaern-news/montag-1-oktober-2018-ganze-sendung-133531189#video=0_7xjo9lf1', + 'only_matching': True, + }] + _PARTNER_ID = '1719221' + + def _real_extract(self, url): + display_id, entry_id = self._match_valid_url(url).groups() + + if not entry_id: + webpage = self._download_webpage(url, display_id) + data = self._search_json( + r'window\.__APOLLO_STATE__\s*=', webpage, 'video data', display_id) + entry_id = traverse_obj(data, ( + lambda _, v: v['__typename'] == 'KalturaData', 'kalturaId', any, {require('kaltura id')})) + + return self.url_result( + f'kaltura:{self._PARTNER_ID}:{entry_id}', + ie=KalturaIE.ie_key(), video_id=entry_id) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/beatbump.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/beatbump.py new file mode 100644 index 0000000000000000000000000000000000000000..777a1b3268dfd5c90a21f5d2f1fa9d62cf20618e --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/beatbump.py @@ -0,0 +1,111 @@ +from .common import InfoExtractor +from .youtube import YoutubeIE, YoutubeTabIE + + +class BeatBumpVideoIE(InfoExtractor): + _VALID_URL = r'https?://beatbump\.(?:ml|io)/listen\?id=(?P[\w-]+)' + _TESTS = [{ + 'url': 'https://beatbump.ml/listen?id=MgNrAu2pzNs', + 'md5': '5ff3fff41d3935b9810a9731e485fe66', + 'info_dict': { + 'id': 'MgNrAu2pzNs', + 'ext': 'mp4', + 'artist': 'Stephen', + 'thumbnail': 'https://i.ytimg.com/vi_webp/MgNrAu2pzNs/maxresdefault.webp', + 'channel_url': 'https://www.youtube.com/channel/UC-pWHpBjdGG69N9mM2auIAA', + 'upload_date': '20190312', + 'categories': ['Music'], + 'playable_in_embed': True, + 'duration': 169, + 'like_count': int, + 'alt_title': 'Voyeur Girl', + 'view_count': int, + 'track': 'Voyeur Girl', + 'uploader': 'Stephen', + 'title': 'Voyeur Girl', + 'channel_follower_count': int, + 'age_limit': 0, + 'availability': 'public', + 'live_status': 'not_live', + 'album': 'it\'s too much love to know my dear', + 'channel': 'Stephen', + 'comment_count': int, + 'description': 'md5:7ae382a65843d6df2685993e90a8628f', + 'tags': 'count:11', + 'creator': 'Stephen', + 'channel_id': 'UC-pWHpBjdGG69N9mM2auIAA', + 'channel_is_verified': True, + 'heatmap': 'count:100', + }, + }, { + 'url': 'https://beatbump.io/listen?id=LDGZAprNGWo', + 'only_matching': True, + }] + + def _real_extract(self, url): + id_ = self._match_id(url) + return self.url_result(f'https://music.youtube.com/watch?v={id_}', YoutubeIE, id_) + + +class BeatBumpPlaylistIE(InfoExtractor): + _VALID_URL = r'https?://beatbump\.(?:ml|io)/(?:release\?id=|artist/|playlist/)(?P[\w-]+)' + _TESTS = [{ + 'url': 'https://beatbump.ml/release?id=MPREb_gTAcphH99wE', + 'playlist_count': 50, + 'info_dict': { + 'id': 'OLAK5uy_l1m0thk3g31NmIIz_vMIbWtyv7eZixlH0', + 'availability': 'unlisted', + 'view_count': int, + 'title': 'Album - Royalty Free Music Library V2 (50 Songs)', + 'description': '', + 'tags': [], + 'modified_date': '20231110', + }, + 'expected_warnings': ['YouTube Music is not directly supported'], + }, { + 'url': 'https://beatbump.ml/artist/UC_aEa8K-EOJ3D6gOs7HcyNg', + 'playlist_mincount': 1, + 'params': {'flatplaylist': True}, + 'info_dict': { + 'id': 'UC_aEa8K-EOJ3D6gOs7HcyNg', + 'uploader_url': 'https://www.youtube.com/@NoCopyrightSounds', + 'channel_url': 'https://www.youtube.com/channel/UC_aEa8K-EOJ3D6gOs7HcyNg', + 'uploader_id': '@NoCopyrightSounds', + 'channel_follower_count': int, + 'title': 'NoCopyrightSounds', + 'uploader': 'NoCopyrightSounds', + 'description': 'md5:cd4fd53d81d363d05eee6c1b478b491a', + 'channel': 'NoCopyrightSounds', + 'tags': 'count:65', + 'channel_id': 'UC_aEa8K-EOJ3D6gOs7HcyNg', + 'channel_is_verified': True, + }, + 'expected_warnings': ['YouTube Music is not directly supported'], + }, { + 'url': 'https://beatbump.ml/playlist/VLPLRBp0Fe2GpgmgoscNFLxNyBVSFVdYmFkq', + 'playlist_mincount': 1, + 'params': {'flatplaylist': True}, + 'info_dict': { + 'id': 'PLRBp0Fe2GpgmgoscNFLxNyBVSFVdYmFkq', + 'uploader_url': 'https://www.youtube.com/@NoCopyrightSounds', + 'description': 'Providing you with copyright free / safe music for gaming, live streaming, studying and more!', + 'view_count': int, + 'channel_url': 'https://www.youtube.com/channel/UC_aEa8K-EOJ3D6gOs7HcyNg', + 'uploader_id': '@NoCopyrightSounds', + 'title': 'NCS : All Releases 💿', + 'uploader': 'NoCopyrightSounds', + 'availability': 'public', + 'channel': 'NoCopyrightSounds', + 'tags': [], + 'modified_date': '20231112', + 'channel_id': 'UC_aEa8K-EOJ3D6gOs7HcyNg', + }, + 'expected_warnings': ['YouTube Music is not directly supported'], + }, { + 'url': 'https://beatbump.io/playlist/VLPLFCHGavqRG-q_2ZhmgU2XB2--ZY6irT1c', + 'only_matching': True, + }] + + def _real_extract(self, url): + id_ = self._match_id(url) + return self.url_result(f'https://music.youtube.com/browse/{id_}', YoutubeTabIE, id_) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/biobiochiletv.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/biobiochiletv.py new file mode 100644 index 0000000000000000000000000000000000000000..180c9656e3556a7b54e5444dbe439b51161396f8 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/biobiochiletv.py @@ -0,0 +1,83 @@ +from .common import InfoExtractor +from ..utils import ( + ExtractorError, + remove_end, +) + + +class BioBioChileTVIE(InfoExtractor): + _VALID_URL = r'https?://(?:tv|www)\.biobiochile\.cl/(?:notas|noticias)/(?:[^/]+/)+(?P[^/]+)\.shtml' + + _TESTS = [{ + 'url': 'http://tv.biobiochile.cl/notas/2015/10/21/sobre-camaras-y-camarillas-parlamentarias.shtml', + 'md5': '26f51f03cf580265defefb4518faec09', + 'info_dict': { + 'id': 'sobre-camaras-y-camarillas-parlamentarias', + 'ext': 'mp4', + 'title': 'Sobre Cámaras y camarillas parlamentarias', + 'thumbnail': r're:^https?://.*\.jpg$', + 'uploader': 'Fernando Atria', + }, + 'skip': 'URL expired and redirected to http://www.biobiochile.cl/portada/bbtv/index.html', + }, { + # different uploader layout + 'url': 'http://tv.biobiochile.cl/notas/2016/03/18/natalia-valdebenito-repasa-a-diputado-hasbun-paso-a-la-categoria-de-hablar-brutalidades.shtml', + 'md5': 'edc2e6b58974c46d5b047dea3c539ff3', + 'info_dict': { + 'id': 'natalia-valdebenito-repasa-a-diputado-hasbun-paso-a-la-categoria-de-hablar-brutalidades', + 'ext': 'mp4', + 'title': 'Natalia Valdebenito repasa a diputado Hasbún: Pasó a la categoría de hablar brutalidades', + 'thumbnail': r're:^https?://.*\.jpg$', + 'uploader': 'Piangella Obrador', + }, + 'params': { + 'skip_download': True, + }, + 'skip': 'URL expired and redirected to http://www.biobiochile.cl/portada/bbtv/index.html', + }, { + 'url': 'http://www.biobiochile.cl/noticias/bbtv/comentarios-bio-bio/2016/07/08/edecanes-del-congreso-figuras-decorativas-que-le-cuestan-muy-caro-a-los-chilenos.shtml', + 'info_dict': { + 'id': 'b4xd0LK3SK', + 'ext': 'mp4', + # TODO: fix url_transparent information overriding + # 'uploader': 'Juan Pablo Echenique', + 'title': 'Comentario Oscar Cáceres', + }, + 'params': { + # empty m3u8 manifest + 'skip_download': True, + }, + }, { + 'url': 'http://tv.biobiochile.cl/notas/2015/10/22/ninos-transexuales-de-quien-es-la-decision.shtml', + 'only_matching': True, + }, { + 'url': 'http://tv.biobiochile.cl/notas/2015/10/21/exclusivo-hector-pinto-formador-de-chupete-revela-version-del-ex-delantero-albo.shtml', + 'only_matching': True, + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + + webpage = self._download_webpage(url, video_id) + + rudo_url = self._search_regex( + r']+src=(?P[\'"])(?P(?:https?:)?//rudo\.video/vod/[0-9a-zA-Z]+)(?P=q1)', + webpage, 'embed URL', None, group='url') + if not rudo_url: + raise ExtractorError('No videos found') + + title = remove_end(self._og_search_title(webpage), ' - BioBioChile TV') + + thumbnail = self._og_search_thumbnail(webpage) + uploader = self._html_search_regex( + r']+href=["\'](?:https?://(?:busca|www)\.biobiochile\.cl)?/(?:lista/)?(?:author|autor)[^>]+>(.+?)', + webpage, 'uploader', fatal=False) + + return { + '_type': 'url_transparent', + 'url': rudo_url, + 'id': video_id, + 'title': title, + 'thumbnail': thumbnail, + 'uploader': uploader, + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/bloomberg.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/bloomberg.py new file mode 100644 index 0000000000000000000000000000000000000000..ec6b7a86eb1f95aff29020575805a8c6bb80750c --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/bloomberg.py @@ -0,0 +1,77 @@ +import re + +from .common import InfoExtractor + + +class BloombergIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?bloomberg\.com/(?:[^/]+/)*(?P[^/?#]+)' + + _TESTS = [{ + 'url': 'https://www.bloomberg.com/news/videos/2021-09-14/apple-unveils-the-new-iphone-13-stock-doesn-t-move-much-video', + 'info_dict': { + 'id': 'V8cFcYMxTHaMcEiiYVr39A', + 'ext': 'flv', + 'title': 'Apple Unveils the New IPhone 13, Stock Doesn\'t Move Much', + }, + 'params': { + 'format': 'best[format_id^=hds]', + }, + }, { + # video ID in BPlayer(...) + 'url': 'http://www.bloomberg.com/features/2016-hello-world-new-zealand/', + 'info_dict': { + 'id': '938c7e72-3f25-4ddb-8b85-a9be731baa74', + 'ext': 'flv', + 'title': 'Meet the Real-Life Tech Wizards of Middle Earth', + 'description': 'Hello World, Episode 1: New Zealand’s freaky AI babies, robot exoskeletons, and a virtual you.', + }, + 'params': { + 'format': 'best[format_id^=hds]', + }, + }, { + # data-bmmrid= + 'url': 'https://www.bloomberg.com/politics/articles/2017-02-08/le-pen-aide-briefed-french-central-banker-on-plan-to-print-money', + 'only_matching': True, + }, { + 'url': 'http://www.bloomberg.com/news/articles/2015-11-12/five-strange-things-that-have-been-happening-in-financial-markets', + 'only_matching': True, + }, { + 'url': 'http://www.bloomberg.com/politics/videos/2015-11-25/karl-rove-on-jeb-bush-s-struggles-stopping-trump', + 'only_matching': True, + }] + + def _real_extract(self, url): + name = self._match_id(url) + webpage = self._download_webpage(url, name) + video_id = self._search_regex( + (r'["\']bmmrId["\']\s*:\s*(["\'])(?P(?:(?!\1).)+)\1', + r'videoId\s*:\s*(["\'])(?P(?:(?!\1).)+)\1', + r'data-bmmrid=(["\'])(?P(?:(?!\1).)+)\1'), + webpage, 'id', group='id', default=None) + if not video_id: + bplayer_data = self._parse_json(self._search_regex( + r'BPlayer\(null,\s*({[^;]+})\);', webpage, 'id'), name) + video_id = bplayer_data['id'] + title = re.sub(': Video$', '', self._og_search_title(webpage)) + + embed_info = self._download_json( + f'http://www.bloomberg.com/multimedia/api/embed?id={video_id}', video_id) + formats = [] + for stream in embed_info['streams']: + stream_url = stream.get('url') + if not stream_url: + continue + if stream['muxing_format'] == 'TS': + formats.extend(self._extract_m3u8_formats( + stream_url, video_id, 'mp4', m3u8_id='hls', fatal=False)) + else: + formats.extend(self._extract_f4m_formats( + stream_url, video_id, f4m_id='hds', fatal=False)) + + return { + 'id': video_id, + 'title': title, + 'formats': formats, + 'description': self._og_search_description(webpage), + 'thumbnail': self._og_search_thumbnail(webpage), + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/bluesky.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/bluesky.py new file mode 100644 index 0000000000000000000000000000000000000000..8cb5c0d257b2c053c0aa9a940cbb973972211948 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/bluesky.py @@ -0,0 +1,393 @@ +from .common import InfoExtractor +from ..utils import ( + ExtractorError, + format_field, + int_or_none, + mimetype2ext, + orderedSet, + parse_iso8601, + truncate_string, + update_url_query, + url_basename, + url_or_none, + variadic, +) +from ..utils.traversal import traverse_obj + + +class BlueskyIE(InfoExtractor): + _VALID_URL = [ + r'https?://(?:www\.)?(?:bsky\.app|main\.bsky\.dev)/profile/(?P[\w.:%-]+)/post/(?P\w+)', + r'at://(?P[\w.:%-]+)/app\.bsky\.feed\.post/(?P\w+)', + ] + _TESTS = [{ + 'url': 'https://bsky.app/profile/blu3blue.bsky.social/post/3l4omssdl632g', + 'md5': '375539c1930ab05d15585ed772ab54fd', + 'info_dict': { + 'id': '3l4omssdl632g', + 'ext': 'mp4', + 'uploader': 'Blu3Blu3Lilith', + 'uploader_id': 'blu3blue.bsky.social', + 'uploader_url': 'https://bsky.app/profile/blu3blue.bsky.social', + 'channel_id': 'did:plc:pzdr5ylumf7vmvwasrpr5bf2', + 'channel_url': 'https://bsky.app/profile/did:plc:pzdr5ylumf7vmvwasrpr5bf2', + 'thumbnail': r're:https://video.bsky.app/watch/.*\.jpg$', + 'title': 'OMG WE HAVE VIDEOS NOW', + 'description': 'OMG WE HAVE VIDEOS NOW', + 'upload_date': '20240921', + 'timestamp': 1726940605, + 'like_count': int, + 'repost_count': int, + 'comment_count': int, + 'tags': [], + }, + }, { + 'url': 'https://bsky.app/profile/bsky.app/post/3l3vgf77uco2g', + 'md5': 'b9e344fdbce9f2852c668a97efefb105', + 'info_dict': { + 'id': '3l3vgf77uco2g', + 'ext': 'mp4', + 'uploader': 'Bluesky', + 'uploader_id': 'bsky.app', + 'uploader_url': 'https://bsky.app/profile/bsky.app', + 'channel_id': 'did:plc:z72i7hdynmk6r22z27h6tvur', + 'channel_url': 'https://bsky.app/profile/did:plc:z72i7hdynmk6r22z27h6tvur', + 'thumbnail': r're:https://video.bsky.app/watch/.*\.jpg$', + 'title': 'Bluesky now has video! Update your app to version 1.91 or refresh on ...', + 'alt_title': 'Bluesky video feature announcement', + 'description': r're:(?s)Bluesky now has video! .{239}', + 'upload_date': '20240911', + 'timestamp': 1726074716, + 'like_count': int, + 'repost_count': int, + 'comment_count': int, + 'tags': [], + 'subtitles': { + 'en': 'mincount:1', + }, + }, + }, { + 'url': 'https://main.bsky.dev/profile/souris.moe/post/3l4qhp7bcs52c', + 'md5': '5f2df8c200b5633eb7fb2c984d29772f', + 'info_dict': { + 'id': '3l4qhp7bcs52c', + 'ext': 'mp4', + 'uploader': 'souris', + 'uploader_id': 'souris.moe', + 'uploader_url': 'https://bsky.app/profile/souris.moe', + 'channel_id': 'did:plc:tj7g244gl5v6ai6cm4f4wlqp', + 'channel_url': 'https://bsky.app/profile/did:plc:tj7g244gl5v6ai6cm4f4wlqp', + 'thumbnail': r're:https://video.bsky.app/watch/.*\.jpg$', + 'title': 'Bluesky video #3l4qhp7bcs52c', + 'upload_date': '20240922', + 'timestamp': 1727003838, + 'like_count': int, + 'repost_count': int, + 'comment_count': int, + 'tags': [], + }, + }, { + 'url': 'https://bsky.app/profile/de1.pds.tentacle.expert/post/3l3w4tnezek2e', + 'md5': 'cc0110ed1f6b0247caac8234cc1e861d', + 'info_dict': { + 'id': '3l3w4tnezek2e', + 'ext': 'mp4', + 'uploader': 'clean', + 'uploader_id': 'de1.pds.tentacle.expert', + 'uploader_url': 'https://bsky.app/profile/de1.pds.tentacle.expert', + 'channel_id': 'did:web:de1.tentacle.expert', + 'channel_url': 'https://bsky.app/profile/did:web:de1.tentacle.expert', + 'thumbnail': r're:https://video.bsky.app/watch/.*\.jpg$', + 'title': 'Bluesky video #3l3w4tnezek2e', + 'upload_date': '20240911', + 'timestamp': 1726098823, + 'like_count': int, + 'repost_count': int, + 'comment_count': int, + 'tags': [], + }, + }, { + 'url': 'https://bsky.app/profile/yunayuispink.bsky.social/post/3l7gqcfes742o', + 'info_dict': { + 'id': 'XxK3t_5V3ao', + 'ext': 'mp4', + 'uploader': 'yunayu', + 'uploader_id': '@yunayuispink', + 'uploader_url': 'https://www.youtube.com/@yunayuispink', + 'channel': 'yunayu', + 'channel_id': 'UCPLvXnHa7lTyNoR_dGsU14w', + 'channel_url': 'https://www.youtube.com/channel/UCPLvXnHa7lTyNoR_dGsU14w', + 'thumbnail': 'https://i.ytimg.com/vi_webp/XxK3t_5V3ao/maxresdefault.webp', + 'description': r're:Have a good goodx10000day', + 'title': '5min vs 5hours drawing', + 'availability': 'public', + 'live_status': 'not_live', + 'playable_in_embed': True, + 'upload_date': '20241026', + 'timestamp': 1729967784, + 'duration': 321, + 'age_limit': 0, + 'like_count': int, + 'view_count': int, + 'comment_count': int, + 'channel_follower_count': int, + 'categories': ['Entertainment'], + 'tags': [], + 'chapters': list, + 'heatmap': 'count:100', + }, + 'add_ie': ['Youtube'], + }, { + 'url': 'https://bsky.app/profile/endshark.bsky.social/post/3jzxjkcemae2m', + 'info_dict': { + 'id': '222792849', + 'ext': 'mp3', + 'uploader': 'LASERBAT', + 'uploader_id': 'laserbatx', + 'uploader_url': 'https://laserbatx.bandcamp.com', + 'artists': ['LASERBAT'], + 'album_artists': ['LASERBAT'], + 'album': 'Hari Nezumi [EP]', + 'track': 'Forward to the End', + 'title': 'LASERBAT - Forward to the End', + 'thumbnail': 'https://f4.bcbits.com/img/a2507705510_5.jpg', + 'duration': 228.571, + 'track_id': '222792849', + 'release_date': '20230423', + 'upload_date': '20230423', + 'timestamp': 1682276040.0, + 'release_timestamp': 1682276040.0, + 'track_number': 1, + }, + 'add_ie': ['Bandcamp'], + }, { + 'url': 'https://bsky.app/profile/dannybhoix.bsky.social/post/3l6oe5mtr2c2j', + 'md5': 'b9e344fdbce9f2852c668a97efefb105', + 'info_dict': { + 'id': '3l3vgf77uco2g', + 'ext': 'mp4', + 'uploader': 'Bluesky', + 'uploader_id': 'bsky.app', + 'uploader_url': 'https://bsky.app/profile/bsky.app', + 'channel_id': 'did:plc:z72i7hdynmk6r22z27h6tvur', + 'channel_url': 'https://bsky.app/profile/did:plc:z72i7hdynmk6r22z27h6tvur', + 'thumbnail': r're:https://video.bsky.app/watch/.*\.jpg$', + 'title': 'Bluesky now has video! Update your app to version 1.91 or refresh on ...', + 'alt_title': 'Bluesky video feature announcement', + 'description': r're:(?s)Bluesky now has video! .{239}', + 'upload_date': '20240911', + 'timestamp': 1726074716, + 'like_count': int, + 'repost_count': int, + 'comment_count': int, + 'tags': [], + 'subtitles': { + 'en': 'mincount:1', + }, + }, + }, { + 'url': 'https://bsky.app/profile/cinny.bun.how/post/3l7rdfxhyds2f', + 'md5': '8775118b235cf9fa6b5ad30f95cda75c', + 'info_dict': { + 'id': '3l7rdfxhyds2f', + 'ext': 'mp4', + 'uploader': 'cinnamon 🐇 🏳️‍⚧️', + 'uploader_id': 'cinny.bun.how', + 'uploader_url': 'https://bsky.app/profile/cinny.bun.how', + 'channel_id': 'did:plc:7x6rtuenkuvxq3zsvffp2ide', + 'channel_url': 'https://bsky.app/profile/did:plc:7x6rtuenkuvxq3zsvffp2ide', + 'thumbnail': r're:https://video.bsky.app/watch/.*\.jpg$', + 'title': 'crazy that i look like this tbh', + 'description': 'crazy that i look like this tbh', + 'upload_date': '20241030', + 'timestamp': 1730332128, + 'like_count': int, + 'repost_count': int, + 'comment_count': int, + 'tags': ['sexual'], + 'age_limit': 18, + }, + }, { + 'url': 'at://did:plc:ia76kvnndjutgedggx2ibrem/app.bsky.feed.post/3l6zrz6zyl2dr', + 'md5': '71b0eb6d85d03145e6af6642c7fc6d78', + 'info_dict': { + 'id': '3l6zrz6zyl2dr', + 'ext': 'mp4', + 'uploader': 'mary🐇', + 'uploader_id': 'mary.my.id', + 'uploader_url': 'https://bsky.app/profile/mary.my.id', + 'channel_id': 'did:plc:ia76kvnndjutgedggx2ibrem', + 'channel_url': 'https://bsky.app/profile/did:plc:ia76kvnndjutgedggx2ibrem', + 'thumbnail': r're:https://video.bsky.app/watch/.*\.jpg$', + 'title': 'Bluesky video #3l6zrz6zyl2dr', + 'upload_date': '20241021', + 'timestamp': 1729523172, + 'like_count': int, + 'repost_count': int, + 'comment_count': int, + 'tags': [], + }, + }, { + 'url': 'https://bsky.app/profile/purpleicetea.bsky.social/post/3l7gv55dc2o2w', + 'info_dict': { + 'id': '3l7gv55dc2o2w', + }, + 'playlist': [{ + 'info_dict': { + 'id': '3l7gv55dc2o2w', + 'ext': 'mp4', + 'upload_date': '20241026', + 'description': 'One of my favorite videos', + 'comment_count': int, + 'uploader_url': 'https://bsky.app/profile/purpleicetea.bsky.social', + 'uploader': 'Purple.Ice.Tea', + 'thumbnail': r're:https://video.bsky.app/watch/.*\.jpg$', + 'channel_url': 'https://bsky.app/profile/did:plc:bjh5ffwya5f53dfy47dezuwx', + 'like_count': int, + 'channel_id': 'did:plc:bjh5ffwya5f53dfy47dezuwx', + 'repost_count': int, + 'timestamp': 1729973202, + 'tags': [], + 'uploader_id': 'purpleicetea.bsky.social', + 'title': 'One of my favorite videos', + }, + }, { + 'info_dict': { + 'id': '3l77u64l7le2e', + 'ext': 'mp4', + 'title': "hearing people on twitter say that bluesky isn't funny yet so post t...", + 'like_count': int, + 'uploader_id': 'thafnine.net', + 'uploader_url': 'https://bsky.app/profile/thafnine.net', + 'upload_date': '20241024', + 'channel_url': 'https://bsky.app/profile/did:plc:6ttyq36rhiyed7wu3ws7dmqj', + 'description': r're:(?s)hearing people on twitter say that bluesky .{93}', + 'tags': [], + 'alt_title': 'md5:9b1ee1937fb3d1a81e932f9ec14d560e', + 'uploader': 'T9', + 'channel_id': 'did:plc:6ttyq36rhiyed7wu3ws7dmqj', + 'thumbnail': r're:https://video.bsky.app/watch/.*\.jpg$', + 'timestamp': 1729731642, + 'comment_count': int, + 'repost_count': int, + }, + }], + }] + _BLOB_URL_TMPL = '{}/xrpc/com.atproto.sync.getBlob' + + def _get_service_endpoint(self, did, video_id): + if did.startswith('did:web:'): + url = f'https://{did[8:]}/.well-known/did.json' + else: + url = f'https://plc.directory/{did}' + services = self._download_json( + url, video_id, 'Fetching service endpoint', 'Falling back to bsky.social', fatal=False) + return traverse_obj( + services, ('service', lambda _, x: x['type'] == 'AtprotoPersonalDataServer', + 'serviceEndpoint', {url_or_none}, any)) or 'https://bsky.social' + + def _extract_post(self, handle, post_id): + return self._download_json( + 'https://public.api.bsky.app/xrpc/app.bsky.feed.getPostThread', + post_id, query={ + 'uri': f'at://{handle}/app.bsky.feed.post/{post_id}', + 'depth': 0, + 'parentHeight': 0, + })['thread']['post'] + + def _real_extract(self, url): + handle, video_id = self._match_valid_url(url).group('handle', 'id') + post = self._extract_post(handle, video_id) + + entries = [] + # app.bsky.embed.video.view/app.bsky.embed.external.view + entries.extend(self._extract_videos(post, video_id)) + # app.bsky.embed.recordWithMedia.view + entries.extend(self._extract_videos( + post, video_id, embed_path=('embed', 'media'), record_subpath=('embed', 'media'))) + # app.bsky.embed.record.view + if nested_post := traverse_obj(post, ('embed', 'record', ('record', None), {dict}, any)): + entries.extend(self._extract_videos( + nested_post, video_id, embed_path=('embeds', 0), record_path='value')) + + if not entries: + raise ExtractorError('No video could be found in this post', expected=True) + if len(entries) == 1: + return entries[0] + return self.playlist_result(entries, video_id) + + @staticmethod + def _build_profile_url(path): + return format_field(path, None, 'https://bsky.app/profile/%s', default=None) + + def _extract_videos(self, root, video_id, embed_path='embed', record_path='record', record_subpath='embed'): + embed_path = variadic(embed_path, (str, bytes, dict, set)) + record_path = variadic(record_path, (str, bytes, dict, set)) + record_subpath = variadic(record_subpath, (str, bytes, dict, set)) + + entries = [] + if external_uri := traverse_obj(root, ( + ((*record_path, *record_subpath), embed_path), 'external', 'uri', {url_or_none}, any)): + entries.append(self.url_result(external_uri)) + if playlist := traverse_obj(root, (*embed_path, 'playlist', {url_or_none})): + formats, subtitles = self._extract_m3u8_formats_and_subtitles( + playlist, video_id, 'mp4', m3u8_id='hls', fatal=False) + else: + return entries + + video_cid = traverse_obj( + root, (*embed_path, 'cid', {str}), + (*record_path, *record_subpath, 'video', 'ref', '$link', {str})) + did = traverse_obj(root, ('author', 'did', {str})) + + if did and video_cid: + endpoint = self._get_service_endpoint(did, video_id) + + formats.append({ + 'format_id': 'blob', + 'quality': 1, + 'url': update_url_query( + self._BLOB_URL_TMPL.format(endpoint), {'did': did, 'cid': video_cid}), + **traverse_obj(root, (*embed_path, 'aspectRatio', { + 'width': ('width', {int_or_none}), + 'height': ('height', {int_or_none}), + })), + **traverse_obj(root, (*record_path, *record_subpath, 'video', { + 'filesize': ('size', {int_or_none}), + 'ext': ('mimeType', {mimetype2ext}), + })), + }) + + for sub_data in traverse_obj(root, ( + *record_path, *record_subpath, 'captions', lambda _, v: v['file']['ref']['$link'])): + subtitles.setdefault(sub_data.get('lang') or 'und', []).append({ + 'url': update_url_query( + self._BLOB_URL_TMPL.format(endpoint), {'did': did, 'cid': sub_data['file']['ref']['$link']}), + 'ext': traverse_obj(sub_data, ('file', 'mimeType', {mimetype2ext})), + }) + + entries.append({ + 'id': video_id, + 'formats': formats, + 'subtitles': subtitles, + **traverse_obj(root, { + 'id': ('uri', {url_basename}), + 'thumbnail': (*embed_path, 'thumbnail', {url_or_none}), + 'alt_title': (*embed_path, 'alt', {str}, filter), + 'uploader': ('author', 'displayName', {str}), + 'uploader_id': ('author', 'handle', {str}), + 'uploader_url': ('author', 'handle', {self._build_profile_url}), + 'channel_id': ('author', 'did', {str}), + 'channel_url': ('author', 'did', {self._build_profile_url}), + 'like_count': ('likeCount', {int_or_none}), + 'repost_count': ('repostCount', {int_or_none}), + 'comment_count': ('replyCount', {int_or_none}), + 'timestamp': ('indexedAt', {parse_iso8601}), + 'tags': ('labels', ..., 'val', {str}, all, {orderedSet}), + 'age_limit': ( + 'labels', ..., 'val', {lambda x: 18 if x in ('sexual', 'porn', 'graphic-media') else None}, any), + 'description': (*record_path, 'text', {str}, filter), + 'title': (*record_path, 'text', {lambda x: x.replace('\n', ' ')}, {truncate_string(left=72)}), + }), + }) + return entries diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/bongacams.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/bongacams.py new file mode 100644 index 0000000000000000000000000000000000000000..ab85477de45c094a121ea777319b6f1438d7bfa4 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/bongacams.py @@ -0,0 +1,69 @@ +from .common import InfoExtractor +from ..utils import ( + int_or_none, + try_get, + urlencode_postdata, +) + + +class BongaCamsIE(InfoExtractor): + _VALID_URL = r'https?://(?P(?:[^/]+\.)?bongacams\d*\.(?:com|net))/(?P[^/?&#]+)' + _TESTS = [{ + 'url': 'https://de.bongacams.com/azumi-8', + 'only_matching': True, + }, { + 'url': 'https://cn.bongacams.com/azumi-8', + 'only_matching': True, + }, { + 'url': 'https://de.bongacams.net/claireashton', + 'info_dict': { + 'id': 'claireashton', + 'ext': 'mp4', + 'title': r're:ClaireAshton \d{4}-\d{2}-\d{2} \d{2}:\d{2}', + 'age_limit': 18, + 'uploader_id': 'ClaireAshton', + 'uploader': 'ClaireAshton', + 'like_count': int, + 'is_live': True, + }, + 'params': { + 'skip_download': True, + }, + }] + + def _real_extract(self, url): + mobj = self._match_valid_url(url) + host = mobj.group('host') + channel_id = mobj.group('id') + + amf = self._download_json( + f'https://{host}/tools/amf.php', channel_id, + data=urlencode_postdata(( + ('method', 'getRoomData'), + ('args[]', channel_id), + ('args[]', 'false'), + )), headers={'X-Requested-With': 'XMLHttpRequest'}) + + server_url = amf['localData']['videoServerUrl'] + + uploader_id = try_get( + amf, lambda x: x['performerData']['username'], str) or channel_id + uploader = try_get( + amf, lambda x: x['performerData']['displayName'], str) + like_count = int_or_none(try_get( + amf, lambda x: x['performerData']['loversCount'])) + + formats = self._extract_m3u8_formats( + f'{server_url}/hls/stream_{uploader_id}/playlist.m3u8', + channel_id, 'mp4', m3u8_id='hls', live=True) + + return { + 'id': channel_id, + 'title': uploader or uploader_id, + 'uploader': uploader, + 'uploader_id': uploader_id, + 'like_count': like_count, + 'age_limit': 18, + 'is_live': True, + 'formats': formats, + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/breitbart.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/breitbart.py new file mode 100644 index 0000000000000000000000000000000000000000..fedf4772a97488b1258731a13addc6638352fece --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/breitbart.py @@ -0,0 +1,34 @@ +from .common import InfoExtractor + + +class BreitBartIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?breitbart\.com/videos/v/(?P[^/?#]+)' + _TESTS = [{ + 'url': 'https://www.breitbart.com/videos/v/5cOz1yup/?pl=Ij6NDOji', + 'md5': '0aa6d1d6e183ac5ca09207fe49f17ade', + 'info_dict': { + 'id': '5cOz1yup', + 'ext': 'mp4', + 'title': 'Watch \u2013 Clyburn: Statues in Congress Have to Go Because they Are Honoring Slavery', + 'description': 'md5:bac35eb0256d1cb17f517f54c79404d5', + 'thumbnail': 'https://cdn.jwplayer.com/thumbs/5cOz1yup-1920.jpg', + 'age_limit': 0, + }, + }, { + 'url': 'https://www.breitbart.com/videos/v/eaiZjVOn/', + 'only_matching': True, + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + webpage = self._download_webpage(url, video_id) + + formats = self._extract_m3u8_formats(f'https://cdn.jwplayer.com/manifests/{video_id}.m3u8', video_id, ext='mp4') + return { + 'id': video_id, + 'title': self._generic_title('', webpage), + 'description': self._og_search_description(webpage), + 'thumbnail': self._og_search_thumbnail(webpage), + 'age_limit': self._rta_search(webpage), + 'formats': formats, + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/btvplus.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/btvplus.py new file mode 100644 index 0000000000000000000000000000000000000000..531ace1471424f8c2091a56a3bfc90c785abb551 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/btvplus.py @@ -0,0 +1,73 @@ +from .common import InfoExtractor +from ..utils import ( + bug_reports_message, + clean_html, + get_element_by_class, + js_to_json, + mimetype2ext, + strip_or_none, + url_or_none, + urljoin, +) +from ..utils.traversal import traverse_obj + + +class BTVPlusIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?btvplus\.bg/produkt/(?:predavaniya|seriali|novini)/(?P\d+)' + _TESTS = [{ + 'url': 'https://btvplus.bg/produkt/predavaniya/67271/btv-reporterite/btv-reporterite-12-07-2025-g', + 'info_dict': { + 'ext': 'mp4', + 'id': '67271', + 'title': 'bTV Репортерите - 12.07.2025 г.', + 'thumbnail': 'https://cdn.btv.bg/media/images/940x529/Jul2025/2113606319.jpg', + }, + }, { + 'url': 'https://btvplus.bg/produkt/seriali/66942/sezon-2/plen-sezon-2-epizod-55', + 'info_dict': { + 'ext': 'mp4', + 'id': '66942', + 'title': 'Плен - сезон 2, епизод 55', + 'thumbnail': 'https://cdn.btv.bg/media/images/940x529/Jun2025/2113595104.jpg', + }, + }, { + 'url': 'https://btvplus.bg/produkt/novini/67270/btv-novinite-centralna-emisija-12-07-2025', + 'only_matching': True, + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + webpage = self._download_webpage(url, video_id) + + player_url = self._search_regex( + r'var\s+videoUrl\s*=\s*[\'"]([^\'"]+)[\'"]', + webpage, 'player URL') + + player_config = self._download_json( + urljoin('https://btvplus.bg', player_url), video_id)['config'] + + videojs_data = self._search_json( + r'videojs\(["\'][^"\']+["\'],', player_config, 'videojs data', + video_id, transform_source=js_to_json) + formats = [] + subtitles = {} + for src in traverse_obj(videojs_data, ('sources', lambda _, v: url_or_none(v['src']))): + ext = mimetype2ext(src.get('type')) + if ext == 'm3u8': + fmts, subs = self._extract_m3u8_formats_and_subtitles( + src['src'], video_id, 'mp4', m3u8_id='hls', fatal=False) + formats.extend(fmts) + self._merge_subtitles(subs, target=subtitles) + else: + self.report_warning(f'Unknown format type {ext}{bug_reports_message()}') + + return { + 'id': video_id, + 'formats': formats, + 'subtitles': subtitles, + 'title': ( + strip_or_none(self._og_search_title(webpage, default=None)) + or clean_html(get_element_by_class('product-title', webpage))), + 'thumbnail': self._og_search_thumbnail(webpage, default=None), + 'description': self._og_search_description(webpage, default=None), + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/buzzfeed.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/buzzfeed.py new file mode 100644 index 0000000000000000000000000000000000000000..9847095bcf4d583d6cd7f42056bfe860fb48a7db --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/buzzfeed.py @@ -0,0 +1,95 @@ +import json +import re + +from .common import InfoExtractor +from .facebook import FacebookIE + + +class BuzzFeedIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?buzzfeed\.com/[^?#]*?/(?P[^?#]+)' + _TESTS = [{ + 'url': 'http://www.buzzfeed.com/abagg/this-angry-ram-destroys-a-punching-bag-like-a-boss?utm_term=4ldqpia', + 'info_dict': { + 'id': 'this-angry-ram-destroys-a-punching-bag-like-a-boss', + 'title': 'This Angry Ram Destroys A Punching Bag Like A Boss', + 'description': 'Rambro!', + }, + 'playlist': [{ + 'info_dict': { + 'id': 'aVCR29aE_OQ', + 'ext': 'mp4', + 'title': 'Angry Ram destroys a punching bag..', + 'description': 'md5:c59533190ef23fd4458a5e8c8c872345', + 'upload_date': '20141024', + 'uploader_id': 'Buddhanz1', + 'uploader': 'Angry Ram', + }, + }], + }, { + 'url': 'http://www.buzzfeed.com/sheridanwatson/look-at-this-cute-dog-omg?utm_term=4ldqpia', + 'params': { + 'skip_download': True, # Got enough YouTube download tests + }, + 'info_dict': { + 'id': 'look-at-this-cute-dog-omg', + 'description': 're:Munchkin the Teddy Bear is back ?!', + 'title': 'You Need To Stop What You\'re Doing And Watching This Dog Walk On A Treadmill', + }, + 'playlist': [{ + 'info_dict': { + 'id': 'mVmBL8B-In0', + 'ext': 'mp4', + 'title': 're:Munchkin the Teddy Bear gets her exercise', + 'description': 'md5:28faab95cda6e361bcff06ec12fc21d8', + 'upload_date': '20141124', + 'uploader_id': 'CindysMunchkin', + 'uploader': 're:^Munchkin the', + }, + }], + }, { + 'url': 'http://www.buzzfeed.com/craigsilverman/the-most-adorable-crash-landing-ever#.eq7pX0BAmK', + 'info_dict': { + 'id': 'the-most-adorable-crash-landing-ever', + 'title': 'Watch This Baby Goose Make The Most Adorable Crash Landing', + 'description': 'This gosling knows how to stick a landing.', + }, + 'playlist': [{ + 'md5': '763ca415512f91ca62e4621086900a23', + 'info_dict': { + 'id': '971793786185728', + 'ext': 'mp4', + 'title': 'We set up crash pads so that the goslings on our roof would have a safe landi...', + 'uploader': 'Calgary Outdoor Centre-University of Calgary', + }, + }], + 'add_ie': ['Facebook'], + }] + + def _real_extract(self, url): + playlist_id = self._match_id(url) + webpage = self._download_webpage(url, playlist_id) + + all_buckets = re.findall( + r'(?s)
[^/]+)' + _TESTS = [{ + 'playlist_mincount': 5, + 'url': 'https://camfm.co.uk/shows/soul-mining/', + 'info_dict': { + 'id': 'soul-mining', + 'thumbnail': 'md5:6a873091f92c936f23bdcce80f75e66a', + 'title': 'Soul Mining', + 'description': 'Telling the stories of jazz, funk and soul from all corners of the world.', + }, + }] + + def _real_extract(self, url): + show_id = self._match_id(url) + page = self._download_webpage(url, show_id) + + return { + '_type': 'playlist', + 'id': show_id, + 'entries': [self.url_result(urljoin('https://camfm.co.uk', i), CamFMEpisodeIE) + for i in re.findall(r"javascript:popup\('(/player/[^']+)', 'listen'", page)], + 'thumbnail': urljoin('https://camfm.co.uk', self._search_regex( + r']+class="thumb-expand"[^>]+src="([^"]+)"', page, 'thumbnail', fatal=False)), + 'title': self._html_search_regex('

([^<]+)

', page, 'title', fatal=False), + 'description': clean_html(get_element_by_class('small-12 medium-8 cell', page)), + } + + +class CamFMEpisodeIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?camfm\.co\.uk/player/(?P[^/]+)' + _TESTS = [{ + 'url': 'https://camfm.co.uk/player/43336', + 'skip': 'Episode will expire - don\'t actually know when, but it will go eventually', + 'info_dict': { + 'id': '43336', + 'title': 'AITAA: Am I the Agony Aunt? - 19:00 Tue 16/05/2023', + 'ext': 'mp3', + 'upload_date': '20230516', + 'description': 'md5:f165144f94927c0f1bfa2ee6e6ab7bbf', + 'timestamp': 1684263600, + 'series': 'AITAA: Am I the Agony Aunt?', + 'thumbnail': 'md5:5980a831360d0744c3764551be3d09c1', + 'categories': ['Entertainment'], + }, + }] + + def _real_extract(self, url): + episode_id = self._match_id(url) + page = self._download_webpage(url, episode_id) + audios = self._parse_html5_media_entries('https://audio.camfm.co.uk', page, episode_id) + + caption = get_element_by_class('caption', page) + series = clean_html(re.sub(r'', '', caption)) + + card_section = get_element_by_class('card-section', page) + date = self._html_search_regex('>Aired at ([^<]+)<', card_section, 'air date', fatal=False) + + return { + 'id': episode_id, + 'title': join_nonempty(series, date, delim=' - '), + 'formats': traverse_obj(audios, (..., 'formats', ...)), + 'timestamp': unified_timestamp(date), # XXX: Does not account for UK's daylight savings + 'series': series, + 'description': clean_html(re.sub(r'[^<]+]+/>', '', card_section)), + 'thumbnail': urljoin('https://camfm.co.uk', self._search_regex( + r']+class="cover-art"[^>]+style="[^"]+url\(\'([^\']+)', + page, 'thumbnail', fatal=False)), + 'categories': get_elements_by_class('label', caption), + 'was_live': True, + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/cbs.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/cbs.py new file mode 100644 index 0000000000000000000000000000000000000000..e8255889724a66d0b014250f55549e5ccd588091 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/cbs.py @@ -0,0 +1,280 @@ +from .brightcove import BrightcoveNewIE +from .common import InfoExtractor +from .theplatform import ThePlatformFeedIE +from .youtube import YoutubeIE +from ..utils import ( + ExtractorError, + extract_attributes, + find_xpath_attr, + get_element_html_by_id, + int_or_none, + smuggle_url, + update_url_query, + url_or_none, + xpath_element, + xpath_text, +) + + +class CBSBaseIE(ThePlatformFeedIE): # XXX: Do not subclass from concrete IE + def _parse_smil_subtitles(self, smil, namespace=None, subtitles_lang='en'): + subtitles = {} + for k, ext in [('sMPTE-TTCCURL', 'tt'), ('ClosedCaptionURL', 'ttml'), ('webVTTCaptionURL', 'vtt')]: + cc_e = find_xpath_attr(smil, self._xpath_ns('.//param', namespace), 'name', k) + if cc_e is not None: + cc_url = cc_e.get('value') + if cc_url: + subtitles.setdefault(subtitles_lang, []).append({ + 'ext': ext, + 'url': cc_url, + }) + return subtitles + + def _extract_common_video_info(self, content_id, asset_types, mpx_acc, extra_info): + tp_path = f'dJ5BDC/media/guid/{mpx_acc}/{content_id}' + tp_release_url = f'https://link.theplatform.com/s/{tp_path}' + info = self._extract_theplatform_metadata(tp_path, content_id) + + formats, subtitles = [], {} + last_e = None + for asset_type, query in asset_types.items(): + try: + tp_formats, tp_subtitles = self._extract_theplatform_smil( + update_url_query(tp_release_url, query), content_id, + f'Downloading {asset_type} SMIL data') + except ExtractorError as e: + last_e = e + if asset_type != 'fallback': + continue + query['formats'] = '' # blank query to check if expired + try: + tp_formats, tp_subtitles = self._extract_theplatform_smil( + update_url_query(tp_release_url, query), content_id, + f'Downloading {asset_type} SMIL data, trying again with another format') + except ExtractorError as e: + last_e = e + continue + formats.extend(tp_formats) + subtitles = self._merge_subtitles(subtitles, tp_subtitles) + if last_e and not formats: + self.raise_no_formats(last_e, True, content_id) + + extra_info.update({ + 'id': content_id, + 'formats': formats, + 'subtitles': subtitles, + }) + info.update({k: v for k, v in extra_info.items() if v is not None}) + return info + + def _extract_video_info(self, *args, **kwargs): + # Extract assets + metadata and call _extract_common_video_info + raise NotImplementedError('This method must be implemented by subclasses') + + def _real_extract(self, url): + return self._extract_video_info(self._match_id(url)) + + +class CBSIE(CBSBaseIE): + _WORKING = False + _VALID_URL = r'''(?x) + (?: + cbs:| + https?://(?:www\.)?(?: + cbs\.com/(?:shows|movies)/(?:video|[^/]+/video|[^/]+)/| + colbertlateshow\.com/(?:video|podcasts)/) + )(?P[\w-]+)''' + + # All tests are blocked outside US + _TESTS = [{ + 'url': 'https://www.cbs.com/shows/video/xrUyNLtl9wd8D_RWWAg9NU2F_V6QpB3R/', + 'info_dict': { + 'id': 'xrUyNLtl9wd8D_RWWAg9NU2F_V6QpB3R', + 'ext': 'mp4', + 'title': 'Tough As Nails - Dreams Never Die', + 'description': 'md5:a3535a62531cdd52b0364248a2c1ae33', + 'duration': 2588, + 'timestamp': 1639015200, + 'upload_date': '20211209', + 'uploader': 'CBSI-NEW', + }, + 'params': { + # m3u8 download + 'skip_download': True, + }, + 'skip': 'Subscription required', + }, { + 'url': 'https://www.cbs.com/shows/video/sZH1MGgomIosZgxGJ1l263MFq16oMtW1/', + 'info_dict': { + 'id': 'sZH1MGgomIosZgxGJ1l263MFq16oMtW1', + 'title': 'The Late Show - 3/16/22 (Michael Buble, Rose Matafeo)', + 'timestamp': 1647488100, + 'description': 'md5:d0e6ec23c544b7fa8e39a8e6844d2439', + 'uploader': 'CBSI-NEW', + 'upload_date': '20220317', + }, + 'params': { + 'ignore_no_formats_error': True, + 'skip_download': True, + }, + 'expected_warnings': [ + 'This content expired on', 'No video formats found', 'Requested format is not available'], + 'skip': '404 Not Found', + }, { + 'url': 'http://colbertlateshow.com/video/8GmB0oY0McANFvp2aEffk9jZZZ2YyXxy/the-colbeard/', + 'only_matching': True, + }, { + 'url': 'http://www.colbertlateshow.com/podcasts/dYSwjqPs_X1tvbV_P2FcPWRa_qT6akTC/in-the-bad-room-with-stephen/', + 'only_matching': True, + }] + + def _extract_video_info(self, content_id, site='cbs', mpx_acc=2198311517): + items_data = self._download_xml( + 'https://can.cbs.com/thunder/player/videoPlayerService.php', + content_id, query={'partner': site, 'contentId': content_id}) + video_data = xpath_element(items_data, './/item') + title = xpath_text(video_data, 'videoTitle', 'title') or xpath_text(video_data, 'videotitle', 'title') + + asset_types = {} + has_drm = False + for item in items_data.findall('.//item'): + asset_type = xpath_text(item, 'assetType') + query = { + 'mbr': 'true', + 'assetTypes': asset_type, + } + if not asset_type: + # fallback for content_ids that videoPlayerService doesn't return anything for + asset_type = 'fallback' + query['formats'] = 'M3U+none,MPEG4,M3U+appleHlsEncryption,MP3' + del query['assetTypes'] + if asset_type in asset_types: + continue + elif any(excluded in asset_type for excluded in ('HLS_FPS', 'DASH_CENC', 'OnceURL')): + if 'DASH_CENC' in asset_type: + has_drm = True + continue + if asset_type.startswith('HLS') or 'StreamPack' in asset_type: + query['formats'] = 'MPEG4,M3U' + elif asset_type in ('RTMP', 'WIFI', '3G'): + query['formats'] = 'MPEG4,FLV' + asset_types[asset_type] = query + + if not asset_types and has_drm: + self.report_drm(content_id) + + return self._extract_common_video_info(content_id, asset_types, mpx_acc, extra_info={ + 'title': title, + 'series': xpath_text(video_data, 'seriesTitle'), + 'season_number': int_or_none(xpath_text(video_data, 'seasonNumber')), + 'episode_number': int_or_none(xpath_text(video_data, 'episodeNumber')), + 'duration': int_or_none(xpath_text(video_data, 'videoLength'), 1000), + 'thumbnail': url_or_none(xpath_text(video_data, 'previewImageURL')), + }) + + +class ParamountPressExpressIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?paramountpressexpress\.com(?:/[\w-]+)+/(?Pyt-)?video/?\?watch=(?P[\w-]+)' + _TESTS = [{ + 'url': 'https://www.paramountpressexpress.com/cbs-entertainment/shows/survivor/video/?watch=pnzew7e2hx', + 'md5': '56631dbcadaab980d1fc47cb7b76cba4', + 'info_dict': { + 'id': '6322981580112', + 'ext': 'mp4', + 'title': 'I’m Felicia', + 'description': 'md5:88fad93f8eede1c9c8f390239e4c6290', + 'uploader_id': '6055873637001', + 'upload_date': '20230320', + 'timestamp': 1679334960, + 'duration': 49.557, + 'thumbnail': r're:^https://.+\.jpg', + 'tags': [], + }, + }, { + 'url': 'https://www.paramountpressexpress.com/cbs-entertainment/video/?watch=2s5eh8kppc', + 'md5': 'edcb03e3210b88a3e56c05aa863e0e5b', + 'info_dict': { + 'id': '6323036027112', + 'ext': 'mp4', + 'title': '‘Y&R’ Set Visit: Jerry O’Connell Quizzes Cast on Pre-Love Scene Rituals and More', + 'description': 'md5:b929867a357aac5544b783d834c78383', + 'uploader_id': '6055873637001', + 'upload_date': '20230321', + 'timestamp': 1679430180, + 'duration': 132.032, + 'thumbnail': r're:^https://.+\.jpg', + 'tags': [], + }, + }, { + 'url': 'https://www.paramountpressexpress.com/paramount-plus/yt-video/?watch=OX9wJWOcqck', + 'info_dict': { + 'id': 'OX9wJWOcqck', + 'ext': 'mp4', + 'title': 'Rugrats | Season 2 Official Trailer | Paramount+', + 'description': 'md5:1f7e26f5625a9f0d6564d9ad97a9f7de', + 'uploader': 'Paramount Plus', + 'uploader_id': '@paramountplus', + 'uploader_url': 'http://www.youtube.com/@paramountplus', + 'channel': 'Paramount Plus', + 'channel_id': 'UCrRttZIypNTA1Mrfwo745Sg', + 'channel_url': 'https://www.youtube.com/channel/UCrRttZIypNTA1Mrfwo745Sg', + 'upload_date': '20230316', + 'duration': 88, + 'age_limit': 0, + 'availability': 'public', + 'live_status': 'not_live', + 'playable_in_embed': True, + 'view_count': int, + 'like_count': int, + 'channel_follower_count': int, + 'thumbnail': 'https://i.ytimg.com/vi/OX9wJWOcqck/maxresdefault.jpg', + 'categories': ['Entertainment'], + 'tags': ['Rugrats'], + }, + }, { + 'url': 'https://www.paramountpressexpress.com/showtime/yt-video/?watch=_ljssSoDLkw', + 'info_dict': { + 'id': '_ljssSoDLkw', + 'ext': 'mp4', + 'title': 'Lavell Crawford: THEE Lavell Crawford Comedy Special Official Trailer | SHOWTIME', + 'description': 'md5:39581bcc3fd810209b642609f448af70', + 'uploader': 'SHOWTIME', + 'uploader_id': '@Showtime', + 'uploader_url': 'http://www.youtube.com/@Showtime', + 'channel': 'SHOWTIME', + 'channel_id': 'UCtwMWJr2BFPkuJTnSvCESSQ', + 'channel_url': 'https://www.youtube.com/channel/UCtwMWJr2BFPkuJTnSvCESSQ', + 'upload_date': '20230209', + 'duration': 49, + 'age_limit': 0, + 'availability': 'public', + 'live_status': 'not_live', + 'playable_in_embed': True, + 'view_count': int, + 'like_count': int, + 'comment_count': int, + 'channel_follower_count': int, + 'thumbnail': 'https://i.ytimg.com/vi_webp/_ljssSoDLkw/maxresdefault.webp', + 'categories': ['People & Blogs'], + 'tags': 'count:27', + }, + }] + + def _real_extract(self, url): + display_id, is_youtube = self._match_valid_url(url).group('id', 'yt') + if is_youtube: + return self.url_result(display_id, YoutubeIE) + + webpage = self._download_webpage(url, display_id) + video_id = self._search_regex( + r'\bvideo_id\s*=\s*["\'](\d+)["\']\s*,', webpage, 'Brightcove ID') + token = self._search_regex(r'\btoken\s*=\s*["\']([\w.-]+)["\']', webpage, 'token') + + player = extract_attributes(get_element_html_by_id('vcbrightcoveplayer', webpage) or '') + account_id = player.get('data-account') or '6055873637001' + player_id = player.get('data-player') or 'OtLKgXlO9F' + embed = player.get('data-embed') or 'default' + + return self.url_result(smuggle_url( + f'https://players.brightcove.net/{account_id}/{player_id}_{embed}/index.html?videoId={video_id}', + {'token': token}), BrightcoveNewIE) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/cinemax.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/cinemax.py new file mode 100644 index 0000000000000000000000000000000000000000..66831ef62d232e87853e5a1ffffa559af527e6f8 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/cinemax.py @@ -0,0 +1,25 @@ +from .hbo import HBOBaseIE + + +class CinemaxIE(HBOBaseIE): + _WORKING = False + _VALID_URL = r'https?://(?:www\.)?cinemax\.com/(?P[^/]+/video/[0-9a-z-]+-(?P\d+))' + _TESTS = [{ + 'url': 'https://www.cinemax.com/warrior/video/s1-ep-1-recap-20126903', + 'md5': '82e0734bba8aa7ef526c9dd00cf35a05', + 'info_dict': { + 'id': '20126903', + 'ext': 'mp4', + 'title': 'S1 Ep 1: Recap', + }, + 'expected_warnings': ['Unknown MIME type application/mp4 in DASH manifest'], + }, { + 'url': 'https://www.cinemax.com/warrior/video/s1-ep-1-recap-20126903.embed', + 'only_matching': True, + }] + + def _real_extract(self, url): + path, video_id = self._match_valid_url(url).groups() + info = self._extract_info(f'https://www.cinemax.com/{path}.xml', video_id) + info['id'] = video_id + return info diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/clipchamp.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/clipchamp.py new file mode 100644 index 0000000000000000000000000000000000000000..a8bdf7e5090f7161967d4edb204076ee760afbcb --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/clipchamp.py @@ -0,0 +1,61 @@ +from .common import InfoExtractor +from ..utils import ( + ExtractorError, + traverse_obj, + unified_timestamp, + url_or_none, +) + + +class ClipchampIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?clipchamp\.com/watch/(?P[\w-]+)' + _TESTS = [{ + 'url': 'https://clipchamp.com/watch/gRXZ4ZhdDaU', + 'info_dict': { + 'id': 'gRXZ4ZhdDaU', + 'ext': 'mp4', + 'title': 'Untitled video', + 'uploader': 'Alexander Schwartz', + 'timestamp': 1680805580, + 'upload_date': '20230406', + 'thumbnail': r're:^https?://.+\.jpg', + }, + 'params': {'skip_download': 'm3u8'}, + }] + + _STREAM_URL_TMPL = 'https://%s.cloudflarestream.com/%s/manifest/video.%s' + _STREAM_URL_QUERY = {'parentOrigin': 'https://clipchamp.com'} + + def _real_extract(self, url): + video_id = self._match_id(url) + webpage = self._download_webpage(url, video_id) + data = self._search_nextjs_data(webpage, video_id)['props']['pageProps']['video'] + + storage_location = data.get('storage_location') + if storage_location != 'cf_stream': + raise ExtractorError(f'Unsupported clip storage location "{storage_location}"') + + path = data['download_url'] + iframe = self._download_webpage( + f'https://iframe.cloudflarestream.com/{path}', video_id, 'Downloading player iframe') + subdomain = self._search_regex( + r'\bcustomer-domain-prefix=["\']([\w-]+)["\']', iframe, + 'subdomain', fatal=False) or 'customer-2ut9yn3y6fta1yxe' + + formats = self._extract_mpd_formats( + self._STREAM_URL_TMPL % (subdomain, path, 'mpd'), video_id, + query=self._STREAM_URL_QUERY, fatal=False, mpd_id='dash') + formats.extend(self._extract_m3u8_formats( + self._STREAM_URL_TMPL % (subdomain, path, 'm3u8'), video_id, 'mp4', + query=self._STREAM_URL_QUERY, fatal=False, m3u8_id='hls')) + + return { + 'id': video_id, + 'formats': formats, + 'uploader': ' '.join(traverse_obj(data, ('creator', ('first_name', 'last_name'), {str}))) or None, + **traverse_obj(data, { + 'title': ('project', 'project_name', {str}), + 'timestamp': ('created_at', {unified_timestamp}), + 'thumbnail': ('thumbnail_url', {url_or_none}), + }), + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/corus.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/corus.py new file mode 100644 index 0000000000000000000000000000000000000000..4af2d186de3151792bd2d6a161353d98776a9fce --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/corus.py @@ -0,0 +1,154 @@ +from .theplatform import ThePlatformFeedIE +from ..utils import ( + ExtractorError, + dict_get, + float_or_none, + int_or_none, +) + + +class CorusIE(ThePlatformFeedIE): # XXX: Do not subclass from concrete IE + _VALID_URL = r'''(?x) + https?:// + (?:www\.)? + (?P + (?: + globaltv| + etcanada| + seriesplus| + wnetwork| + ytv + )\.com| + (?: + hgtv| + foodnetwork| + slice| + history| + showcase| + bigbrothercanada| + abcspark| + disney(?:channel|lachaine) + )\.ca + ) + /(?:[^/]+/)* + (?: + video\.html\?.*?\bv=| + videos?/(?:[^/]+/)*(?:[a-z0-9-]+-)? + ) + (?P + [\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}| + (?:[A-Z]{4})?\d{12,20} + ) + ''' + _TESTS = [{ + 'url': 'https://www.hgtv.ca/video/bryan-inc/movie-night-popcorn-with-bryan/870923331648/', + 'info_dict': { + 'id': '870923331648', + 'ext': 'mp4', + 'title': 'Movie Night Popcorn with Bryan', + 'description': 'Bryan whips up homemade popcorn, the old fashion way for Jojo and Lincoln.', + 'upload_date': '20170206', + 'timestamp': 1486392197, + }, + 'params': { + 'skip_download': True, + }, + 'expected_warnings': ['Failed to parse JSON'], + # FIXME: yt-dlp wrongly raises for geo restriction + }, { + 'url': 'http://www.foodnetwork.ca/shows/chopped/video/episode/chocolate-obsession/video.html?v=872683587753', + 'only_matching': True, + }, { + 'url': 'http://etcanada.com/video/873675331955/meet-the-survivor-game-changers-castaways-part-2/', + 'only_matching': True, + }, { + 'url': 'http://www.history.ca/the-world-without-canada/video/full-episodes/natural-resources/video.html?v=955054659646#video', + 'only_matching': True, + }, { + 'url': 'http://www.showcase.ca/eyewitness/video/eyewitness++106/video.html?v=955070531919&p=1&s=da#video', + 'only_matching': True, + }, { + 'url': 'http://www.bigbrothercanada.ca/video/1457812035894/', + 'only_matching': True, + }, { + 'url': 'https://www.bigbrothercanada.ca/video/big-brother-canada-704/1457812035894/', + 'only_matching': True, + }, { + 'url': 'https://www.seriesplus.com/emissions/dre-mary-mort-sur-ordonnance/videos/deux-coeurs-battant/SERP0055626330000200/', + 'only_matching': True, + }, { + 'url': 'https://www.disneychannel.ca/shows/gabby-duran-the-unsittables/video/crybaby-duran-clip/2f557eec-0588-11ea-ae2b-e2c6776b770e/', + 'only_matching': True, + }] + _GEO_BYPASS = False + _SITE_MAP = { + 'globaltv': 'series', + 'etcanada': 'series', + 'foodnetwork': 'food', + 'bigbrothercanada': 'series', + 'disneychannel': 'disneyen', + 'disneylachaine': 'disneyfr', + } + + def _real_extract(self, url): + domain, video_id = self._match_valid_url(url).groups() + site = domain.split('.')[0] + path = self._SITE_MAP.get(site, site) + if path != 'series': + path = 'migration/' + path + video = self._download_json( + f'https://globalcontent.corusappservices.com/templates/{path}/playlist/', + video_id, query={'byId': video_id}, + headers={'Accept': 'application/json'})[0] + title = video['title'] + + formats = [] + for source in video.get('sources', []): + smil_url = source.get('file') + if not smil_url: + continue + source_type = source.get('type') + note = 'Downloading{} smil file'.format(' ' + source_type if source_type else '') + resp = self._download_webpage( + smil_url, video_id, note, fatal=False, + headers=self.geo_verification_headers()) + if not resp: + continue + error = self._parse_json(resp, video_id, fatal=False) + if error: + if error.get('exception') == 'GeoLocationBlocked': + self.raise_geo_restricted(countries=['CA']) + raise ExtractorError(error['description']) + smil = self._parse_xml(resp, video_id, fatal=False) + if smil is None: + continue + namespace = self._parse_smil_namespace(smil) + formats.extend(self._parse_smil_formats( + smil, smil_url, video_id, namespace)) + if not formats and video.get('drm'): + self.report_drm(video_id) + + subtitles = {} + for track in video.get('tracks', []): + track_url = track.get('file') + if not track_url: + continue + lang = 'fr' if site in ('disneylachaine', 'seriesplus') else 'en' + subtitles.setdefault(lang, []).append({'url': track_url}) + + metadata = video.get('metadata') or {} + get_number = lambda x: int_or_none(video.get('pl1$' + x) or metadata.get(x + 'Number')) + + return { + 'id': video_id, + 'title': title, + 'formats': formats, + 'thumbnail': dict_get(video, ('defaultThumbnailUrl', 'thumbnail', 'image')), + 'description': video.get('description'), + 'timestamp': int_or_none(video.get('availableDate'), 1000), + 'subtitles': subtitles, + 'duration': float_or_none(metadata.get('duration')), + 'series': dict_get(video, ('show', 'pl1$show')), + 'season_number': get_number('season'), + 'episode_number': get_number('episode'), + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/curiositystream.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/curiositystream.py new file mode 100644 index 0000000000000000000000000000000000000000..f5a2c3c311c376ba1b5466d00266f199465d8dfb --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/curiositystream.py @@ -0,0 +1,202 @@ +import re +import urllib.parse + +from .common import InfoExtractor +from ..utils import ExtractorError, int_or_none, urlencode_postdata + + +class CuriosityStreamBaseIE(InfoExtractor): + _NETRC_MACHINE = 'curiositystream' + _auth_token = None + + def _handle_errors(self, result): + error = result.get('error', {}).get('message') + if error: + if isinstance(error, dict): + error = ', '.join(error.values()) + raise ExtractorError( + f'{self.IE_NAME} said: {error}', expected=True) + + def _call_api(self, path, video_id, query=None): + headers = {} + if not self._auth_token: + auth_cookie = self._get_cookies('https://curiositystream.com').get('auth_token') + if auth_cookie: + self.write_debug('Obtained auth_token cookie') + self._auth_token = urllib.parse.unquote(auth_cookie.value) + if self._auth_token: + headers['X-Auth-Token'] = self._auth_token + result = self._download_json( + self._API_BASE_URL + path, video_id, headers=headers, query=query) + self._handle_errors(result) + return result['data'] + + def _perform_login(self, username, password): + result = self._download_json( + 'https://api.curiositystream.com/v1/login', None, + note='Logging in', data=urlencode_postdata({ + 'email': username, + 'password': password, + })) + self._handle_errors(result) + CuriosityStreamBaseIE._auth_token = result['message']['auth_token'] + + +class CuriosityStreamIE(CuriosityStreamBaseIE): + IE_NAME = 'curiositystream' + _VALID_URL = r'https?://(?:app\.)?curiositystream\.com/video/(?P\d+)' + _TESTS = [{ + 'url': 'http://app.curiositystream.com/video/2', + 'info_dict': { + 'id': '2', + 'ext': 'mp4', + 'title': 'How Did You Develop The Internet?', + 'description': 'Vint Cerf, Google\'s Chief Internet Evangelist, describes how he and Bob Kahn created the internet.', + 'channel': 'Curiosity Stream', + 'categories': ['Technology', 'Interview'], + 'average_rating': float, + 'series_id': '2', + 'thumbnail': r're:https://img.curiositystream.com/.+\.jpg', + 'tags': [], + 'duration': 158, + }, + 'params': { + # m3u8 download + 'skip_download': True, + }, + }] + + _API_BASE_URL = 'https://api.curiositystream.com/v1/media/' + + def _real_extract(self, url): + video_id = self._match_id(url) + + formats = [] + for encoding_format in ('m3u8', 'mpd'): + media = self._call_api(video_id, video_id, query={ + 'encodingsNew': 'true', + 'encodingsFormat': encoding_format, + }) + for encoding in media.get('encodings', []): + playlist_url = encoding.get('master_playlist_url') + if encoding_format == 'm3u8': + # use `m3u8` entry_protocol until EXT-X-MAP is properly supported by `m3u8_native` entry_protocol + formats.extend(self._extract_m3u8_formats( + playlist_url, video_id, 'mp4', + m3u8_id='hls', fatal=False)) + elif encoding_format == 'mpd': + formats.extend(self._extract_mpd_formats( + playlist_url, video_id, mpd_id='dash', fatal=False)) + encoding_url = encoding.get('url') + file_url = encoding.get('file_url') + if not encoding_url and not file_url: + continue + f = { + 'width': int_or_none(encoding.get('width')), + 'height': int_or_none(encoding.get('height')), + 'vbr': int_or_none(encoding.get('video_bitrate')), + 'abr': int_or_none(encoding.get('audio_bitrate')), + 'filesize': int_or_none(encoding.get('size_in_bytes')), + 'vcodec': encoding.get('video_codec'), + 'acodec': encoding.get('audio_codec'), + 'container': encoding.get('container_type'), + } + for f_url in (encoding_url, file_url): + if not f_url: + continue + fmt = f.copy() + rtmp = re.search(r'^(?Prtmpe?://(?P[^/]+)/(?P.+))/(?Pmp[34]:.+)$', f_url) + if rtmp: + fmt.update({ + 'url': rtmp.group('url'), + 'play_path': rtmp.group('playpath'), + 'app': rtmp.group('app'), + 'ext': 'flv', + 'format_id': 'rtmp', + }) + else: + fmt.update({ + 'url': f_url, + 'format_id': 'http', + }) + formats.append(fmt) + + title = media['title'] + + subtitles = {} + for closed_caption in media.get('closed_captions', []): + sub_url = closed_caption.get('file') + if not sub_url: + continue + lang = closed_caption.get('code') or closed_caption.get('language') or 'en' + subtitles.setdefault(lang, []).append({ + 'url': sub_url, + }) + + return { + 'id': video_id, + 'formats': formats, + 'title': title, + 'description': media.get('description'), + 'thumbnail': media.get('image_large') or media.get('image_medium') or media.get('image_small'), + 'duration': int_or_none(media.get('duration')), + 'tags': media.get('tags'), + 'subtitles': subtitles, + 'channel': media.get('producer'), + 'categories': [media.get('primary_category'), media.get('type')], + 'average_rating': media.get('rating_percentage'), + 'series_id': str(media.get('collection_id') or '') or None, + } + + +class CuriosityStreamCollectionBaseIE(CuriosityStreamBaseIE): + + def _real_extract(self, url): + collection_id = self._match_id(url) + collection = self._call_api(collection_id, collection_id) + entries = [] + for media in collection.get('media', []): + media_id = str(media.get('id')) + media_type, ie = ('series', CuriosityStreamSeriesIE) if media.get('is_collection') else ('video', CuriosityStreamIE) + entries.append(self.url_result( + f'https://curiositystream.com/{media_type}/{media_id}', + ie=ie.ie_key(), video_id=media_id)) + return self.playlist_result( + entries, collection_id, + collection.get('title'), collection.get('description')) + + +class CuriosityStreamCollectionsIE(CuriosityStreamCollectionBaseIE): + IE_NAME = 'curiositystream:collections' + _VALID_URL = r'https?://(?:app\.)?curiositystream\.com/collections/(?P\d+)' + _API_BASE_URL = 'https://api.curiositystream.com/v2/collections/' + _TESTS = [{ + 'url': 'https://curiositystream.com/collections/86', + 'info_dict': { + 'id': '86', + 'title': 'Staff Picks', + 'description': 'Wondering where to start? Here are a few of our favorite series and films... from our couch to yours.', + }, + 'playlist_mincount': 7, + }, { + 'url': 'https://curiositystream.com/collections/36', + 'only_matching': True, + }] + + +class CuriosityStreamSeriesIE(CuriosityStreamCollectionBaseIE): + IE_NAME = 'curiositystream:series' + _VALID_URL = r'https?://(?:app\.)?curiositystream\.com/(?:series|collection)/(?P\d+)' + _API_BASE_URL = 'https://api.curiositystream.com/v2/series/' + _TESTS = [{ + 'url': 'https://curiositystream.com/series/2', + 'info_dict': { + 'id': '2', + 'title': 'Curious Minds: The Internet', + 'description': 'How is the internet shaping our lives in the 21st Century?', + }, + 'playlist_mincount': 16, + }, { + 'url': 'https://curiositystream.com/collection/2', + 'only_matching': True, + }] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/damtomo.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/damtomo.py new file mode 100644 index 0000000000000000000000000000000000000000..9ac0b6f2f48f4965edbbca003a3631af46f45be1 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/damtomo.py @@ -0,0 +1,107 @@ +import re + +from .common import InfoExtractor +from ..utils import ExtractorError, clean_html, int_or_none, try_get, unified_strdate + + +class DamtomoBaseIE(InfoExtractor): + def _real_extract(self, url): + video_id = self._match_id(url) + webpage, handle = self._download_webpage_handle(self._WEBPAGE_URL_TMPL % video_id, video_id, encoding='sjis') + + if handle.url == 'https://www.clubdam.com/sorry/': + raise ExtractorError('You are rate-limited. Try again later.', expected=True) + if '

予期せぬエラーが発生しました。

' in webpage: + raise ExtractorError('There is an error on server-side. Try again later.', expected=True) + + description = self._search_regex(r'(?m)
\s*

\s*([^<]*?)\s*

', webpage, 'description', default=None) + uploader_id = self._search_regex(r'(?P.+?)', webpage)} + + # since videos do not have title, give the name of song instead + data_dict['user_name'] = re.sub(r'\s*さん\s*$', '', data_dict['user_name']) + title = data_dict.get('song_title') + + stream_tree = self._download_xml( + self._DKML_XML_URL % video_id, video_id, note='Requesting stream information', encoding='sjis', + # doing this has no problem since there is no character outside ASCII, + # and never likely to happen in the future + transform_source=lambda x: re.sub(r'\s*encoding="[^"]+?"', '', x)) + m3u8_url = try_get(stream_tree, lambda x: x.find( + './/d:streamingUrl', {'d': self._DKML_XML_NS}).text.strip(), str) + if not m3u8_url: + raise ExtractorError('Failed to obtain m3u8 URL') + formats = self._extract_m3u8_formats(m3u8_url, video_id, ext='mp4') + + return { + 'id': video_id, + 'title': title, + 'uploader_id': uploader_id, + 'description': description, + 'uploader': data_dict.get('user_name'), + 'upload_date': unified_strdate(self._search_regex(r'(\d{4}/\d{2}/\d{2})', data_dict.get('date'), 'upload_date', default=None)), + 'view_count': int_or_none(self._search_regex(r'(\d+)', data_dict['audience'], 'view_count', default=None)), + 'like_count': int_or_none(self._search_regex(r'(\d+)', data_dict['nice'], 'like_count', default=None)), + 'track': title, + 'artist': data_dict.get('song_artist'), + 'formats': formats, + } + + +class DamtomoVideoIE(DamtomoBaseIE): + IE_NAME = 'damtomo:video' + _VALID_URL = r'https?://(?:www\.)?clubdam\.com/app/damtomo/(?:SP/)?karaokeMovie/StreamingDkm\.do\?karaokeMovieId=(?P\d+)' + _WEBPAGE_URL_TMPL = 'https://www.clubdam.com/app/damtomo/karaokeMovie/StreamingDkm.do?karaokeMovieId=%s' + _DKML_XML_URL = 'https://www.clubdam.com/app/damtomo/karaokeMovie/GetStreamingDkmUrlXML.do?movieSelectFlg=2&karaokeMovieId=%s' + _DKML_XML_NS = 'https://www.clubdam.com/app/damtomo/karaokeMovie/GetStreamingDkmUrlXML' + _TESTS = [{ + 'url': 'https://www.clubdam.com/app/damtomo/karaokeMovie/StreamingDkm.do?karaokeMovieId=2414316', + 'info_dict': { + 'id': '2414316', + 'title': 'Get Wild', + 'uploader': 'Kドロン', + 'uploader_id': 'ODk5NTQwMzQ', + 'track': 'Get Wild', + 'artist': 'TM NETWORK(TMN)', + 'upload_date': '20201226', + }, + }] + + +class DamtomoRecordIE(DamtomoBaseIE): + IE_NAME = 'damtomo:record' + _VALID_URL = r'https?://(?:www\.)?clubdam\.com/app/damtomo/(?:SP/)?karaokePost/StreamingKrk\.do\?karaokeContributeId=(?P\d+)' + _WEBPAGE_URL_TMPL = 'https://www.clubdam.com/app/damtomo/karaokePost/StreamingKrk.do?karaokeContributeId=%s' + _DKML_XML_URL = 'https://www.clubdam.com/app/damtomo/karaokePost/GetStreamingKrkUrlXML.do?karaokeContributeId=%s' + _DKML_XML_NS = 'https://www.clubdam.com/app/damtomo/karaokePost/GetStreamingKrkUrlXML' + _TESTS = [{ + 'url': 'https://www.clubdam.com/app/damtomo/karaokePost/StreamingKrk.do?karaokeContributeId=27376862', + 'info_dict': { + 'id': '27376862', + 'title': 'イカSUMMER [良音]', + 'uploader': 'NANA', + 'uploader_id': 'MzAyMDExNTY', + 'upload_date': '20210721', + 'view_count': 4, + 'like_count': 1, + 'track': 'イカSUMMER [良音]', + 'artist': 'ORANGE RANGE', + }, + }, { + 'url': 'https://www.clubdam.com/app/damtomo/karaokePost/StreamingKrk.do?karaokeContributeId=27489418', + 'info_dict': { + 'id': '27489418', + 'title': '心みだれて〜say it with flowers〜(生音)', + 'uploader_id': 'NjI1MjI2MjU', + 'description': 'やっぱりキーを下げて正解だった感じ。リベンジ成功ということで。', + 'uploader': '箱の「中の人」', + 'upload_date': '20210815', + 'view_count': 5, + 'like_count': 3, + 'track': '心みだれて〜say it with flowers〜(生音)', + 'artist': '小林明子', + }, + }] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/detik.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/detik.py new file mode 100644 index 0000000000000000000000000000000000000000..50977591942d2eb24f2626b47f2f3d01f96f936f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/detik.py @@ -0,0 +1,159 @@ +from .common import InfoExtractor +from ..utils import int_or_none, merge_dicts, try_call, url_basename + + +class DetikEmbedIE(InfoExtractor): + _VALID_URL = False + _WEBPAGE_TESTS = [{ + # cnn embed + 'url': 'https://www.cnnindonesia.com/embed/video/846189', + 'info_dict': { + 'id': '846189', + 'ext': 'mp4', + 'description': 'md5:ece7b003b3ee7d81c6a5cfede7d5397d', + 'thumbnail': r're:https?://akcdn\.detik\.net\.id/visual/2022/09/11/thumbnail-video-1_169.jpeg', + 'title': 'Video CNN Indonesia - VIDEO: Momen Charles Disambut Meriah usai Dilantik jadi Raja Inggris', + 'age_limit': 0, + 'tags': ['raja charles', ' raja charles iii', ' ratu elizabeth', ' ratu elizabeth meninggal dunia', ' raja inggris', ' inggris'], + 'release_timestamp': 1662869995, + 'release_date': '20220911', + 'uploader': 'REUTERS', + }, + }, { + # 20.detik + 'url': 'https://20.detik.com/otobuzz/20220704-220704093/mulai-rp-10-jutaan-ini-skema-kredit-mitsubishi-pajero-sport', + 'info_dict': { + 'display_id': 'mulai-rp-10-jutaan-ini-skema-kredit-mitsubishi-pajero-sport', + 'id': '220704093', + 'ext': 'mp4', + 'description': 'md5:9b2257341b6f375cdcf90106146d5ffb', + 'thumbnail': r're:https?://cdnv\.detik\.com/videoservice/AdminTV/2022/07/04/5d6187e402ec4a91877755a5886ff5b6-20220704161859-0s.jpg', + 'title': 'Mulai Rp 10 Jutaan! Ini Skema Kredit Mitsubishi Pajero Sport', + 'timestamp': 1656951521, + 'upload_date': '20220704', + 'duration': 83.0, + 'tags': ['cicilan mobil', 'mitsubishi pajero sport', 'mitsubishi', 'pajero sport'], + 'release_timestamp': 1656926321, + 'release_date': '20220704', + 'age_limit': 0, + 'uploader': 'Ridwan Arifin ', # TODO: strip trailling whitespace at uploader + }, + }, { + # pasangmata.detik + 'url': 'https://pasangmata.detik.com/contribution/366649', + 'info_dict': { + 'id': '366649', + 'ext': 'mp4', + 'title': 'Saling Dorong Aparat dan Pendemo di Aksi Tolak Kenaikan BBM', + 'description': 'md5:7a6580876c8381c454679e028620bea7', + 'age_limit': 0, + 'tags': 'count:17', + 'thumbnail': 'https://akcdn.detik.net.id/community/data/media/thumbs-pasangmata/2022/09/08/366649-16626229351533009620.mp4-03.jpg', + }, + }, { + # insertlive embed + 'url': 'https://www.insertlive.com/embed/video/290482', + 'info_dict': { + 'id': '290482', + 'ext': 'mp4', + 'release_timestamp': 1663063704, + 'thumbnail': 'https://akcdn.detik.net.id/visual/2022/09/13/leonardo-dicaprio_169.png?w=600&q=90', + 'age_limit': 0, + 'description': 'Aktor Leonardo DiCaprio memang baru saja putus dari kekasihnya yang bernama Camilla Morrone.', + 'release_date': '20220913', + 'title': 'Diincar Leonardo DiCaprio, Gigi Hadid Ngaku Tertarik Tapi Belum Cinta', + 'tags': ['leonardo dicaprio', ' gigi hadid', ' hollywood'], + 'uploader': '!nsertlive', + }, + }, { + # beautynesia embed + 'url': 'https://www.beautynesia.id/embed/video/261636', + 'info_dict': { + 'id': '261636', + 'ext': 'mp4', + 'age_limit': 0, + 'release_timestamp': 1662375600, + 'description': 'Menurut ramalan astrologi, tiga zodiak ini bakal hoki sepanjang September 2022.', + 'title': '3 Zodiak Paling Beruntung Selama September 2022', + 'release_date': '20220905', + 'tags': ['zodiac update', ' zodiak', ' ramalan bintang', ' zodiak beruntung 2022', ' zodiak hoki september 2022', ' zodiak beruntung september 2022'], + 'thumbnail': 'https://akcdn.detik.net.id/visual/2022/09/05/3-zodiak-paling-beruntung-selama-september-2022_169.jpeg?w=600&q=90', + 'uploader': 'amh', + }, + }, { + # cnbcindonesia embed + 'url': 'https://www.cnbcindonesia.com/embed/video/371839', + 'info_dict': { + 'id': '371839', + 'ext': 'mp4', + 'title': 'Puluhan Pejabat Rusia Tuntut Putin Mundur', + 'tags': ['putin'], + 'age_limit': 0, + 'thumbnail': 'https://awsimages.detik.net.id/visual/2022/09/13/cnbc-indonesia-tv-3_169.png?w=600&q=80', + 'description': 'md5:8b9111e37555fcd95fe549a9b4ae6fdc', + }, + }, { + # detik shortlink (we can get it from https://dtk.id/?) + 'url': 'https://dtk.id/NkISKr', + 'info_dict': { + 'id': '220914049', + 'ext': 'mp4', + 'release_timestamp': 1663114488, + 'uploader': 'Tim 20Detik', + 'title': 'Pakar Bicara soal Tim Khusus Jokowi dan Mereka yang Pro ke Bjorka', + 'age_limit': 0, + 'thumbnail': 'https://cdnv.detik.com/videoservice/AdminTV/2022/09/14/f15cae71d7b640c58e75b254ecbb1ce1-20220914071613-0s.jpg?w=400&q=80', + 'display_id': 'pakar-bicara-soal-tim-khusus-jokowi-dan-mereka-yang-pro-ke-bjorka', + 'upload_date': '20220914', + 'release_date': '20220914', + 'description': 'md5:5eb03225f7ee40207dd3a1e18a73f1ff', + 'timestamp': 1663139688, + 'duration': 213.0, + 'tags': ['hacker bjorka', 'bjorka', 'hacker bjorka bocorkan data rahasia presiden jokowi', 'jokowi'], + }, + }] + + def _extract_from_webpage(self, url, webpage): + player_type, video_data = self._search_regex( + r']+src="https?://(aws)?cdn\.detik\.net\.id/(?Pflowplayer|detikVideo)[^>]+>\s*(?P{[^}]+})', + webpage, 'playerjs', group=('type', 'video_data'), default=(None, '')) + if not player_type: + return + + display_id, extra_info_dict = url_basename(url), {} + + if player_type == 'flowplayer': + video_json_data = self._parse_json(video_data.replace('\'', '"'), display_id) + video_url = video_json_data['videoUrl'] + + extra_info_dict = { + 'id': self._search_regex(r'identifier\s*:\s*\'([^\']+)', webpage, 'identifier'), + 'thumbnail': video_json_data.get('imageUrl'), + } + + elif player_type == 'detikVideo': + video_url = self._search_regex( + r'videoUrl\s*:\s*[\'"]?([^"\']+)', video_data, 'videoUrl') + extra_info_dict = { + 'id': self._html_search_meta(['video_id', 'dtk:video_id'], webpage), + 'thumbnail': self._search_regex(r'imageUrl\s*:\s*[\'"]?([^"\']+)', video_data, 'videoUrl'), + 'duration': int_or_none(self._html_search_meta('duration', webpage, fatal=False, default=None)), + 'release_timestamp': int_or_none(self._html_search_meta('dtk:publishdateunix', webpage, fatal=False, default=None), 1000), + 'timestamp': int_or_none(self._html_search_meta('dtk:createdateunix', webpage, fatal=False, default=None), 1000), + 'uploader': self._search_regex( + r'([^-]+)', self._html_search_meta('dtk:author', webpage, default='').strip(), 'uploader', + default=None), + } + + formats, subtitles = self._extract_m3u8_formats_and_subtitles(video_url, display_id) + + json_ld_data = self._search_json_ld(webpage, display_id, default={}) + yield merge_dicts(json_ld_data, extra_info_dict, { + 'display_id': display_id, + 'title': self._html_search_meta(['og:title', 'originalTitle'], webpage) or self._html_extract_title(webpage), + 'description': self._html_search_meta(['og:description', 'twitter:description', 'description'], webpage), + 'formats': formats, + 'subtitles': subtitles, + 'tags': try_call(lambda: self._html_search_meta( + ['keywords', 'keyword', 'dtk:keywords'], webpage).split(',')), + }) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/dplay.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/dplay.py new file mode 100644 index 0000000000000000000000000000000000000000..798c3f0f5edd2fd0c0151bd88b505b0305c8ca5b --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/dplay.py @@ -0,0 +1,1306 @@ +import json +import uuid + +from .common import InfoExtractor +from ..networking.exceptions import HTTPError +from ..utils import ( + ExtractorError, + determine_ext, + float_or_none, + int_or_none, + remove_start, + strip_or_none, + try_get, + unified_timestamp, +) +from ..utils.traversal import traverse_obj + + +class DPlayBaseIE(InfoExtractor): + _PATH_REGEX = r'/(?P[^/]+/[^/?#]+)' + _auth_token_cache = {} + + def _get_auth(self, disco_base, display_id, realm, needs_device_id=True): + key = (disco_base, realm) + st = self._get_cookies(disco_base).get('st') + token = (st and st.value) or self._auth_token_cache.get(key) + + if not token: + query = {'realm': realm} + if needs_device_id: + query['deviceId'] = uuid.uuid4().hex + token = self._download_json( + disco_base + 'token', display_id, 'Downloading token', + query=query)['data']['attributes']['token'] + + # Save cache only if cookies are not being set + if not self._get_cookies(disco_base).get('st'): + self._auth_token_cache[key] = token + + return f'Bearer {token}' + + def _process_errors(self, e, geo_countries): + info = self._parse_json(e.cause.response.read().decode('utf-8'), None) + error = info['errors'][0] + error_code = error.get('code') + if error_code == 'access.denied.geoblocked': + self.raise_geo_restricted(countries=geo_countries) + elif error_code in ('access.denied.missingpackage', 'invalid.token'): + raise ExtractorError( + 'This video is only available for registered users. You may want to use --cookies.', expected=True) + raise ExtractorError(info['errors'][0]['detail'], expected=True) + + def _update_disco_api_headers(self, headers, disco_base, display_id, realm): + headers['Authorization'] = self._get_auth(disco_base, display_id, realm, False) + + def _download_video_playback_info(self, disco_base, video_id, headers): + streaming = self._download_json( + disco_base + 'playback/videoPlaybackInfo/' + video_id, + video_id, headers=headers)['data']['attributes']['streaming'] + streaming_list = [] + for format_id, format_dict in streaming.items(): + streaming_list.append({ + 'type': format_id, + 'url': format_dict.get('url'), + }) + return streaming_list + + def _get_disco_api_info(self, url, display_id, disco_host, realm, country, domain=''): + country = self.get_param('geo_bypass_country') or country + geo_countries = [country.upper()] + self._initialize_geo_bypass({ + 'countries': geo_countries, + }) + disco_base = f'https://{disco_host}/' + headers = { + 'Referer': url, + } + self._update_disco_api_headers(headers, disco_base, display_id, realm) + try: + video = self._download_json( + disco_base + 'content/videos/' + display_id, display_id, + headers=headers, query={ + 'fields[channel]': 'name', + 'fields[image]': 'height,src,width', + 'fields[show]': 'name', + 'fields[tag]': 'name', + 'fields[video]': 'description,episodeNumber,name,publishStart,seasonNumber,videoDuration', + 'include': 'images,primaryChannel,show,tags', + }) + except ExtractorError as e: + if isinstance(e.cause, HTTPError) and e.cause.status == 400: + self._process_errors(e, geo_countries) + raise + video_id = video['data']['id'] + info = video['data']['attributes'] + title = info['name'].strip() + formats = [] + subtitles = {} + try: + streaming = self._download_video_playback_info( + disco_base, video_id, headers) + except ExtractorError as e: + if isinstance(e.cause, HTTPError) and e.cause.status == 403: + self._process_errors(e, geo_countries) + raise + for format_dict in streaming: + if not isinstance(format_dict, dict): + continue + format_url = format_dict.get('url') + if not format_url: + continue + format_id = format_dict.get('type') + ext = determine_ext(format_url) + if format_id == 'dash' or ext == 'mpd': + dash_fmts, dash_subs = self._extract_mpd_formats_and_subtitles( + format_url, display_id, mpd_id='dash', fatal=False) + formats.extend(dash_fmts) + subtitles = self._merge_subtitles(subtitles, dash_subs) + elif format_id == 'hls' or ext == 'm3u8': + m3u8_fmts, m3u8_subs = self._extract_m3u8_formats_and_subtitles( + format_url, display_id, 'mp4', + entry_protocol='m3u8_native', m3u8_id='hls', + fatal=False) + formats.extend(m3u8_fmts) + subtitles = self._merge_subtitles(subtitles, m3u8_subs) + else: + formats.append({ + 'url': format_url, + 'format_id': format_id, + }) + + creator = series = None + tags = [] + thumbnails = [] + included = video.get('included') or [] + if isinstance(included, list): + for e in included: + attributes = e.get('attributes') + if not attributes: + continue + e_type = e.get('type') + if e_type == 'channel': + creator = attributes.get('name') + elif e_type == 'image': + src = attributes.get('src') + if src: + thumbnails.append({ + 'url': src, + 'width': int_or_none(attributes.get('width')), + 'height': int_or_none(attributes.get('height')), + }) + if e_type == 'show': + series = attributes.get('name') + elif e_type == 'tag': + name = attributes.get('name') + if name: + tags.append(name) + return { + 'id': video_id, + 'display_id': display_id, + 'title': title, + 'description': strip_or_none(info.get('description')), + 'duration': float_or_none(info.get('videoDuration'), 1000), + 'timestamp': unified_timestamp(info.get('publishStart')), + 'series': series, + 'season_number': int_or_none(info.get('seasonNumber')), + 'episode_number': int_or_none(info.get('episodeNumber')), + 'creator': creator, + 'tags': tags, + 'thumbnails': thumbnails, + 'formats': formats, + 'subtitles': subtitles, + 'http_headers': { + 'referer': domain, + }, + } + + +class DPlayIE(DPlayBaseIE): + _VALID_URL = r'''(?x)https?:// + (?P + (?:www\.)?(?Pd + (?: + play\.(?Pdk|fi|jp|se|no)| + iscoveryplus\.(?Pdk|es|fi|it|se|no) + ) + )| + (?Pes|it)\.dplay\.com + )/[^/]+''' + DPlayBaseIE._PATH_REGEX + + _TESTS = [{ + # non geo restricted, via secure api, unsigned download hls URL + 'url': 'https://www.dplay.se/videos/nugammalt-77-handelser-som-format-sverige/nugammalt-77-handelser-som-format-sverige-101', + 'info_dict': { + 'id': '13628', + 'display_id': 'nugammalt-77-handelser-som-format-sverige/nugammalt-77-handelser-som-format-sverige-101', + 'ext': 'mp4', + 'title': 'Svensken lär sig njuta av livet', + 'description': 'md5:d3819c9bccffd0fe458ca42451dd50d8', + 'duration': 2649.856, + 'timestamp': 1365453720, + 'upload_date': '20130408', + 'creator': 'Kanal 5', + 'series': 'Nugammalt - 77 händelser som format Sverige', + 'season_number': 1, + 'episode_number': 1, + }, + 'params': { + 'skip_download': True, + }, + }, { + # geo restricted, via secure api, unsigned download hls URL + 'url': 'http://www.dplay.dk/videoer/ted-bundy-mind-of-a-monster/ted-bundy-mind-of-a-monster', + 'info_dict': { + 'id': '104465', + 'display_id': 'ted-bundy-mind-of-a-monster/ted-bundy-mind-of-a-monster', + 'ext': 'mp4', + 'title': 'Ted Bundy: Mind Of A Monster', + 'description': 'md5:8b780f6f18de4dae631668b8a9637995', + 'duration': 5290.027, + 'timestamp': 1570694400, + 'upload_date': '20191010', + 'creator': 'ID - Investigation Discovery', + 'series': 'Ted Bundy: Mind Of A Monster', + 'season_number': 1, + 'episode_number': 1, + }, + 'params': { + 'skip_download': True, + }, + }, { + # disco-api + 'url': 'https://www.dplay.no/videoer/i-kongens-klr/sesong-1-episode-7', + 'info_dict': { + 'id': '40206', + 'display_id': 'i-kongens-klr/sesong-1-episode-7', + 'ext': 'mp4', + 'title': 'Episode 7', + 'description': 'md5:e3e1411b2b9aebeea36a6ec5d50c60cf', + 'duration': 2611.16, + 'timestamp': 1516726800, + 'upload_date': '20180123', + 'series': 'I kongens klær', + 'season_number': 1, + 'episode_number': 7, + }, + 'params': { + 'skip_download': True, + }, + 'skip': 'Available for Premium users', + }, { + 'url': 'http://it.dplay.com/nove/biografie-imbarazzanti/luigi-di-maio-la-psicosi-di-stanislawskij/', + 'md5': '2b808ffb00fc47b884a172ca5d13053c', + 'info_dict': { + 'id': '6918', + 'display_id': 'biografie-imbarazzanti/luigi-di-maio-la-psicosi-di-stanislawskij', + 'ext': 'mp4', + 'title': 'Luigi Di Maio: la psicosi di Stanislawskij', + 'description': 'md5:3c7a4303aef85868f867a26f5cc14813', + 'thumbnail': r're:^https?://.*\.jpe?g', + 'upload_date': '20160524', + 'timestamp': 1464076800, + 'series': 'Biografie imbarazzanti', + 'season_number': 1, + 'episode': 'Episode 1', + 'episode_number': 1, + }, + }, { + 'url': 'https://es.dplay.com/dmax/la-fiebre-del-oro/temporada-8-episodio-1/', + 'info_dict': { + 'id': '21652', + 'display_id': 'la-fiebre-del-oro/temporada-8-episodio-1', + 'ext': 'mp4', + 'title': 'Episodio 1', + 'description': 'md5:b9dcff2071086e003737485210675f69', + 'thumbnail': r're:^https?://.*\.png', + 'upload_date': '20180709', + 'timestamp': 1531173540, + 'series': 'La fiebre del oro', + 'season_number': 8, + 'episode': 'Episode 1', + 'episode_number': 1, + }, + 'params': { + 'skip_download': True, + }, + }, { + 'url': 'https://www.dplay.fi/videot/shifting-gears-with-aaron-kaufman/episode-16', + 'only_matching': True, + }, { + 'url': 'https://www.dplay.jp/video/gold-rush/24086', + 'only_matching': True, + }, { + 'url': 'https://www.discoveryplus.se/videos/nugammalt-77-handelser-som-format-sverige/nugammalt-77-handelser-som-format-sverige-101', + 'only_matching': True, + }, { + 'url': 'https://www.discoveryplus.dk/videoer/ted-bundy-mind-of-a-monster/ted-bundy-mind-of-a-monster', + 'only_matching': True, + }, { + 'url': 'https://www.discoveryplus.no/videoer/i-kongens-klr/sesong-1-episode-7', + 'only_matching': True, + }, { + 'url': 'https://www.discoveryplus.it/videos/biografie-imbarazzanti/luigi-di-maio-la-psicosi-di-stanislawskij', + 'only_matching': True, + }, { + 'url': 'https://www.discoveryplus.es/videos/la-fiebre-del-oro/temporada-8-episodio-1', + 'only_matching': True, + }, { + 'url': 'https://www.discoveryplus.fi/videot/shifting-gears-with-aaron-kaufman/episode-16', + 'only_matching': True, + }] + + def _real_extract(self, url): + mobj = self._match_valid_url(url) + display_id = mobj.group('id') + domain = remove_start(mobj.group('domain'), 'www.') + country = mobj.group('country') or mobj.group('subdomain_country') or mobj.group('plus_country') + host = 'disco-api.' + domain if domain[0] == 'd' else 'eu2-prod.disco-api.com' + return self._get_disco_api_info( + url, display_id, host, 'dplay' + country, country, domain) + + +class DiscoveryPlusBaseIE(DPlayBaseIE): + """Subclasses must set _PRODUCT, _DISCO_API_PARAMS""" + + _DISCO_CLIENT_VER = '27.43.0' + + def _update_disco_api_headers(self, headers, disco_base, display_id, realm): + headers.update({ + 'x-disco-params': f'realm={realm},siteLookupKey={self._PRODUCT}', + 'x-disco-client': f'WEB:UNKNOWN:{self._PRODUCT}:{self._DISCO_CLIENT_VER}', + 'Authorization': self._get_auth(disco_base, display_id, realm), + }) + + def _download_video_playback_info(self, disco_base, video_id, headers): + return self._download_json( + disco_base + 'playback/v3/videoPlaybackInfo', + video_id, headers=headers, data=json.dumps({ + 'deviceInfo': { + 'adBlocker': False, + 'drmSupported': False, + }, + 'videoId': video_id, + 'wisteriaProperties': {}, + }).encode())['data']['attributes']['streaming'] + + def _real_extract(self, url): + return self._get_disco_api_info(url, self._match_id(url), **self._DISCO_API_PARAMS) + + +class HGTVDeIE(DiscoveryPlusBaseIE): + _VALID_URL = r'https?://de\.hgtv\.com/sendungen' + DPlayBaseIE._PATH_REGEX + _TESTS = [{ + 'url': 'https://de.hgtv.com/sendungen/mein-kleinstadt-traumhaus/vom-landleben-ins-loft', + 'info_dict': { + 'id': '7332936', + 'ext': 'mp4', + 'display_id': 'mein-kleinstadt-traumhaus/vom-landleben-ins-loft', + 'title': 'Vom Landleben ins Loft', + 'description': 'md5:e5f72c02c853970796dd3818f2e25745', + 'episode': 'Episode 7', + 'episode_number': 7, + 'season': 'Season 7', + 'season_number': 7, + 'series': 'Mein Kleinstadt-Traumhaus', + 'duration': 2645.0, + 'timestamp': 1725998100, + 'upload_date': '20240910', + 'creators': ['HGTV'], + 'tags': [], + 'thumbnail': 'https://eu1-prod-images.disco-api.com/2024/08/09/82a386b9-c688-32c7-b9ff-0b13865f0bae.jpeg', + }, + }] + + _PRODUCT = 'hgtv' + _DISCO_API_PARAMS = { + 'disco_host': 'eu1-prod.disco-api.com', + 'realm': 'hgtv', + 'country': 'de', + } + + def _update_disco_api_headers(self, headers, disco_base, display_id, realm): + headers.update({ + 'x-disco-params': f'realm={realm}', + 'x-disco-client': 'Alps:HyogaPlayer:0.0.0', + 'Authorization': self._get_auth(disco_base, display_id, realm), + }) + + +class GoDiscoveryIE(DiscoveryPlusBaseIE): + _VALID_URL = r'https?://(?:go\.)?discovery\.com/video' + DPlayBaseIE._PATH_REGEX + _TESTS = [{ + 'url': 'https://go.discovery.com/video/in-the-eye-of-the-storm-discovery-atve-us/trapped-in-a-twister', + 'info_dict': { + 'id': '5352642', + 'display_id': 'in-the-eye-of-the-storm-discovery-atve-us/trapped-in-a-twister', + 'ext': 'mp4', + 'title': 'Trapped in a Twister', + 'description': 'Twisters destroy Midwest towns, trapping spotters in the eye of the storm.', + 'episode_number': 1, + 'episode': 'Episode 1', + 'season_number': 1, + 'season': 'Season 1', + 'series': 'In The Eye Of The Storm', + 'duration': 2490.237, + 'upload_date': '20240715', + 'timestamp': 1721008800, + 'tags': [], + 'creators': ['Discovery'], + 'thumbnail': 'https://us1-prod-images.disco-api.com/2024/07/10/5e39637d-cabf-3ab3-8e9a-f4e9d37bc036.jpeg', + }, + }, { + 'url': 'https://go.discovery.com/video/dirty-jobs-discovery-atve-us/rodbuster-galvanizer', + 'info_dict': { + 'id': '4164906', + 'display_id': 'dirty-jobs-discovery-atve-us/rodbuster-galvanizer', + 'ext': 'mp4', + 'title': 'Rodbuster / Galvanizer', + 'description': 'Mike installs rebar with a team of rodbusters, then he galvanizes steel.', + 'season_number': 9, + 'episode_number': 1, + }, + 'skip': 'Available for Premium users', + }, { + 'url': 'https://discovery.com/video/dirty-jobs-discovery-atve-us/rodbuster-galvanizer', + 'only_matching': True, + }] + + _PRODUCT = 'dsc' + _DISCO_API_PARAMS = { + 'disco_host': 'us1-prod-direct.go.discovery.com', + 'realm': 'go', + 'country': 'us', + } + + +class TravelChannelIE(DiscoveryPlusBaseIE): + _VALID_URL = r'https?://(?:watch\.)?travelchannel\.com/video' + DPlayBaseIE._PATH_REGEX + _TESTS = [{ + 'url': 'https://watch.travelchannel.com/video/the-dead-files-travel-channel/protect-the-children', + 'info_dict': { + 'id': '4710177', + 'display_id': 'the-dead-files-travel-channel/protect-the-children', + 'ext': 'mp4', + 'title': 'Protect the Children', + 'description': 'An evil presence threatens an Ohio woman\'s children and marriage.', + 'season_number': 14, + 'season': 'Season 14', + 'episode_number': 10, + 'episode': 'Episode 10', + 'series': 'The Dead Files', + 'duration': 2550.481, + 'timestamp': 1664510400, + 'upload_date': '20220930', + 'tags': [], + 'creators': ['Travel Channel'], + 'thumbnail': 'https://us1-prod-images.disco-api.com/2022/03/17/5e45eace-de5d-343a-9293-f400a2aa77d5.jpeg', + }, + }, { + 'url': 'https://watch.travelchannel.com/video/ghost-adventures-travel-channel/ghost-train-of-ely', + 'info_dict': { + 'id': '2220256', + 'display_id': 'ghost-adventures-travel-channel/ghost-train-of-ely', + 'ext': 'mp4', + 'title': 'Ghost Train of Ely', + 'description': 'The crew investigates the dark history of the Nevada Northern Railway.', + 'season_number': 24, + 'episode_number': 1, + }, + 'skip': 'Available for Premium users', + }, { + 'url': 'https://watch.travelchannel.com/video/ghost-adventures-travel-channel/ghost-train-of-ely', + 'only_matching': True, + }] + + _PRODUCT = 'trav' + _DISCO_API_PARAMS = { + 'disco_host': 'us1-prod-direct.watch.travelchannel.com', + 'realm': 'go', + 'country': 'us', + } + + +class CookingChannelIE(DiscoveryPlusBaseIE): + _VALID_URL = r'https?://(?:watch\.)?cookingchanneltv\.com/video' + DPlayBaseIE._PATH_REGEX + _TESTS = [{ + 'url': 'https://watch.cookingchanneltv.com/video/bobbys-triple-threat-food-network-atve-us/titans-vs-marcus-samuelsson', + 'info_dict': { + 'id': '5350005', + 'ext': 'mp4', + 'display_id': 'bobbys-triple-threat-food-network-atve-us/titans-vs-marcus-samuelsson', + 'title': 'Titans vs Marcus Samuelsson', + 'description': 'Marcus Samuelsson throws his legendary global tricks at the Titans.', + 'episode_number': 1, + 'episode': 'Episode 1', + 'season_number': 3, + 'season': 'Season 3', + 'series': 'Bobby\'s Triple Threat', + 'duration': 2520.851, + 'upload_date': '20240710', + 'timestamp': 1720573200, + 'tags': [], + 'creators': ['Food Network'], + 'thumbnail': 'https://us1-prod-images.disco-api.com/2024/07/04/529cd095-27ec-35c5-84e9-90ebd3e5d2da.jpeg', + }, + }, { + 'url': 'https://watch.cookingchanneltv.com/video/carnival-eats-cooking-channel/the-postman-always-brings-rice-2348634', + 'info_dict': { + 'id': '2348634', + 'display_id': 'carnival-eats-cooking-channel/the-postman-always-brings-rice-2348634', + 'ext': 'mp4', + 'title': 'The Postman Always Brings Rice', + 'description': 'Noah visits the Maui Fair and the Aurora Winter Festival in Vancouver.', + 'season_number': 9, + 'episode_number': 1, + }, + 'skip': 'Available for Premium users', + }, { + 'url': 'https://watch.cookingchanneltv.com/video/carnival-eats-cooking-channel/the-postman-always-brings-rice-2348634', + 'only_matching': True, + }] + + _PRODUCT = 'cook' + _DISCO_API_PARAMS = { + 'disco_host': 'us1-prod-direct.watch.cookingchanneltv.com', + 'realm': 'go', + 'country': 'us', + } + + +class HGTVUsaIE(DiscoveryPlusBaseIE): + _VALID_URL = r'https?://(?:watch\.)?hgtv\.com/video' + DPlayBaseIE._PATH_REGEX + _TESTS = [{ + 'url': 'https://watch.hgtv.com/video/flip-or-flop-the-final-flip-hgtv-atve-us/flip-or-flop-the-final-flip', + 'info_dict': { + 'id': '5025585', + 'display_id': 'flip-or-flop-the-final-flip-hgtv-atve-us/flip-or-flop-the-final-flip', + 'ext': 'mp4', + 'title': 'Flip or Flop: The Final Flip', + 'description': 'Tarek and Christina are going their separate ways after one last flip!', + 'series': 'Flip or Flop: The Final Flip', + 'duration': 2580.644, + 'upload_date': '20231101', + 'timestamp': 1698811200, + 'tags': [], + 'creators': ['HGTV'], + 'thumbnail': 'https://us1-prod-images.disco-api.com/2022/11/27/455caa6c-1462-3f14-b63d-a026d7a5e6d3.jpeg', + }, + }, { + 'url': 'https://watch.hgtv.com/video/home-inspector-joe-hgtv-atve-us/this-mold-house', + 'info_dict': { + 'id': '4289736', + 'display_id': 'home-inspector-joe-hgtv-atve-us/this-mold-house', + 'ext': 'mp4', + 'title': 'This Mold House', + 'description': 'Joe and Noel help take a familys dream home from hazardous to fabulous.', + 'season_number': 1, + 'episode_number': 1, + }, + 'skip': 'Available for Premium users', + }, { + 'url': 'https://watch.hgtv.com/video/home-inspector-joe-hgtv-atve-us/this-mold-house', + 'only_matching': True, + }] + + _PRODUCT = 'hgtv' + _DISCO_API_PARAMS = { + 'disco_host': 'us1-prod-direct.watch.hgtv.com', + 'realm': 'go', + 'country': 'us', + } + + +class FoodNetworkIE(DiscoveryPlusBaseIE): + _VALID_URL = r'https?://(?:watch\.)?foodnetwork\.com/video' + DPlayBaseIE._PATH_REGEX + _TESTS = [{ + 'url': 'https://watch.foodnetwork.com/video/guys-grocery-games-food-network/wild-in-the-aisles', + 'info_dict': { + 'id': '2152549', + 'display_id': 'guys-grocery-games-food-network/wild-in-the-aisles', + 'ext': 'mp4', + 'title': 'Wild in the Aisles', + 'description': 'The chefs make spaghetti and meatballs with "Out of Stock" ingredients.', + 'season_number': 1, + 'season': 'Season 1', + 'episode_number': 1, + 'episode': 'Episode 1', + 'series': 'Guy\'s Grocery Games', + 'tags': [], + 'creators': ['Food Network'], + 'duration': 2520.651, + 'upload_date': '20230623', + 'timestamp': 1687492800, + 'thumbnail': 'https://us1-prod-images.disco-api.com/2022/06/15/37fb5333-cad2-3dbb-af7c-c20ec77c89c6.jpeg', + }, + }, { + 'url': 'https://watch.foodnetwork.com/video/kids-baking-championship-food-network/float-like-a-butterfly', + 'info_dict': { + 'id': '4116449', + 'display_id': 'kids-baking-championship-food-network/float-like-a-butterfly', + 'ext': 'mp4', + 'title': 'Float Like a Butterfly', + 'description': 'The 12 kid bakers create colorful carved butterfly cakes.', + 'season_number': 10, + 'episode_number': 1, + }, + 'skip': 'Available for Premium users', + }, { + 'url': 'https://watch.foodnetwork.com/video/kids-baking-championship-food-network/float-like-a-butterfly', + 'only_matching': True, + }] + + _PRODUCT = 'food' + _DISCO_API_PARAMS = { + 'disco_host': 'us1-prod-direct.watch.foodnetwork.com', + 'realm': 'go', + 'country': 'us', + } + + +class DestinationAmericaIE(DiscoveryPlusBaseIE): + _VALID_URL = r'https?://(?:www\.)?destinationamerica\.com/video' + DPlayBaseIE._PATH_REGEX + _TESTS = [{ + 'url': 'https://www.destinationamerica.com/video/bbq-pit-wars-destination-america/smoke-on-the-water', + 'info_dict': { + 'id': '2218409', + 'display_id': 'bbq-pit-wars-destination-america/smoke-on-the-water', + 'ext': 'mp4', + 'title': 'Smoke on the Water', + 'description': 'The pitmasters head to Georgia for the Smoke on the Water BBQ Festival.', + 'season_number': 2, + 'season': 'Season 2', + 'episode_number': 1, + 'episode': 'Episode 1', + 'series': 'BBQ Pit Wars', + 'tags': [], + 'creators': ['Destination America'], + 'duration': 2614.878, + 'upload_date': '20230623', + 'timestamp': 1687492800, + 'thumbnail': 'https://us1-prod-images.disco-api.com/2020/05/11/c0f8e85d-9a10-3e6f-8e43-f6faafa81ba2.jpeg', + }, + }, { + 'url': 'https://www.destinationamerica.com/video/alaska-monsters-destination-america-atve-us/central-alaskas-bigfoot', + 'info_dict': { + 'id': '4210904', + 'display_id': 'alaska-monsters-destination-america-atve-us/central-alaskas-bigfoot', + 'ext': 'mp4', + 'title': 'Central Alaskas Bigfoot', + 'description': 'A team heads to central Alaska to investigate an aggressive Bigfoot.', + 'season_number': 1, + 'episode_number': 1, + }, + 'skip': 'Available for Premium users', + }, { + 'url': 'https://www.destinationamerica.com/video/alaska-monsters-destination-america-atve-us/central-alaskas-bigfoot', + 'only_matching': True, + }] + + _PRODUCT = 'dam' + _DISCO_API_PARAMS = { + 'disco_host': 'us1-prod-direct.destinationamerica.com', + 'realm': 'go', + 'country': 'us', + } + + +class InvestigationDiscoveryIE(DiscoveryPlusBaseIE): + _VALID_URL = r'https?://(?:www\.)?investigationdiscovery\.com/video' + DPlayBaseIE._PATH_REGEX + _TESTS = [{ + 'url': 'https://www.investigationdiscovery.com/video/deadly-influence-the-social-media-murders-investigation-discovery-atve-us/rip-bianca', + 'info_dict': { + 'id': '5341132', + 'display_id': 'deadly-influence-the-social-media-murders-investigation-discovery-atve-us/rip-bianca', + 'ext': 'mp4', + 'title': 'RIP Bianca', + 'description': 'A teenage influencer discovers an online world of threat, harm and danger.', + 'season_number': 1, + 'season': 'Season 1', + 'episode_number': 3, + 'episode': 'Episode 3', + 'series': 'Deadly Influence: The Social Media Murders', + 'creators': ['Investigation Discovery'], + 'tags': [], + 'duration': 2490.888, + 'upload_date': '20240618', + 'timestamp': 1718672400, + 'thumbnail': 'https://us1-prod-images.disco-api.com/2024/06/15/b567c774-9e44-3c6c-b0ba-db860a73e812.jpeg', + }, + }, { + 'url': 'https://www.investigationdiscovery.com/video/unmasked-investigation-discovery/the-killer-clown', + 'info_dict': { + 'id': '2139409', + 'display_id': 'unmasked-investigation-discovery/the-killer-clown', + 'ext': 'mp4', + 'title': 'The Killer Clown', + 'description': 'A wealthy Florida woman is fatally shot in the face by a clown at her door.', + 'season_number': 1, + 'episode_number': 1, + }, + 'skip': 'Available for Premium users', + }, { + 'url': 'https://www.investigationdiscovery.com/video/unmasked-investigation-discovery/the-killer-clown', + 'only_matching': True, + }] + + _PRODUCT = 'ids' + _DISCO_API_PARAMS = { + 'disco_host': 'us1-prod-direct.investigationdiscovery.com', + 'realm': 'go', + 'country': 'us', + } + + +class AmHistoryChannelIE(DiscoveryPlusBaseIE): + _VALID_URL = r'https?://(?:www\.)?ahctv\.com/video' + DPlayBaseIE._PATH_REGEX + _TESTS = [{ + 'url': 'https://www.ahctv.com/video/blood-and-fury-americas-civil-war-ahc/battle-of-bull-run', + 'info_dict': { + 'id': '2139199', + 'display_id': 'blood-and-fury-americas-civil-war-ahc/battle-of-bull-run', + 'ext': 'mp4', + 'title': 'Battle of Bull Run', + 'description': 'Two untested armies clash in the first real battle of the Civil War.', + 'season_number': 1, + 'season': 'Season 1', + 'episode_number': 1, + 'episode': 'Episode 1', + 'series': 'Blood and Fury: America\'s Civil War', + 'duration': 2612.509, + 'upload_date': '20220923', + 'timestamp': 1663905600, + 'creators': ['AHC'], + 'tags': [], + 'thumbnail': 'https://us1-prod-images.disco-api.com/2020/05/11/4af61bd7-d705-3108-82c4-1a6e541e20fa.jpeg', + }, + }, { + 'url': 'https://www.ahctv.com/video/modern-sniper-ahc/army', + 'info_dict': { + 'id': '2309730', + 'display_id': 'modern-sniper-ahc/army', + 'ext': 'mp4', + 'title': 'Army', + 'description': 'Snipers today face challenges their predecessors couldve only dreamed of.', + 'season_number': 1, + 'episode_number': 1, + }, + 'skip': 'Available for Premium users', + }, { + 'url': 'https://www.ahctv.com/video/modern-sniper-ahc/army', + 'only_matching': True, + }] + + _PRODUCT = 'ahc' + _DISCO_API_PARAMS = { + 'disco_host': 'us1-prod-direct.ahctv.com', + 'realm': 'go', + 'country': 'us', + } + + +class ScienceChannelIE(DiscoveryPlusBaseIE): + _VALID_URL = r'https?://(?:www\.)?sciencechannel\.com/video' + DPlayBaseIE._PATH_REGEX + _TESTS = [{ + 'url': 'https://www.sciencechannel.com/video/spaces-deepest-secrets-science-atve-us/mystery-of-the-dead-planets', + 'info_dict': { + 'id': '2347335', + 'display_id': 'spaces-deepest-secrets-science-atve-us/mystery-of-the-dead-planets', + 'ext': 'mp4', + 'title': 'Mystery of the Dead Planets', + 'description': 'Astronomers unmask the truly destructive nature of the cosmos.', + 'season_number': 7, + 'season': 'Season 7', + 'episode_number': 1, + 'episode': 'Episode 1', + 'series': 'Space\'s Deepest Secrets', + 'duration': 2524.989, + 'upload_date': '20230128', + 'timestamp': 1674882000, + 'creators': ['Science'], + 'tags': [], + 'thumbnail': 'https://us1-prod-images.disco-api.com/2021/03/30/3796829d-aead-3f9a-bd8d-e49048b3cdca.jpeg', + }, + }, { + 'url': 'https://www.sciencechannel.com/video/strangest-things-science-atve-us/nazi-mystery-machine', + 'info_dict': { + 'id': '2842849', + 'display_id': 'strangest-things-science-atve-us/nazi-mystery-machine', + 'ext': 'mp4', + 'title': 'Nazi Mystery Machine', + 'description': 'Experts investigate the secrets of a revolutionary encryption machine.', + 'season_number': 1, + 'episode_number': 1, + }, + 'skip': 'Available for Premium users', + }, { + 'url': 'https://www.sciencechannel.com/video/strangest-things-science-atve-us/nazi-mystery-machine', + 'only_matching': True, + }] + + _PRODUCT = 'sci' + _DISCO_API_PARAMS = { + 'disco_host': 'us1-prod-direct.sciencechannel.com', + 'realm': 'go', + 'country': 'us', + } + + +class DiscoveryLifeIE(DiscoveryPlusBaseIE): + _VALID_URL = r'https?://(?:www\.)?discoverylife\.com/video' + DPlayBaseIE._PATH_REGEX + _TESTS = [{ + 'url': 'https://www.discoverylife.com/video/er-files-discovery-life-atve-us/sweet-charity', + 'info_dict': { + 'id': '2347614', + 'display_id': 'er-files-discovery-life-atve-us/sweet-charity', + 'ext': 'mp4', + 'title': 'Sweet Charity', + 'description': 'The staff at Charity Hospital treat a serious foot infection.', + 'season_number': 1, + 'season': 'Season 1', + 'episode_number': 1, + 'episode': 'Episode 1', + 'series': 'ER Files', + 'duration': 2364.261, + 'upload_date': '20230721', + 'timestamp': 1689912000, + 'creators': ['Discovery Life'], + 'tags': [], + 'thumbnail': 'https://us1-prod-images.disco-api.com/2021/03/16/4b6f0124-360b-3546-b6a4-5552db886b86.jpeg', + }, + }, { + 'url': 'https://www.discoverylife.com/video/surviving-death-discovery-life-atve-us/bodily-trauma', + 'info_dict': { + 'id': '2218238', + 'display_id': 'surviving-death-discovery-life-atve-us/bodily-trauma', + 'ext': 'mp4', + 'title': 'Bodily Trauma', + 'description': 'Meet three people who tested the limits of the human body.', + 'season_number': 1, + 'episode_number': 2, + }, + 'skip': 'Available for Premium users', + }, { + 'url': 'https://www.discoverylife.com/video/surviving-death-discovery-life-atve-us/bodily-trauma', + 'only_matching': True, + }] + + _PRODUCT = 'dlf' + _DISCO_API_PARAMS = { + 'disco_host': 'us1-prod-direct.discoverylife.com', + 'realm': 'go', + 'country': 'us', + } + + +class AnimalPlanetIE(DiscoveryPlusBaseIE): + _VALID_URL = r'https?://(?:www\.)?animalplanet\.com/video' + DPlayBaseIE._PATH_REGEX + _TESTS = [{ + 'url': 'https://www.animalplanet.com/video/mysterious-creatures-with-forrest-galante-animal-planet-atve-us/the-demon-of-peru', + 'info_dict': { + 'id': '4650835', + 'display_id': 'mysterious-creatures-with-forrest-galante-animal-planet-atve-us/the-demon-of-peru', + 'ext': 'mp4', + 'title': 'The Demon of Peru', + 'description': 'In Peru, a farming village is being terrorized by a “man-like beast.”', + 'season_number': 1, + 'season': 'Season 1', + 'episode_number': 4, + 'episode': 'Episode 4', + 'series': 'Mysterious Creatures with Forrest Galante', + 'duration': 2490.488, + 'upload_date': '20230111', + 'timestamp': 1673413200, + 'creators': ['Animal Planet'], + 'tags': [], + 'thumbnail': 'https://us1-prod-images.disco-api.com/2022/03/01/6dbaa833-9a2e-3fee-9381-c19eddf67c0c.jpeg', + }, + }, { + 'url': 'https://www.animalplanet.com/video/north-woods-law-animal-planet/squirrel-showdown', + 'info_dict': { + 'id': '3338923', + 'display_id': 'north-woods-law-animal-planet/squirrel-showdown', + 'ext': 'mp4', + 'title': 'Squirrel Showdown', + 'description': 'A woman is suspected of being in possession of flying squirrel kits.', + 'season_number': 16, + 'episode_number': 11, + }, + 'skip': 'Available for Premium users', + }, { + 'url': 'https://www.animalplanet.com/video/north-woods-law-animal-planet/squirrel-showdown', + 'only_matching': True, + }] + + _PRODUCT = 'apl' + _DISCO_API_PARAMS = { + 'disco_host': 'us1-prod-direct.animalplanet.com', + 'realm': 'go', + 'country': 'us', + } + + +class TLCIE(DiscoveryPlusBaseIE): + _VALID_URL = r'https?://(?:go\.)?tlc\.com/video' + DPlayBaseIE._PATH_REGEX + _TESTS = [{ + 'url': 'https://go.tlc.com/video/90-day-the-last-resort-tlc-atve-us/the-last-chance', + 'info_dict': { + 'id': '5186422', + 'display_id': '90-day-the-last-resort-tlc-atve-us/the-last-chance', + 'ext': 'mp4', + 'title': 'The Last Chance', + 'description': 'Infidelity shakes Kalani and Asuelu\'s world, and Angela threatens divorce.', + 'season_number': 1, + 'season': 'Season 1', + 'episode_number': 1, + 'episode': 'Episode 1', + 'series': '90 Day: The Last Resort', + 'duration': 5123.91, + 'upload_date': '20230815', + 'timestamp': 1692061200, + 'creators': ['TLC'], + 'tags': [], + 'thumbnail': 'https://us1-prod-images.disco-api.com/2023/08/08/0ee367e2-ac76-334d-bf23-dbf796696a24.jpeg', + }, + }, { + 'url': 'https://go.tlc.com/video/my-600-lb-life-tlc/melissas-story-part-1', + 'info_dict': { + 'id': '2206540', + 'display_id': 'my-600-lb-life-tlc/melissas-story-part-1', + 'ext': 'mp4', + 'title': 'Melissas Story (Part 1)', + 'description': 'At 650 lbs, Melissa is ready to begin her seven-year weight loss journey.', + 'season_number': 1, + 'episode_number': 1, + }, + 'skip': 'Available for Premium users', + }, { + 'url': 'https://go.tlc.com/video/my-600-lb-life-tlc/melissas-story-part-1', + 'only_matching': True, + }] + + _PRODUCT = 'tlc' + _DISCO_API_PARAMS = { + 'disco_host': 'us1-prod-direct.tlc.com', + 'realm': 'go', + 'country': 'us', + } + + +class DiscoveryPlusIE(DiscoveryPlusBaseIE): + _VALID_URL = r'https?://(?:www\.)?discoveryplus\.com/(?!it/)(?:(?P[a-z]{2})/)?video(?:/sport|/olympics)?' + DPlayBaseIE._PATH_REGEX + _TESTS = [{ + 'url': 'https://www.discoveryplus.com/video/property-brothers-forever-home/food-and-family', + 'info_dict': { + 'id': '1140794', + 'display_id': 'property-brothers-forever-home/food-and-family', + 'ext': 'mp4', + 'title': 'Food and Family', + 'description': 'The brothers help a Richmond family expand their single-level home.', + 'duration': 2583.113, + 'timestamp': 1609304400, + 'upload_date': '20201230', + 'creator': 'HGTV', + 'series': 'Property Brothers: Forever Home', + 'season_number': 1, + 'episode_number': 1, + }, + 'skip': 'Available for Premium users', + }, { + 'url': 'https://discoveryplus.com/ca/video/bering-sea-gold-discovery-ca/goldslingers', + 'only_matching': True, + }, { + 'url': 'https://www.discoveryplus.com/gb/video/sport/eurosport-1-british-eurosport-1-british-sport/6-hours-of-spa-review', + 'only_matching': True, + }, { + 'url': 'https://www.discoveryplus.com/gb/video/olympics/dplus-sport-dplus-sport-sport/rugby-sevens-australia-samoa', + 'only_matching': True, + }] + + _PRODUCT = None + _DISCO_API_PARAMS = None + + def _update_disco_api_headers(self, headers, disco_base, display_id, realm): + headers.update({ + 'x-disco-params': f'realm={realm},siteLookupKey={self._PRODUCT}', + 'x-disco-client': f'WEB:UNKNOWN:dplus_us:{self._DISCO_CLIENT_VER}', + 'Authorization': self._get_auth(disco_base, display_id, realm), + }) + + def _real_extract(self, url): + video_id, country = self._match_valid_url(url).group('id', 'country') + if not country: + country = 'us' + + self._PRODUCT = f'dplus_{country}' + + if country in ('br', 'ca', 'us'): + self._DISCO_API_PARAMS = { + 'disco_host': 'us1-prod-direct.discoveryplus.com', + 'realm': 'go', + 'country': country, + } + else: + self._DISCO_API_PARAMS = { + 'disco_host': 'eu1-prod-direct.discoveryplus.com', + 'realm': 'dplay', + 'country': country, + } + + return self._get_disco_api_info(url, video_id, **self._DISCO_API_PARAMS) + + +class DiscoveryPlusIndiaIE(DiscoveryPlusBaseIE): + _VALID_URL = r'https?://(?:www\.)?discoveryplus\.in/videos?' + DPlayBaseIE._PATH_REGEX + _TESTS = [{ + 'url': 'https://www.discoveryplus.in/videos/how-do-they-do-it/fugu-and-more?seasonId=8&type=EPISODE', + 'info_dict': { + 'id': '27104', + 'ext': 'mp4', + 'display_id': 'how-do-they-do-it/fugu-and-more', + 'title': 'Fugu and More', + 'description': 'The Japanese catch, prepare and eat the deadliest fish on the planet.', + 'duration': 1319.32, + 'timestamp': 1582309800, + 'upload_date': '20200221', + 'series': 'How Do They Do It?', + 'season_number': 8, + 'episode_number': 2, + 'creator': 'Discovery Channel', + 'thumbnail': r're:https://.+\.jpeg', + 'episode': 'Episode 2', + 'season': 'Season 8', + 'tags': [], + }, + 'params': { + 'skip_download': True, + }, + }] + + _PRODUCT = 'dplus-india' + _DISCO_API_PARAMS = { + 'disco_host': 'ap2-prod-direct.discoveryplus.in', + 'realm': 'dplusindia', + 'country': 'in', + 'domain': 'https://www.discoveryplus.in/', + } + + def _update_disco_api_headers(self, headers, disco_base, display_id, realm): + headers.update({ + 'x-disco-params': f'realm={realm}', + 'x-disco-client': f'WEB:UNKNOWN:{self._PRODUCT}:17.0.0', + 'Authorization': self._get_auth(disco_base, display_id, realm), + }) + + +class DiscoveryNetworksDeIE(DiscoveryPlusBaseIE): + _VALID_URL = r'https?://(?:www\.)?(?P(?:tlc|dmax)\.de)/(?:programme|show|sendungen)/(?P[^/?#]+)/(?:video/)?(?P[^/?#]+)' + + _TESTS = [{ + 'url': 'https://dmax.de/sendungen/goldrausch-in-australien/german-gold', + 'info_dict': { + 'id': '4756322', + 'ext': 'mp4', + 'title': 'German Gold', + 'description': 'md5:f3073306553a8d9b40e6ac4cdbf09fc6', + 'display_id': 'goldrausch-in-australien/german-gold', + 'episode': 'Episode 1', + 'episode_number': 1, + 'season': 'Season 5', + 'season_number': 5, + 'series': 'Goldrausch in Australien', + 'duration': 2648.0, + 'upload_date': '20230517', + 'timestamp': 1684357500, + 'creators': ['DMAX'], + 'thumbnail': 'https://eu1-prod-images.disco-api.com/2023/05/09/f72fb510-7992-3b12-af7f-f16a2c22d1e3.jpeg', + 'tags': ['schatzsucher', 'schatz', 'nugget', 'bodenschätze', 'down under', 'australien', 'goldrausch'], + 'categories': ['Gold', 'Schatzsucher'], + }, + 'params': {'skip_download': 'm3u8'}, + }, { + 'url': 'https://www.tlc.de/programme/breaking-amish/video/die-welt-da-drauen/DCB331270001100', + 'info_dict': { + 'id': '78867', + 'ext': 'mp4', + 'title': 'Die Welt da draußen', + 'description': 'md5:61033c12b73286e409d99a41742ef608', + 'timestamp': 1554069600, + 'upload_date': '20190331', + 'creator': 'TLC', + 'season': 'Season 1', + 'series': 'Breaking Amish', + 'episode_number': 1, + 'tags': ['new york', 'großstadt', 'amische', 'landleben', 'modern', 'infos', 'tradition', 'herausforderung'], + 'display_id': 'breaking-amish/die-welt-da-drauen', + 'episode': 'Episode 1', + 'duration': 2625.024, + 'season_number': 1, + 'thumbnail': r're:https://.+\.jpg', + }, + 'skip': '404 Not Found', + }, { + 'url': 'https://www.dmax.de/programme/dmax-highlights/video/tuning-star-sidney-hoffmann-exklusiv-bei-dmax/191023082312316', + 'only_matching': True, + }, { + 'url': 'https://tlc.de/sendungen/breaking-amish/die-welt-da-drauen/', + 'only_matching': True, + }, { + 'url': 'https://dmax.de/sendungen/feuerwache-3-alarm-in-muenchen/24-stunden-auf-der-feuerwache-3', + 'info_dict': { + 'id': '8873549', + 'ext': 'mp4', + 'title': '24 Stunden auf der Feuerwache 3', + 'description': 'md5:f3084ef6170bfb79f9a6e0c030e09330', + 'display_id': 'feuerwache-3-alarm-in-muenchen/24-stunden-auf-der-feuerwache-3', + 'episode': 'Episode 1', + 'episode_number': 1, + 'season': 'Season 1', + 'season_number': 1, + 'series': 'Feuerwache 3 - Alarm in München', + 'duration': 2632.0, + 'upload_date': '20251016', + 'timestamp': 1760645100, + 'creators': ['DMAX'], + 'thumbnail': 'https://eu1-prod-images.disco-api.com/2025/10/14/0bdee68c-a8d8-33d9-9204-16eb61108552.jpeg', + 'tags': [], + 'categories': ['DMAX Originals', 'Jobs', 'Blaulicht'], + }, + 'params': {'skip_download': 'm3u8'}, + }, { + 'url': 'https://tlc.de/sendungen/ghost-adventures/der-poltergeist-im-kostumladen', + 'info_dict': { + 'id': '4550602', + 'ext': 'mp4', + 'title': 'Der Poltergeist im Kostümladen', + 'description': 'md5:20b52b9736a0a3a7873d19a238fad7fc', + 'display_id': 'ghost-adventures/der-poltergeist-im-kostumladen', + 'episode': 'Episode 1', + 'episode_number': 1, + 'season': 'Season 25', + 'season_number': 25, + 'series': 'Ghost Adventures', + 'duration': 2493.0, + 'upload_date': '20241223', + 'timestamp': 1734948900, + 'creators': ['TLC'], + 'thumbnail': 'https://eu1-prod-images.disco-api.com/2023/04/05/59941d26-a81b-365f-829f-69d8cd81fd0f.jpeg', + 'tags': [], + 'categories': ['Paranormal', 'Gruselig!'], + }, + 'params': {'skip_download': 'm3u8'}, + }, { + 'url': 'https://tlc.de/sendungen/evil-gesichter-des-boesen/das-geheimnis-meines-bruders', + 'info_dict': { + 'id': '7792288', + 'ext': 'mp4', + 'title': 'Das Geheimnis meines Bruders', + 'description': 'md5:3167550bb582eb9c92875c86a0a20882', + 'display_id': 'evil-gesichter-des-boesen/das-geheimnis-meines-bruders', + 'episode': 'Episode 1', + 'episode_number': 1, + 'season': 'Season 1', + 'season_number': 1, + 'series': 'Evil - Gesichter des Bösen', + 'duration': 2626.0, + 'upload_date': '20240926', + 'timestamp': 1727388000, + 'creators': ['TLC'], + 'thumbnail': 'https://eu1-prod-images.disco-api.com/2024/11/29/e9f3e3ae-74ec-3631-81b7-fc7bbe844741.jpeg', + 'tags': 'count:13', + 'categories': ['True Crime', 'Mord'], + }, + 'params': {'skip_download': 'm3u8'}, + }] + + def _real_extract(self, url): + domain, programme, alternate_id = self._match_valid_url(url).groups() + display_id = f'{programme}/{alternate_id}' + meta = self._download_json( + f'https://de-api.loma-cms.com/feloma/videos/{alternate_id}/', + display_id, query={ + 'environment': domain.split('.')[0], + 'v': '2', + 'filter[show.slug]': programme, + }, fatal=False) + video_id = traverse_obj(meta, ('uid', {str}, {lambda s: s[-7:]})) or display_id + + disco_api_info = self._get_disco_api_info( + url, video_id, 'eu1-prod.disco-api.com', domain.replace('.', ''), 'DE') + disco_api_info['display_id'] = display_id + disco_api_info['categories'] = traverse_obj(meta, ( + 'taxonomies', lambda _, v: v['category'] == 'genre', 'title', {str.strip}, filter, all, filter)) + + return disco_api_info + + def _update_disco_api_headers(self, headers, disco_base, display_id, realm): + headers.update({ + 'x-disco-params': f'realm={realm}', + 'x-disco-client': 'Alps:HyogaPlayer:0.0.0', + 'Authorization': self._get_auth(disco_base, display_id, realm), + }) + + +class DiscoveryPlusShowBaseIE(DPlayBaseIE): + + def _entries(self, show_name): + headers = { + 'x-disco-client': self._X_CLIENT, + 'x-disco-params': f'realm={self._REALM}', + 'referer': self._DOMAIN, + 'Authentication': self._get_auth(self._BASE_API, None, self._REALM), + } + show_json = self._download_json( + f'{self._BASE_API}cms/routes/{self._SHOW_STR}/{show_name}?include=default', + video_id=show_name, headers=headers)['included'][self._INDEX]['attributes']['component'] + show_id = show_json['mandatoryParams'].split('=')[-1] + season_url = self._BASE_API + 'content/videos?sort=episodeNumber&filter[seasonNumber]={}&filter[show.id]={}&page[size]=100&page[number]={}' + for season in show_json['filters'][0]['options']: + season_id = season['id'] + total_pages, page_num = 1, 0 + while page_num < total_pages: + season_json = self._download_json( + season_url.format(season_id, show_id, str(page_num + 1)), show_name, headers=headers, + note='Downloading season {} JSON metadata{}'.format(season_id, f' page {page_num}' if page_num else '')) + if page_num == 0: + total_pages = try_get(season_json, lambda x: x['meta']['totalPages'], int) or 1 + episodes_json = season_json['data'] + for episode in episodes_json: + video_path = episode['attributes']['path'] + yield self.url_result( + f'{self._DOMAIN}videos/{video_path}', + ie=self._VIDEO_IE.ie_key(), video_id=episode.get('id') or video_path) + page_num += 1 + + def _real_extract(self, url): + show_name = self._match_valid_url(url).group('show_name') + return self.playlist_result(self._entries(show_name), playlist_id=show_name) + + +class DiscoveryPlusItalyIE(DiscoveryPlusBaseIE): + _VALID_URL = r'https?://(?:www\.)?discoveryplus\.com/it/video(?:/sport|/olympics)?' + DPlayBaseIE._PATH_REGEX + _TESTS = [{ + 'url': 'https://www.discoveryplus.com/it/video/i-signori-della-neve/stagione-2-episodio-1-i-preparativi', + 'only_matching': True, + }, { + 'url': 'https://www.discoveryplus.com/it/video/super-benny/trailer', + 'only_matching': True, + }, { + 'url': 'https://www.discoveryplus.com/it/video/olympics/dplus-sport-dplus-sport-sport/water-polo-greece-italy', + 'only_matching': True, + }, { + 'url': 'https://www.discoveryplus.com/it/video/sport/dplus-sport-dplus-sport-sport/lisa-vittozzi-allinferno-e-ritorno', + 'only_matching': True, + }] + + _PRODUCT = 'dplus_it' + _DISCO_API_PARAMS = { + 'disco_host': 'eu1-prod-direct.discoveryplus.com', + 'realm': 'dplay', + 'country': 'it', + } + + def _update_disco_api_headers(self, headers, disco_base, display_id, realm): + headers.update({ + 'x-disco-params': f'realm={realm},siteLookupKey={self._PRODUCT}', + 'x-disco-client': f'WEB:UNKNOWN:dplus_us:{self._DISCO_CLIENT_VER}', + 'Authorization': self._get_auth(disco_base, display_id, realm), + }) + + +class DiscoveryPlusItalyShowIE(DiscoveryPlusShowBaseIE): + _VALID_URL = r'https?://(?:www\.)?discoveryplus\.it/programmi/(?P[^/]+)/?(?:[?#]|$)' + _TESTS = [{ + 'url': 'https://www.discoveryplus.it/programmi/deal-with-it-stai-al-gioco', + 'playlist_mincount': 168, + 'info_dict': { + 'id': 'deal-with-it-stai-al-gioco', + }, + }] + + _BASE_API = 'https://disco-api.discoveryplus.it/' + _DOMAIN = 'https://www.discoveryplus.it/' + _X_CLIENT = 'WEB:UNKNOWN:dplay-client:2.6.0' + _REALM = 'dplayit' + _SHOW_STR = 'programmi' + _INDEX = 1 + _VIDEO_IE = DPlayIE + + +class DiscoveryPlusIndiaShowIE(DiscoveryPlusShowBaseIE): + _VALID_URL = r'https?://(?:www\.)?discoveryplus\.in/show/(?P[^/]+)/?(?:[?#]|$)' + _TESTS = [{ + 'url': 'https://www.discoveryplus.in/show/how-do-they-do-it', + 'playlist_mincount': 140, + 'info_dict': { + 'id': 'how-do-they-do-it', + }, + }] + + _BASE_API = 'https://ap2-prod-direct.discoveryplus.in/' + _DOMAIN = 'https://www.discoveryplus.in/' + _X_CLIENT = 'WEB:UNKNOWN:dplus-india:prod' + _REALM = 'dplusindia' + _SHOW_STR = 'show' + _INDEX = 4 + _VIDEO_IE = DiscoveryPlusIndiaIE diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/drooble.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/drooble.py new file mode 100644 index 0000000000000000000000000000000000000000..16e9a61941407ae3e04ee8d844ef58f1fc8a4d5b --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/drooble.py @@ -0,0 +1,113 @@ +import json + +from .common import InfoExtractor +from ..utils import ( + ExtractorError, + int_or_none, + try_get, +) + + +class DroobleIE(InfoExtractor): + _VALID_URL = r'''(?x)https?://drooble\.com/(?: + (?:(?P[^/]+)/)?(?Psong|videos|music/albums)/(?P\d+)| + (?P[^/]+)/(?Pvideos|music)) + ''' + _TESTS = [{ + 'url': 'https://drooble.com/song/2858030', + 'md5': '5ffda90f61c7c318dc0c3df4179eb064', + 'info_dict': { + 'id': '2858030', + 'ext': 'mp3', + 'title': 'Skankocillin', + 'upload_date': '20200801', + 'timestamp': 1596241390, + 'uploader_id': '95894', + 'uploader': 'Bluebeat Shelter', + }, + }, { + 'url': 'https://drooble.com/karl340758/videos/2859183', + 'info_dict': { + 'id': 'J6QCQY_I5Tk', + 'ext': 'mp4', + 'title': 'Skankocillin', + 'uploader_id': 'UCrSRoI5vVyeYihtWEYua7rg', + 'description': 'md5:ffc0bd8ba383db5341a86a6cd7d9bcca', + 'upload_date': '20200731', + 'uploader': 'Bluebeat Shelter', + }, + }, { + 'url': 'https://drooble.com/karl340758/music/albums/2858031', + 'info_dict': { + 'id': '2858031', + }, + 'playlist_mincount': 8, + }, { + 'url': 'https://drooble.com/karl340758/music', + 'info_dict': { + 'id': 'karl340758', + }, + 'playlist_mincount': 8, + }, { + 'url': 'https://drooble.com/karl340758/videos', + 'info_dict': { + 'id': 'karl340758', + }, + 'playlist_mincount': 8, + }] + + def _call_api(self, method, video_id, data=None): + response = self._download_json( + f'https://drooble.com/api/dt/{method}', video_id, data=json.dumps(data).encode()) + if not response[0]: + raise ExtractorError('Unable to download JSON metadata') + return response[1] + + def _real_extract(self, url): + mobj = self._match_valid_url(url) + user = mobj.group('user') or mobj.group('user_2') + kind = mobj.group('kind') or mobj.group('kind_2') + display_id = mobj.group('id') or user + + if mobj.group('kind_2') == 'videos': + data = {'from_user': display_id, 'album': -1, 'limit': 18, 'offset': 0, 'order': 'new2old', 'type': 'video'} + elif kind in ('music/albums', 'music'): + data = {'user': user, 'public_only': True, 'individual_limit': {'singles': 1, 'albums': 1, 'playlists': 1}} + else: + data = {'url_slug': display_id, 'children': 10, 'order': 'old2new'} + + method = 'getMusicOverview' if kind in ('music/albums', 'music') else 'getElements' + json_data = self._call_api(method, display_id, data=data) + if kind in ('music/albums', 'music'): + json_data = json_data['singles']['list'] + + entites = [] + for media in json_data: + url = media.get('external_media_url') or media.get('link') + if url.startswith('https://www.youtube.com'): + entites.append({ + '_type': 'url', + 'url': url, + 'ie_key': 'Youtube', + }) + continue + is_audio = (media.get('type') or '').lower() == 'audio' + entites.append({ + 'url': url, + 'id': media['id'], + 'title': media['title'], + 'duration': int_or_none(media.get('duration')), + 'timestamp': int_or_none(media.get('timestamp')), + 'album': try_get(media, lambda x: x['album']['title']), + 'uploader': try_get(media, lambda x: x['creator']['display_name']), + 'uploader_id': try_get(media, lambda x: x['creator']['id']), + 'thumbnail': media.get('image_comment'), + 'like_count': int_or_none(media.get('likes')), + 'vcodec': 'none' if is_audio else None, + 'ext': 'mp3' if is_audio else None, + }) + + if len(entites) > 1: + return self.playlist_result(entites, display_id) + + return entites[0] diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/drtalks.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/drtalks.py new file mode 100644 index 0000000000000000000000000000000000000000..5ea7f75807edb9b1da82d7b42f43742c7dfec081 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/drtalks.py @@ -0,0 +1,51 @@ +from .brightcove import BrightcoveNewIE +from .common import InfoExtractor +from ..utils import url_or_none +from ..utils.traversal import traverse_obj + + +class DrTalksIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?drtalks\.com/videos/(?P[\w-]+)' + _TESTS = [{ + 'url': 'https://drtalks.com/videos/six-pillars-of-resilience-tools-for-managing-stress-and-flourishing/', + 'info_dict': { + 'id': '6366193757112', + 'ext': 'mp4', + 'uploader_id': '6314452011001', + 'tags': ['resilience'], + 'description': 'md5:9c6805aee237ee6de8052461855b9dda', + 'timestamp': 1734546659, + 'thumbnail': 'https://drtalks.com/wp-content/uploads/2024/12/Episode-82-Eva-Selhub-DrTalks-Thumbs.jpg', + 'title': 'Six Pillars of Resilience: Tools for Managing Stress and Flourishing', + 'duration': 2800.682, + 'upload_date': '20241218', + }, + }, { + 'url': 'https://drtalks.com/videos/the-pcos-puzzle-mastering-metabolic-health-with-marcelle-pick/', + 'info_dict': { + 'id': '6364699891112', + 'ext': 'mp4', + 'title': 'The PCOS Puzzle: Mastering Metabolic Health with Marcelle Pick', + 'description': 'md5:e87cbe00ca50135d5702787fc4043aaa', + 'thumbnail': 'https://drtalks.com/wp-content/uploads/2024/11/Episode-34-Marcelle-Pick-OBGYN-NP-DrTalks.jpg', + 'duration': 3515.2, + 'tags': ['pcos'], + 'upload_date': '20241114', + 'timestamp': 1731592119, + 'uploader_id': '6314452011001', + }, + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + webpage = self._download_webpage(url, video_id) + next_data = self._search_nextjs_data(webpage, video_id)['props']['pageProps']['data']['video'] + + return self.url_result( + next_data['videos']['brightcoveVideoLink'], BrightcoveNewIE, video_id, + url_transparent=True, + **traverse_obj(next_data, { + 'title': ('title', {str}), + 'description': ('videos', 'summury', {str}), + 'thumbnail': ('featuredImage', 'node', 'sourceUrl', {url_or_none}), + })) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/drtv.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/drtv.py new file mode 100644 index 0000000000000000000000000000000000000000..ba86eb2b49a053c5ed8f499bc4e0659e4ab6a7d7 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/drtv.py @@ -0,0 +1,400 @@ +import json +import uuid + +from .common import InfoExtractor +from ..utils import ( + ExtractorError, + int_or_none, + mimetype2ext, + parse_iso8601, + try_call, + update_url_query, + url_or_none, +) +from ..utils.traversal import traverse_obj + +SERIES_API = 'https://production-cdn.dr-massive.com/api/page?device=web_browser&item_detail_expand=all&lang=da&max_list_prefetch=3&path=%s' + + +class DRTVIE(InfoExtractor): + _VALID_URL = r'''(?x) + https?:// + (?: + (?:www\.)?dr\.dk/tv/se(?:/ondemand)?/(?:[^/?#]+/)*| + (?:www\.)?(?:dr\.dk|dr-massive\.com)/drtv/(?:se|episode|program)/ + ) + (?P[\da-z_-]+) + ''' + _GEO_BYPASS = False + _GEO_COUNTRIES = ['DK'] + IE_NAME = 'drtv' + _TESTS = [{ + 'url': 'https://www.dr.dk/tv/se/boern/ultra/klassen-ultra/klassen-darlig-taber-10', + 'md5': '25e659cccc9a2ed956110a299fdf5983', + 'info_dict': { + 'id': 'klassen-darlig-taber-10', + 'ext': 'mp4', + 'title': 'Klassen - Dårlig taber (10)', + 'description': 'md5:815fe1b7fa656ed80580f31e8b3c79aa', + 'timestamp': 1539085800, + 'upload_date': '20181009', + 'duration': 606.84, + 'series': 'Klassen', + 'season': 'Klassen I', + 'season_number': 1, + 'season_id': 'urn:dr:mu:bundle:57d7e8216187a4031cfd6f6b', + 'episode': 'Episode 10', + 'episode_number': 10, + 'release_year': 2016, + }, + 'expected_warnings': ['Unable to download f4m manifest'], + 'skip': 'this video has been removed', + }, { + # with SignLanguage formats + 'url': 'https://www.dr.dk/tv/se/historien-om-danmark/-/historien-om-danmark-stenalder', + 'info_dict': { + 'id': '00831690010', + 'ext': 'mp4', + 'title': 'Historien om Danmark: Stenalder', + 'description': 'md5:8c66dcbc1669bbc6f873879880f37f2a', + 'timestamp': 1546628400, + 'upload_date': '20190104', + 'duration': 3504.619, + 'formats': 'mincount:20', + 'release_year': 2017, + 'season_id': 'urn:dr:mu:bundle:5afc03ad6187a4065ca5fd35', + 'season_number': 1, + 'season': 'Historien om Danmark', + 'series': 'Historien om Danmark', + }, + 'skip': 'this video has been removed', + }, { + 'url': 'https://www.dr.dk/drtv/se/frank-and-kastaniegaarden_71769', + 'info_dict': { + 'id': '00951930010', + 'ext': 'mp4', + 'title': 'Frank & Kastaniegaarden', + 'description': 'md5:974e1780934cf3275ef10280204bccb0', + 'release_timestamp': 1546545600, + 'release_date': '20190103', + 'duration': 2576, + 'season': 'Frank & Kastaniegaarden', + 'season_id': '67125', + 'release_year': 2019, + 'season_number': 2019, + 'series': 'Frank & Kastaniegaarden', + 'episode_number': 1, + 'episode': 'Frank & Kastaniegaarden', + 'thumbnail': r're:https?://.+', + }, + 'params': { + 'skip_download': True, + }, + }, { + # Foreign and Regular subtitle track + 'url': 'https://www.dr.dk/drtv/se/spise-med-price_-pasta-selv_397445', + 'info_dict': { + 'id': '00212301010', + 'ext': 'mp4', + 'episode_number': 1, + 'title': 'Spise med Price: Pasta Selv', + 'alt_title': '1. Pasta Selv', + 'release_date': '20230807', + 'description': 'md5:2da9060524fed707810d71080b3d0cd8', + 'duration': 1750, + 'season': 'Spise med Price', + 'release_timestamp': 1691438400, + 'season_id': '397440', + 'episode': 'Spise med Price: Pasta Selv', + 'thumbnail': r're:https?://.+', + 'season_number': 15, + 'series': 'Spise med Price', + 'release_year': 2022, + 'subtitles': 'mincount:2', + }, + 'params': { + 'skip_download': 'm3u8', + }, + }, { + 'url': 'https://www.dr.dk/drtv/episode/bonderoeven_71769', + 'only_matching': True, + }, { + 'url': 'https://dr-massive.com/drtv/se/bonderoeven_71769', + 'only_matching': True, + }, { + 'url': 'https://www.dr.dk/drtv/program/jagten_220924', + 'only_matching': True, + }] + + SUBTITLE_LANGS = { + 'DanishLanguageSubtitles': 'da', + 'ForeignLanguageSubtitles': 'da_foreign', + 'CombinedLanguageSubtitles': 'da_combined', + } + + _TOKEN = None + + def _real_initialize(self): + if self._TOKEN: + return + + token_response = self._download_json( + 'https://isl.dr-massive.com/api/authorization/anonymous-sso', None, + note='Downloading anonymous token', headers={ + 'content-type': 'application/json', + }, query={ + 'device': 'phone_android', + 'lang': 'da', + 'supportFallbackToken': 'true', + }, data=json.dumps({ + 'deviceId': str(uuid.uuid4()), + 'scopes': ['Catalog'], + 'optout': True, + }).encode()) + + self._TOKEN = traverse_obj( + token_response, (lambda _, x: x['type'] == 'UserAccount', 'value', {str}), get_all=False) + if not self._TOKEN: + raise ExtractorError('Unable to get anonymous token') + + def _real_extract(self, url): + url_slug = self._match_id(url) + webpage = self._download_webpage(url, url_slug) + + json_data = self._search_json( + r'window\.__data\s*=', webpage, 'data', url_slug, fatal=False) or {} + item = traverse_obj( + json_data, ('cache', 'page', ..., (None, ('entries', 0)), 'item', {dict}), get_all=False) + if item: + item_id = item.get('id') + else: + item_id = url_slug.rsplit('_', 1)[-1] + item = self._download_json( + f'https://production-cdn.dr-massive.com/api/items/{item_id}', item_id, + note='Attempting to download backup item data', query={ + 'device': 'web_browser', + 'expand': 'all', + 'ff': 'idp,ldp,rpt', + 'geoLocation': 'dk', + 'isDeviceAbroad': 'false', + 'lang': 'da', + 'segments': 'drtv,optedout', + 'sub': 'Anonymous', + }) + + video_id = try_call(lambda: item['customId'].rsplit(':', 1)[-1]) or item_id + stream_data = self._download_json( + f'https://production.dr-massive.com/api/account/items/{item_id}/videos', video_id, + note='Downloading stream data', query={ + 'delivery': 'stream', + 'device': 'web_browser', + 'ff': 'idp,ldp,rpt', + 'lang': 'da', + 'resolution': 'HD-1080', + 'sub': 'Anonymous', + }, headers={'authorization': f'Bearer {self._TOKEN}'}) + + formats = [] + subtitles = {} + for stream in traverse_obj(stream_data, (lambda _, x: x['url'])): + format_id = stream.get('format', 'na') + access_service = stream.get('accessService') + preference = None + subtitle_suffix = '' + if access_service in ('SpokenSubtitles', 'SignLanguage', 'VisuallyInterpreted'): + preference = -1 + format_id += f'-{access_service}' + subtitle_suffix = f'-{access_service}' + elif access_service == 'StandardVideo': + preference = 1 + fmts, subs = self._extract_m3u8_formats_and_subtitles( + stream.get('url'), video_id, ext='mp4', preference=preference, m3u8_id=format_id, fatal=False) + formats.extend(fmts) + + api_subtitles = traverse_obj(stream, ('subtitles', lambda _, v: url_or_none(v['link']), {dict})) + if not api_subtitles: + self._merge_subtitles(subs, target=subtitles) + + for sub_track in api_subtitles: + lang = sub_track.get('language') or 'da' + subtitles.setdefault(self.SUBTITLE_LANGS.get(lang, lang) + subtitle_suffix, []).append({ + 'url': sub_track['link'], + 'ext': mimetype2ext(sub_track.get('format')) or 'vtt', + }) + + if not formats and traverse_obj(item, ('season', 'customFields', 'IsGeoRestricted')): + self.raise_geo_restricted(countries=self._GEO_COUNTRIES) + + return { + 'id': video_id, + 'formats': formats, + 'subtitles': subtitles, + **traverse_obj(item, { + 'title': 'title', + 'alt_title': 'contextualTitle', + 'description': 'description', + 'thumbnail': ('images', 'wallpaper'), + 'release_timestamp': ('customFields', 'BroadcastTimeDK', {parse_iso8601}), + 'duration': ('duration', {int_or_none}), + 'series': ('season', 'show', 'title'), + 'season': ('season', 'title'), + 'season_number': ('season', 'seasonNumber', {int_or_none}), + 'season_id': 'seasonId', + 'episode': 'episodeName', + 'episode_number': ('episodeNumber', {int_or_none}), + 'release_year': ('releaseYear', {int_or_none}), + }), + } + + +class DRTVLiveIE(InfoExtractor): + IE_NAME = 'drtv:live' + _VALID_URL = r'https?://(?:www\.)?dr\.dk/(?:tv|TV)/live/(?P[\da-z-]+)' + _GEO_COUNTRIES = ['DK'] + _TEST = { + 'url': 'https://www.dr.dk/tv/live/dr1', + 'info_dict': { + 'id': 'dr1', + 'ext': 'mp4', + 'title': 're:^DR1 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$', + }, + 'params': { + # m3u8 download + 'skip_download': True, + }, + } + + def _real_extract(self, url): + channel_id = self._match_id(url) + channel_data = self._download_json( + 'https://www.dr.dk/mu-online/api/1.0/channel/' + channel_id, + channel_id) + title = channel_data['Title'] + + formats = [] + for streaming_server in channel_data.get('StreamingServers', []): + server = streaming_server.get('Server') + if not server: + continue + link_type = streaming_server.get('LinkType') + for quality in streaming_server.get('Qualities', []): + for stream in quality.get('Streams', []): + stream_path = stream.get('Stream') + if not stream_path: + continue + stream_url = update_url_query( + f'{server}/{stream_path}', {'b': ''}) + if link_type == 'HLS': + formats.extend(self._extract_m3u8_formats( + stream_url, channel_id, 'mp4', + m3u8_id=link_type, fatal=False, live=True)) + elif link_type == 'HDS': + formats.extend(self._extract_f4m_formats(update_url_query( + f'{server}/{stream_path}', {'hdcore': '3.7.0'}), + channel_id, f4m_id=link_type, fatal=False)) + + return { + 'id': channel_id, + 'title': title, + 'thumbnail': channel_data.get('PrimaryImageUri'), + 'formats': formats, + 'is_live': True, + } + + +class DRTVSeasonIE(InfoExtractor): + IE_NAME = 'drtv:season' + _VALID_URL = r'https?://(?:www\.)?(?:dr\.dk|dr-massive\.com)/drtv/saeson/(?P[\w-]+)_(?P\d+)' + _GEO_COUNTRIES = ['DK'] + _TESTS = [{ + 'url': 'https://www.dr.dk/drtv/saeson/frank-and-kastaniegaarden_9008', + 'info_dict': { + 'id': '9008', + 'display_id': 'frank-and-kastaniegaarden', + 'title': 'Frank & Kastaniegaarden', + 'series': 'Frank & Kastaniegaarden', + 'season_number': 2008, + 'alt_title': 'Season 2008', + }, + 'playlist_mincount': 8, + }, { + 'url': 'https://www.dr.dk/drtv/saeson/frank-and-kastaniegaarden_8761', + 'info_dict': { + 'id': '8761', + 'display_id': 'frank-and-kastaniegaarden', + 'title': 'Frank & Kastaniegaarden', + 'series': 'Frank & Kastaniegaarden', + 'season_number': 2009, + 'alt_title': 'Season 2009', + }, + 'playlist_mincount': 19, + }] + + def _real_extract(self, url): + display_id, season_id = self._match_valid_url(url).group('display_id', 'id') + data = self._download_json(SERIES_API % f'/saeson/{display_id}_{season_id}', display_id) + + entries = [{ + '_type': 'url', + 'url': f'https://www.dr.dk/drtv{episode["path"]}', + 'ie_key': DRTVIE.ie_key(), + 'title': episode.get('title'), + 'alt_title': episode.get('contextualTitle'), + 'episode': episode.get('episodeName'), + 'description': episode.get('shortDescription'), + 'series': traverse_obj(data, ('entries', 0, 'item', 'title')), + 'season_number': traverse_obj(data, ('entries', 0, 'item', 'seasonNumber')), + 'episode_number': episode.get('episodeNumber'), + } for episode in traverse_obj(data, ('entries', 0, 'item', 'episodes', 'items'))] + + return { + '_type': 'playlist', + 'id': season_id, + 'display_id': display_id, + 'title': traverse_obj(data, ('entries', 0, 'item', 'title')), + 'alt_title': traverse_obj(data, ('entries', 0, 'item', 'contextualTitle')), + 'series': traverse_obj(data, ('entries', 0, 'item', 'title')), + 'entries': entries, + 'season_number': traverse_obj(data, ('entries', 0, 'item', 'seasonNumber')), + } + + +class DRTVSeriesIE(InfoExtractor): + IE_NAME = 'drtv:series' + _VALID_URL = r'https?://(?:www\.)?(?:dr\.dk|dr-massive\.com)/drtv/serie/(?P[\w-]+)_(?P\d+)' + _GEO_COUNTRIES = ['DK'] + _TESTS = [{ + 'url': 'https://www.dr.dk/drtv/serie/frank-and-kastaniegaarden_6954', + 'info_dict': { + 'id': '6954', + 'display_id': 'frank-and-kastaniegaarden', + 'title': 'Frank & Kastaniegaarden', + 'series': 'Frank & Kastaniegaarden', + 'alt_title': '', + }, + 'playlist_mincount': 15, + }] + + def _real_extract(self, url): + display_id, series_id = self._match_valid_url(url).group('display_id', 'id') + data = self._download_json(SERIES_API % f'/serie/{display_id}_{series_id}', display_id) + + entries = [{ + '_type': 'url', + 'url': f'https://www.dr.dk/drtv{season.get("path")}', + 'ie_key': DRTVSeasonIE.ie_key(), + 'title': season.get('title'), + 'alt_title': season.get('contextualTitle'), + 'series': traverse_obj(data, ('entries', 0, 'item', 'title')), + 'season_number': traverse_obj(data, ('entries', 0, 'item', 'seasonNumber')), + } for season in traverse_obj(data, ('entries', 0, 'item', 'show', 'seasons', 'items'))] + + return { + '_type': 'playlist', + 'id': series_id, + 'display_id': display_id, + 'title': traverse_obj(data, ('entries', 0, 'item', 'title')), + 'alt_title': traverse_obj(data, ('entries', 0, 'item', 'contextualTitle')), + 'series': traverse_obj(data, ('entries', 0, 'item', 'title')), + 'entries': entries, + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/dtube.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/dtube.py new file mode 100644 index 0000000000000000000000000000000000000000..2c47de8448c6f42c98cb11ab15f08a1f5231e201 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/dtube.py @@ -0,0 +1,79 @@ +import json + +from .common import InfoExtractor +from ..utils import ( + int_or_none, + parse_iso8601, +) + + +class DTubeIE(InfoExtractor): + _WORKING = False + _VALID_URL = r'https?://(?:www\.)?d\.tube/(?:#!/)?v/(?P[0-9a-z.-]+)/(?P[0-9a-z]{8})' + _TEST = { + 'url': 'https://d.tube/#!/v/broncnutz/x380jtr1', + 'md5': '9f29088fa08d699a7565ee983f56a06e', + 'info_dict': { + 'id': 'x380jtr1', + 'ext': 'mp4', + 'title': 'Lefty 3-Rings is Back Baby!! NCAA Picks', + 'description': 'md5:60be222088183be3a42f196f34235776', + 'uploader_id': 'broncnutz', + 'upload_date': '20190107', + 'timestamp': 1546854054, + }, + 'params': { + 'format': '480p', + }, + } + + def _real_extract(self, url): + uploader_id, video_id = self._match_valid_url(url).groups() + result = self._download_json('https://api.steemit.com/', video_id, data=json.dumps({ + 'jsonrpc': '2.0', + 'method': 'get_content', + 'params': [uploader_id, video_id], + }).encode())['result'] + + metadata = json.loads(result['json_metadata']) + video = metadata['video'] + content = video['content'] + info = video.get('info', {}) + title = info.get('title') or result['title'] + + def canonical_url(h): + if not h: + return None + return 'https://video.dtube.top/ipfs/' + h + + formats = [] + for q in ('240', '480', '720', '1080', ''): + video_url = canonical_url(content.get(f'video{q}hash')) + if not video_url: + continue + format_id = (q + 'p') if q else 'Source' + try: + self.to_screen(f'{video_id}: Checking {format_id} video format URL') + self._downloader._opener.open(video_url, timeout=5).close() + except TimeoutError: + self.to_screen( + f'{video_id}: {format_id} URL is invalid, skipping') + continue + formats.append({ + 'format_id': format_id, + 'url': video_url, + 'height': int_or_none(q), + 'ext': 'mp4', + }) + + return { + 'id': video_id, + 'title': title, + 'description': content.get('description'), + 'thumbnail': canonical_url(info.get('snaphash')), + 'tags': content.get('tags') or metadata.get('tags'), + 'duration': info.get('duration'), + 'formats': formats, + 'timestamp': parse_iso8601(result.get('created')), + 'uploader_id': uploader_id, + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/ebay.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/ebay.py new file mode 100644 index 0000000000000000000000000000000000000000..f1d122f8872fde5807d1788436c902b0197ac5d0 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/ebay.py @@ -0,0 +1,36 @@ +from .common import InfoExtractor +from ..utils import remove_end + + +class EbayIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?ebay\.com/itm/(?P\d+)' + _TESTS = [{ + 'url': 'https://www.ebay.com/itm/194509326719', + 'info_dict': { + 'id': '194509326719', + 'ext': 'mp4', + 'title': 'WiFi internal antenna adhesive for wifi 2.4GHz wifi 5 wifi 6 wifi 6E full bands', + }, + 'params': {'skip_download': 'm3u8'}, + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + webpage = self._download_webpage(url, video_id) + + video_json = self._search_json(r'"video":', webpage, 'video json', video_id) + + formats = [] + for key, url in video_json['playlistMap'].items(): + if key == 'HLS': + formats.extend(self._extract_m3u8_formats(url, video_id, fatal=False)) + elif key == 'DASH': + formats.extend(self._extract_mpd_formats(url, video_id, fatal=False)) + else: + self.report_warning(f'Unsupported format {key}', video_id) + + return { + 'id': video_id, + 'title': remove_end(self._html_extract_title(webpage), ' | eBay'), + 'formats': formats, + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/epicon.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/epicon.py new file mode 100644 index 0000000000000000000000000000000000000000..696f3e11f038b00e407c21f4cbf159fd159d73f0 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/epicon.py @@ -0,0 +1,116 @@ +import re + +from .common import InfoExtractor +from ..utils import ExtractorError + + +class EpiconIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?epicon\.in/(?:documentaries|movies|tv-shows/[^/?#]+/[^/?#]+)/(?P[^/?#]+)' + _TESTS = [{ + 'url': 'https://www.epicon.in/documentaries/air-battle-of-srinagar', + 'info_dict': { + 'id': 'air-battle-of-srinagar', + 'ext': 'mp4', + 'title': 'Air Battle of Srinagar', + 'description': 'md5:c4de2013af9bc05ae4392e4115d518d7', + 'thumbnail': r're:^https?://.*\.jpg$', + }, + }, { + 'url': 'https://www.epicon.in/movies/krit', + 'info_dict': { + 'id': 'krit', + 'ext': 'mp4', + 'title': 'Krit', + 'description': 'md5:c12b35dad915d48ccff7f013c79bab4a', + 'thumbnail': r're:^https?://.*\.jpg$', + }, + }, { + 'url': 'https://www.epicon.in/tv-shows/paapnaashini-ganga/season-1/vardaan', + 'info_dict': { + 'id': 'vardaan', + 'ext': 'mp4', + 'title': 'Paapnaashini Ganga - Season 1 - Ep 1 - VARDAAN', + 'description': 'md5:f517058c3d0402398eefa6242f4dd6ae', + 'thumbnail': r're:^https?://.*\.jpg$', + }, + }, { + 'url': 'https://www.epicon.in/movies/jayadev', + 'info_dict': { + 'id': 'jayadev', + 'ext': 'mp4', + 'title': 'Jayadev', + 'description': 'md5:09e349eecd8e585a3b6466904f19df6c', + 'thumbnail': r're:^https?://.*\.jpg$', + }, + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + webpage = self._download_webpage(url, video_id) + cid = self._search_regex(r'class=\"mylist-icon\ iconclick\"\ id=\"(\d+)', webpage, 'cid') + headers = {'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'} + data = f'cid={cid}&action=st&type=video'.encode() + data_json = self._parse_json( + self._download_json('https://www.epicon.in/ajaxplayer/', video_id, headers=headers, data=data), video_id) + + if not data_json['success']: + raise ExtractorError(data_json['message'], expected=True) + + title = self._search_regex(r'setplaytitle=\"([^\"]+)', webpage, 'title') + description = self._og_search_description(webpage) or None + thumbnail = self._og_search_thumbnail(webpage) or None + formats = self._extract_m3u8_formats(data_json['url']['video_url'], video_id) + + subtitles = {} + for subtitle in data_json.get('subtitles', []): + sub_url = subtitle.get('file') + if not sub_url: + continue + subtitles.setdefault(subtitle.get('lang', 'English'), []).append({ + 'url': self._proto_relative_url(sub_url), + }) + + return { + 'id': video_id, + 'formats': formats, + 'title': title, + 'description': description, + 'thumbnail': thumbnail, + 'subtitles': subtitles, + } + + +class EpiconSeriesIE(InfoExtractor): + _VALID_URL = r'(?!.*season)https?://(?:www\.)?epicon\.in/tv-shows/(?P[^/?#]+)' + _TESTS = [{ + 'url': 'https://www.epicon.in/tv-shows/1-of-something', + 'playlist_mincount': 5, + 'info_dict': { + 'id': '1-of-something', + }, + }, { + 'url': 'https://www.epicon.in/tv-shows/eco-india-english', + 'playlist_mincount': 76, + 'info_dict': { + 'id': 'eco-india-english', + }, + }, { + 'url': 'https://www.epicon.in/tv-shows/s/', + 'playlist_mincount': 25, + 'info_dict': { + 'id': 's', + }, + }, { + 'url': 'https://www.epicon.in/tv-shows/ekaant', + 'playlist_mincount': 38, + 'info_dict': { + 'id': 'ekaant', + }, + }] + + def _real_extract(self, url): + playlist_id = self._match_id(url) + webpage = self._download_webpage(url, playlist_id) + episodes = re.findall(rf'ct-tray-url=\"(tv-shows/{playlist_id}/[^\"]+)', webpage) + entries = [self.url_result(f'https://www.epicon.in/{episode}', EpiconIE) for episode in episodes] + return self.playlist_result(entries, playlist_id=playlist_id) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/erocast.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/erocast.py new file mode 100644 index 0000000000000000000000000000000000000000..bd22137bee52dcdd8ca5cb32a8d813aedae9f5c6 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/erocast.py @@ -0,0 +1,63 @@ +from .common import InfoExtractor +from ..utils import ( + int_or_none, + parse_iso8601, + str_or_none, + traverse_obj, + url_or_none, +) + + +class ErocastIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?erocast\.me/track/(?P[0-9]+)' + _TESTS = [{ + 'url': 'https://erocast.me/track/9787/f', + 'md5': 'af63b91f5f231096aba54dd682abea3b', + 'info_dict': { + 'id': '9787', + 'title': '[F4M] Your roommate, who is definitely not possessed by an alien, suddenly wants to fuck you', + 'url': 'https://erocast.s3.us-east-2.wasabisys.com/1220419/track.m3u8', + 'ext': 'm4a', + 'age_limit': 18, + 'release_timestamp': 1696178652, + 'release_date': '20231001', + 'modified_timestamp': int, + 'modified_date': str, + 'description': 'ExtraTerrestrial Tuesday!', + 'uploader': 'clarissaisshy', + 'uploader_id': '8113', + 'uploader_url': 'https://erocast.me/clarissaisshy', + 'thumbnail': 'https://erocast.s3.us-east-2.wasabisys.com/1220418/conversions/1696179247-lg.jpg', + 'duration': 2307, + 'view_count': int, + 'comment_count': int, + 'webpage_url': 'https://erocast.me/track/9787/f4m-your-roommate-who-is-definitely-not-possessed-by-an-alien-suddenly-wants-to-fuck-you', + }, + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + webpage = self._download_webpage(url, video_id) + data = self._search_json( + rf'') + + return { + 'id': video_id, + 'formats': self._extract_m3u8_formats( + data.get('file_url') or data['stream_url'], video_id, 'm4a', m3u8_id='hls'), + 'age_limit': 18, + **traverse_obj(data, { + 'title': ('title', {str}), + 'description': ('description', {str}), + 'release_timestamp': ('created_at', {parse_iso8601}), + 'modified_timestamp': ('updated_at', {parse_iso8601}), + 'uploader': ('user', 'name', {str}), + 'uploader_id': ('user', 'id', {str_or_none}), + 'uploader_url': ('user', 'permalink_url', {url_or_none}), + 'thumbnail': ('artwork_url', {url_or_none}), + 'duration': ('duration', {int_or_none}), + 'view_count': ('plays', {int_or_none}), + 'comment_count': ('comment_count', {int_or_none}), + 'webpage_url': ('permalink_url', {url_or_none}), + }), + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/euscreen.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/euscreen.py new file mode 100644 index 0000000000000000000000000000000000000000..f08938fc9b9b350f6f70488cb7d6e49bc00af93c --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/euscreen.py @@ -0,0 +1,59 @@ +from .common import InfoExtractor +from ..utils import ( + js_to_json, + parse_duration, +) + + +class EUScreenIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?euscreen\.eu/item.html\?id=(?P[^&?$/]+)' + + _TESTS = [{ + 'url': 'https://euscreen.eu/item.html?id=EUS_0EBCBF356BFC4E12A014023BA41BD98C', + 'info_dict': { + 'id': 'EUS_0EBCBF356BFC4E12A014023BA41BD98C', + 'ext': 'mp4', + 'title': "L'effondrement du stade du Heysel", + 'alt_title': 'Collapse of the Heysel Stadium', + 'duration': 318.0, + 'description': 'md5:f0ffffdfce6821139357a1b8359d6152', + 'series': 'JA2 DERNIERE', + 'episode': '-', + 'uploader': 'INA / France', + 'thumbnail': 'http://images3.noterik.com/domain/euscreenxl/user/eu_ina/video/EUS_0EBCBF356BFC4E12A014023BA41BD98C/image.jpg', + }, + 'params': {'skip_download': True}, + }] + + _payload = b'-1Win32MozillaNetscape5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36true784758undefinedSat, 07 Oct 2021 08:56:50 GMT1633769810758' + + def _real_extract(self, url): + video_id = self._match_id(url) + args_for_js_request = self._download_webpage( + 'https://euscreen.eu/lou/LouServlet/domain/euscreenxl/html5application/euscreenxlitem', + video_id, data=self._payload, query={'actionlist': 'itempage', 'id': video_id}) + info_js = self._download_webpage( + 'https://euscreen.eu/lou/LouServlet/domain/euscreenxl/html5application/euscreenxlitem', + video_id, data=args_for_js_request.replace('screenid', 'screenId').encode()) + video_json = self._parse_json( + self._search_regex(r'setVideo\(({.+})\)\(\$end\$\)put', info_js, 'Video JSON'), + video_id, transform_source=js_to_json) + meta_json = self._parse_json( + self._search_regex(r'setData\(({.+})\)\(\$end\$\)', info_js, 'Metadata JSON'), + video_id, transform_source=js_to_json) + formats = [{ + 'url': source['src'], + } for source in video_json.get('sources', [])] + + return { + 'id': video_id, + 'title': meta_json.get('originalTitle'), + 'alt_title': meta_json.get('title'), + 'duration': parse_duration(meta_json.get('duration')), + 'description': '{}\n{}'.format(meta_json.get('summaryOriginal', ''), meta_json.get('summaryEnglish', '')), + 'series': meta_json.get('series') or meta_json.get('seriesEnglish'), + 'episode': meta_json.get('episodeNumber'), + 'uploader': meta_json.get('provider'), + 'thumbnail': meta_json.get('screenshot') or video_json.get('screenshot'), + 'formats': formats, + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/faz.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/faz.py new file mode 100644 index 0000000000000000000000000000000000000000..796bac3c3173b12ccf5e8565e196d36fbfd9b74d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/faz.py @@ -0,0 +1,89 @@ +import re + +from .common import InfoExtractor +from ..compat import compat_etree_fromstring +from ..utils import ( + int_or_none, + xpath_element, + xpath_text, +) + + +class FazIE(InfoExtractor): + IE_NAME = 'faz.net' + _VALID_URL = r'https?://(?:www\.)?faz\.net/(?:[^/]+/)*.*?-(?P\d+)\.html' + + _TESTS = [{ + 'url': 'http://www.faz.net/multimedia/videos/stockholm-chemie-nobelpreis-fuer-drei-amerikanische-forscher-12610585.html', + 'info_dict': { + 'id': '12610585', + 'ext': 'mp4', + 'title': 'Stockholm: Chemie-Nobelpreis für drei amerikanische Forscher', + 'description': 'md5:1453fbf9a0d041d985a47306192ea253', + }, + }, { + 'url': 'http://www.faz.net/aktuell/politik/berlin-gabriel-besteht-zerreissprobe-ueber-datenspeicherung-13659345.html', + 'only_matching': True, + }, { + 'url': 'http://www.faz.net/berlin-gabriel-besteht-zerreissprobe-ueber-datenspeicherung-13659345.html', + 'only_matching': True, + }, { + 'url': 'http://www.faz.net/-13659345.html', + 'only_matching': True, + }, { + 'url': 'http://www.faz.net/aktuell/politik/-13659345.html', + 'only_matching': True, + }, { + 'url': 'http://www.faz.net/foobarblafasel-13659345.html', + 'only_matching': True, + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + + webpage = self._download_webpage(url, video_id) + description = self._og_search_description(webpage) + media = self._html_search_regex( + r"data-videojs-media='([^']+)", + webpage, 'media') + if media == 'extern': + perform_url = self._search_regex( + r"]+?src='((?:http:)?//player\.performgroup\.com/eplayer/eplayer\.html#/?[0-9a-f]{26}\.[0-9a-z]{26})", + webpage, 'perform url') + return self.url_result(perform_url) + config = compat_etree_fromstring(media) + + encodings = xpath_element(config, 'ENCODINGS', 'encodings', True) + formats = [] + for pref, code in enumerate(['LOW', 'HIGH', 'HQ']): + encoding = xpath_element(encodings, code) + if encoding is not None: + encoding_url = xpath_text(encoding, 'FILENAME') + if encoding_url: + tbr = xpath_text(encoding, 'AVERAGEBITRATE', 1000) + if tbr: + tbr = int_or_none(tbr.replace(',', '.')) + f = { + 'url': encoding_url, + 'format_id': code.lower(), + 'quality': pref, + 'tbr': tbr, + 'vcodec': xpath_text(encoding, 'CODEC'), + } + mobj = re.search(r'(\d+)x(\d+)_(\d+)\.mp4', encoding_url) + if mobj: + f.update({ + 'width': int(mobj.group(1)), + 'height': int(mobj.group(2)), + 'tbr': tbr or int(mobj.group(3)), + }) + formats.append(f) + + return { + 'id': video_id, + 'title': self._og_search_title(webpage), + 'formats': formats, + 'description': description.strip() if description else None, + 'thumbnail': xpath_text(config, 'STILL/STILL_BIG'), + 'duration': int_or_none(xpath_text(config, 'DURATION')), + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/fc2.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/fc2.py new file mode 100644 index 0000000000000000000000000000000000000000..aa6ff6335dcf52418c004d674941768d179376ed --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/fc2.py @@ -0,0 +1,299 @@ +import re +import urllib.parse + +from .common import InfoExtractor +from ..networking import Request +from ..utils import ( + ExtractorError, + UserNotLive, + js_to_json, + traverse_obj, + update_url_query, + urlencode_postdata, + urljoin, +) + + +class FC2IE(InfoExtractor): + _VALID_URL = r'(?:https?://video\.fc2\.com/(?:[^/]+/)*content/|fc2:)(?P[^/]+)' + IE_NAME = 'fc2' + _NETRC_MACHINE = 'fc2' + _TESTS = [{ + 'url': 'http://video.fc2.com/en/content/20121103kUan1KHs', + 'md5': 'a6ebe8ebe0396518689d963774a54eb7', + 'info_dict': { + 'id': '20121103kUan1KHs', + 'title': 'Boxing again with Puff', + 'ext': 'mp4', + 'thumbnail': r're:https?://.+\.jpe?g', + }, + 'params': { + 'skip_download': 'm3u8', + }, + }, { + # Direct video url + 'url': 'https://video.fc2.com/content/20121209FP73fxDx', + 'md5': '066bdb9b3a56a97f49cbf0d0b8a75a1f', + 'info_dict': { + 'id': '20121209FP73fxDx', + 'title': 'Farewelling The Wiggles Live in Sydney Dec 8 2012', + 'ext': 'mp4', + 'thumbnail': r're:https?://.+\.jpe?g', + 'description': 'Saying goodbye to the Wiggles at their Celebration Concert in Sydney, and what a concert that was!', + }, + }, { + 'url': 'http://video.fc2.com/en/content/20150125cEva0hDn/', + 'info_dict': { + 'id': '20150125cEva0hDn', + 'ext': 'mp4', + }, + 'params': { + 'username': 'ytdl@yt-dl.org', + 'password': '(snip)', + }, + 'skip': 'requires actual password', + }, { + 'url': 'http://video.fc2.com/en/a/content/20130926eZpARwsF', + 'only_matching': True, + }] + + def _login(self): + username, password = self._get_login_info() + if username is None or password is None: + return False + + # Log in + login_form_strs = { + 'email': username, + 'password': password, + 'done': 'video', + 'Submit': ' Login ', + } + + login_data = urlencode_postdata(login_form_strs) + request = Request( + 'https://secure.id.fc2.com/index.php?mode=login&switch_language=en', login_data) + + login_results = self._download_webpage(request, None, note='Logging in', errnote='Unable to log in') + if 'mode=redirect&login=done' not in login_results: + self.report_warning('unable to log in: bad username or password') + return False + + # this is also needed + login_redir = Request('http://id.fc2.com/?mode=redirect&login=done') + self._download_webpage( + login_redir, None, note='Login redirect', errnote='Login redirect failed') + + return True + + def _real_extract(self, url): + video_id = self._match_id(url) + self._login() + webpage = None + if not url.startswith('fc2:'): + webpage = self._download_webpage(url, video_id) + self.cookiejar.clear_session_cookies() # must clear + self._login() + + title, thumbnail, description = None, None, None + if webpage is not None: + title = self._html_search_regex( + (r'([^<]+?)', + r'\s+href="[^"]+"\s*title="([^"]+?)"\s*rel="nofollow">\s*\s*\1'), + webpage, + 'title', fatal=False) + thumbnail = self._og_search_thumbnail(webpage) + description = self._og_search_description(webpage, default=None) + + vidplaylist = self._download_json( + f'https://video.fc2.com/api/v3/videoplaylist/{video_id}?sh=1&fs=0', video_id, + note='Downloading info page') + vid_url = traverse_obj(vidplaylist, ('playlist', 'nq')) + if not vid_url: + raise ExtractorError('Unable to extract video URL') + vid_url = urljoin('https://video.fc2.com/', vid_url) + + return { + 'id': video_id, + 'title': title, + 'url': vid_url, + 'ext': 'mp4', + 'protocol': 'm3u8_native' if vidplaylist.get('type') == 2 else 'https', + 'description': description, + 'thumbnail': thumbnail, + } + + +class FC2EmbedIE(InfoExtractor): + _VALID_URL = r'https?://video\.fc2\.com/flv2\.swf\?(?P.+)' + IE_NAME = 'fc2:embed' + + _TEST = { + 'url': 'http://video.fc2.com/flv2.swf?t=201404182936758512407645&i=20130316kwishtfitaknmcgd76kjd864hso93htfjcnaogz629mcgfs6rbfk0hsycma7shkf85937cbchfygd74&i=201403223kCqB3Ez&d=2625&sj=11&lang=ja&rel=1&from=11&cmt=1&tk=TlRBM09EQTNNekU9&tl=プリズン・ブレイク%20S1-01%20マイケル%20【吹替】', + 'md5': 'b8aae5334cb691bdb1193a88a6ab5d5a', + 'info_dict': { + 'id': '201403223kCqB3Ez', + 'ext': 'flv', + 'title': 'プリズン・ブレイク S1-01 マイケル 【吹替】', + 'thumbnail': r're:^https?://.*\.jpg$', + }, + } + + def _real_extract(self, url): + mobj = self._match_valid_url(url) + query = urllib.parse.parse_qs(mobj.group('query')) + + video_id = query['i'][-1] + title = query.get('tl', [f'FC2 video {video_id}'])[0] + + sj = query.get('sj', [None])[0] + thumbnail = None + if sj: + # See thumbnailImagePath() in ServerConst.as of flv2.swf + thumbnail = 'http://video{}-thumbnail.fc2.com/up/pic/{}.jpg'.format( + sj, '/'.join((video_id[:6], video_id[6:8], video_id[-2], video_id[-1], video_id))) + + return { + '_type': 'url_transparent', + 'ie_key': FC2IE.ie_key(), + 'url': f'fc2:{video_id}', + 'title': title, + 'thumbnail': thumbnail, + } + + +class FC2LiveIE(InfoExtractor): + _VALID_URL = r'https?://live\.fc2\.com/(?P\d+)' + IE_NAME = 'fc2:live' + + _TESTS = [{ + 'url': 'https://live.fc2.com/57892267/', + 'info_dict': { + 'id': '57892267', + 'title': 'どこまで・・・', + 'uploader': 'あつあげ', + 'uploader_id': '57892267', + 'thumbnail': r're:https?://.+fc2.+', + }, + 'skip': 'livestream', + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + webpage = self._download_webpage(f'https://live.fc2.com/{video_id}/', video_id) + + self._set_cookie('live.fc2.com', 'js-player_size', '1') + + member_api = self._download_json( + 'https://live.fc2.com/api/memberApi.php', video_id, data=urlencode_postdata({ + 'channel': '1', + 'profile': '1', + 'user': '1', + 'streamid': video_id, + }), note='Requesting member info') + + control_server = self._download_json( + 'https://live.fc2.com/api/getControlServer.php', video_id, note='Downloading ControlServer data', + data=urlencode_postdata({ + 'channel_id': video_id, + 'mode': 'play', + 'orz': '', + 'channel_version': member_api['data']['channel_data']['version'], + 'client_version': '2.1.0\n [1]', + 'client_type': 'pc', + 'client_app': 'browser_hls', + 'ipv6': '', + }), headers={'X-Requested-With': 'XMLHttpRequest'}) + # A non-zero 'status' indicates the stream is not live, so check truthiness + if traverse_obj(control_server, ('status', {int})) and 'control_token' not in control_server: + raise UserNotLive(video_id=video_id) + self._set_cookie('live.fc2.com', 'l_ortkn', control_server['orz_raw']) + + ws_url = update_url_query(control_server['url'], {'control_token': control_server['control_token']}) + playlist_data = None + + ws = self._request_webpage(Request(ws_url, headers={ + 'Origin': 'https://live.fc2.com', + }), video_id, note='Fetching HLS playlist info via WebSocket') + + self.write_debug('Sending HLS server request') + + while True: + recv = ws.recv() + if not recv: + continue + data = self._parse_json(recv, video_id, fatal=False) + if not data or not isinstance(data, dict): + continue + + if data.get('name') == 'connect_complete': + break + ws.send(r'{"name":"get_hls_information","arguments":{},"id":1}') + + while True: + recv = ws.recv() + if not recv: + continue + data = self._parse_json(recv, video_id, fatal=False) + if not data or not isinstance(data, dict): + continue + if data.get('name') == '_response_' and data.get('id') == 1: + self.write_debug('Goodbye') + playlist_data = data + break + self.write_debug('Server said: {}{}'.format(recv[:100], '...' if len(recv) > 100 else '')) + + if not playlist_data: + raise ExtractorError('Unable to fetch HLS playlist info via WebSocket') + + formats = [] + for name, playlists in playlist_data['arguments'].items(): + if not isinstance(playlists, list): + continue + for pl in playlists: + if pl.get('status') == 0 and 'master_playlist' in pl.get('url'): + formats.extend(self._extract_m3u8_formats( + pl['url'], video_id, ext='mp4', m3u8_id=name, live=True, + headers={ + 'Origin': 'https://live.fc2.com', + 'Referer': url, + })) + + for fmt in formats: + fmt.update({ + 'protocol': 'fc2_live', + 'ws': ws, + }) + + title = self._html_search_meta(('og:title', 'twitter:title'), webpage, 'live title', fatal=False) + if not title: + title = self._html_extract_title(webpage, 'html title', fatal=False) + if title: + # remove service name in + title = re.sub(r'\s+-\s+.+$', '', title) + uploader = None + if title: + match = self._search_regex(r'^(.+?)\s*\[(.+?)\]$', title, 'title and uploader', default=None, group=(1, 2)) + if match and all(match): + title, uploader = match + + live_info_view = self._search_regex(r'(?s)liveInfoView\s*:\s*({.+?}),\s*premiumStateView', webpage, 'user info', fatal=False) or None + if live_info_view: + # remove jQuery code from object literal + live_info_view = re.sub(r'\$\(.+?\)[^,]+,', '"",', live_info_view) + live_info_view = self._parse_json(js_to_json(live_info_view), video_id) + + return { + 'id': video_id, + 'title': title or traverse_obj(live_info_view, 'title'), + 'description': self._html_search_meta( + ('og:description', 'twitter:description'), + webpage, 'live description', fatal=False) or traverse_obj(live_info_view, 'info'), + 'formats': formats, + 'uploader': uploader or traverse_obj(live_info_view, 'name'), + 'uploader_id': video_id, + 'thumbnail': traverse_obj(live_info_view, 'thumb'), + 'is_live': True, + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/fifa.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/fifa.py new file mode 100644 index 0000000000000000000000000000000000000000..e08b1140238543d1e700b4dcd2303912e503ee52 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/fifa.py @@ -0,0 +1,82 @@ +from .common import InfoExtractor +from ..utils import ( + int_or_none, + traverse_obj, + unified_timestamp, +) + + +class FifaIE(InfoExtractor): + _VALID_URL = r'https?://www\.fifa\.com/fifaplus/\w{2}/watch/([^#?]+/)?(?P<id>\w+)' + _TESTS = [{ + 'url': 'https://www.fifa.com/fifaplus/en/watch/7on10qPcnyLajDDU3ntg6y', + 'info_dict': { + 'id': '7on10qPcnyLajDDU3ntg6y', + 'title': 'Italy v France | Final | 2006 FIFA World Cup Germany™ | Full Match Replay', + 'description': 'md5:f4520d0ee80529c8ba4134a7d692ff8b', + 'ext': 'mp4', + 'categories': ['FIFA Tournaments'], + 'thumbnail': 'https://digitalhub.fifa.com/transform/135e2656-3a51-407b-8810-6c34bec5b59b/FMR_2006_Italy_France_Final_Hero', + 'duration': 8165, + 'release_timestamp': 1152403200, + 'release_date': '20060709', + }, + 'params': {'skip_download': 'm3u8'}, + }, { + 'url': 'https://www.fifa.com/fifaplus/pt/watch/1cg5r5Qt6Qt12ilkDgb1sV', + 'info_dict': { + 'id': '1cg5r5Qt6Qt12ilkDgb1sV', + 'title': 'Brazil v Germany | Semi-finals | 2014 FIFA World Cup Brazil™ | Extended Highlights', + 'description': 'md5:d908c74ee66322b804ae2e521b02a855', + 'ext': 'mp4', + 'categories': ['FIFA Tournaments', 'Highlights'], + 'thumbnail': 'https://digitalhub.fifa.com/transform/d8fe6f61-276d-4a73-a7fe-6878a35fd082/FIFAPLS_100EXTHL_2014BRAvGER_TMB', + 'duration': 902, + 'release_timestamp': 1404777600, + 'release_date': '20140708', + }, + 'params': {'skip_download': 'm3u8'}, + }, { + 'url': 'https://www.fifa.com/fifaplus/fr/watch/3C6gQH9C2DLwzNx7BMRQdp', + 'info_dict': { + 'id': '3C6gQH9C2DLwzNx7BMRQdp', + 'title': 'Josimar goal against Northern Ireland | Classic Goals', + 'description': 'md5:cbe7e7bb52f603c9f1fe9a4780fe983b', + 'ext': 'mp4', + 'categories': ['FIFA Tournaments', 'Goal'], + 'duration': 28, + 'thumbnail': 'https://digitalhub.fifa.com/transform/f9301391-f8d9-48b5-823e-c093ac5e3e11/CG_MEN_1986_JOSIMAR', + }, + 'params': {'skip_download': 'm3u8'}, + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + webpage = self._download_webpage(url, video_id) + + preconnect_link = self._search_regex( + r'<link\b[^>]+\brel\s*=\s*"preconnect"[^>]+href\s*=\s*"([^"]+)"', webpage, 'Preconnect Link') + + video_details = self._download_json( + f'{preconnect_link}/sections/videoDetails/{video_id}', video_id, 'Downloading Video Details', fatal=False) + + preplay_parameters = self._download_json( + f'{preconnect_link}/videoPlayerData/{video_id}', video_id, 'Downloading Preplay Parameters')['preplayParameters'] + + content_data = self._download_json( + 'https://content.uplynk.com/preplay/{contentId}/multiple.json?{queryStr}&sig={signature}'.format(**preplay_parameters), + video_id, 'Downloading Content Data') + + formats, subtitles = self._extract_m3u8_formats_and_subtitles(content_data['playURL'], video_id) + + return { + 'id': video_id, + 'title': video_details.get('title'), + 'description': video_details.get('description'), + 'duration': int_or_none(video_details.get('duration')), + 'release_timestamp': unified_timestamp(video_details.get('dateOfRelease')), + 'categories': traverse_obj(video_details, (('videoCategory', 'videoSubcategory'),)), + 'thumbnail': traverse_obj(video_details, ('backgroundImage', 'src')), + 'formats': formats, + 'subtitles': subtitles, + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/foxsports.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/foxsports.py new file mode 100644 index 0000000000000000000000000000000000000000..8e89ccf84154c39b1f0b564cb2e406ad1537202f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/foxsports.py @@ -0,0 +1,52 @@ +from .common import InfoExtractor +from .uplynk import UplynkPreplayIE +from ..networking import HEADRequest +from ..utils import float_or_none, make_archive_id, smuggle_url + + +class FoxSportsIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?foxsports\.com/watch/(?P<id>[\w-]+)' + _TESTS = [{ + 'url': 'https://www.foxsports.com/watch/play-612168c6700004b', + 'info_dict': { + 'id': 'b72f5bd8658140baa5791bb676433733', + 'ext': 'mp4', + 'display_id': 'play-612168c6700004b', + 'title': 'md5:e0c4ecac3a1f25295b4fae22fb5c126a', + 'description': 'md5:371bc43609708ae2b9e1a939229762af', + 'uploader_id': '06b4a36349624051a9ba52ac3a91d268', + 'upload_date': '20221205', + 'timestamp': 1670262586, + 'duration': 31.7317, + 'thumbnail': r're:^https?://.*\.jpg$', + 'extra_param_to_segment_url': str, + }, + 'params': { + 'skip_download': 'm3u8', + }, + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + webpage = self._download_webpage(url, video_id) + json_ld = self._search_json_ld(webpage, video_id, expected_type='VideoObject', default={}) + data = self._download_json( + f'https://api3.fox.com/v2.0/vodplayer/sportsclip/{video_id}', + video_id, note='Downloading API JSON', headers={ + 'x-api-key': 'cf289e299efdfa39fb6316f259d1de93', + }) + preplay_url = self._request_webpage( + HEADRequest(data['url']), video_id, 'Fetching preplay URL').url + + return { + '_type': 'url_transparent', + 'ie_key': UplynkPreplayIE.ie_key(), + 'url': smuggle_url(preplay_url, {'Origin': 'https://www.foxsports.com'}), + 'display_id': video_id, + 'title': data.get('name') or json_ld.get('title'), + 'description': data.get('description') or json_ld.get('description'), + 'duration': float_or_none(data.get('durationInSeconds')), + 'timestamp': json_ld.get('timestamp'), + 'thumbnails': json_ld.get('thumbnails'), + '_old_archive_ids': [make_archive_id(self, video_id)], + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/francaisfacile.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/francaisfacile.py new file mode 100644 index 0000000000000000000000000000000000000000..c432cf486cdf17ecba741186870e4277186e72ab --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/francaisfacile.py @@ -0,0 +1,76 @@ +import urllib.parse + +from .common import InfoExtractor +from ..utils import ( + float_or_none, + url_or_none, +) +from ..utils.traversal import traverse_obj + + +class FrancaisFacileIE(InfoExtractor): + _VALID_URL = r'https?://francaisfacile\.rfi\.fr/[a-z]{2}/(?:actualit%C3%A9|podcasts/[^/#?]+)/(?P<id>[^/#?]+)' + _TESTS = [{ + 'url': 'https://francaisfacile.rfi.fr/fr/actualit%C3%A9/20250305-r%C3%A9concilier-les-jeunes-avec-la-lecture-gr%C3%A2ce-aux-r%C3%A9seaux-sociaux', + 'md5': '4f33674cb205744345cc835991100afa', + 'info_dict': { + 'id': 'WBMZ58952-FLE-FR-20250305', + 'display_id': '20250305-réconcilier-les-jeunes-avec-la-lecture-grâce-aux-réseaux-sociaux', + 'title': 'Réconcilier les jeunes avec la lecture grâce aux réseaux sociaux', + 'url': 'https://aod-fle.akamaized.net/fle/sounds/fr/2025/03/05/6b6af52a-f9ba-11ef-a1f8-005056a97652.mp3', + 'ext': 'mp3', + 'description': 'md5:b903c63d8585bd59e8cc4d5f80c4272d', + 'duration': 103.15, + 'timestamp': 1741177984, + 'upload_date': '20250305', + }, + }, { + 'url': 'https://francaisfacile.rfi.fr/fr/actualit%C3%A9/20250307-argentine-le-sac-d-un-alpiniste-retrouv%C3%A9-40-ans-apr%C3%A8s-sa-mort', + 'md5': 'b8c3a63652d4ae8e8092dda5700c1cd9', + 'info_dict': { + 'id': 'WBMZ59102-FLE-FR-20250307', + 'display_id': '20250307-argentine-le-sac-d-un-alpiniste-retrouvé-40-ans-après-sa-mort', + 'title': 'Argentine: le sac d\'un alpiniste retrouvé 40 ans après sa mort', + 'url': 'https://aod-fle.akamaized.net/fle/sounds/fr/2025/03/07/8edf4082-fb46-11ef-8a37-005056bf762b.mp3', + 'ext': 'mp3', + 'description': 'md5:7fd088fbdf4a943bb68cf82462160dca', + 'duration': 117.74, + 'timestamp': 1741352789, + 'upload_date': '20250307', + }, + }, { + 'url': 'https://francaisfacile.rfi.fr/fr/podcasts/un-mot-une-histoire/20250317-le-mot-de-david-foenkinos-peut-%C3%AAtre', + 'md5': 'db83c2cc2589b4c24571c6b6cf14f5f1', + 'info_dict': { + 'id': 'WBMZ59441-FLE-FR-20250317', + 'display_id': '20250317-le-mot-de-david-foenkinos-peut-être', + 'title': 'Le mot de David Foenkinos: «peut-être» - Un mot, une histoire', + 'url': 'https://aod-fle.akamaized.net/fle/sounds/fr/2025/03/17/4ca6cbbe-0315-11f0-a85b-005056a97652.mp3', + 'ext': 'mp3', + 'description': 'md5:3fe35fae035803df696bfa7af2496e49', + 'duration': 198.96, + 'timestamp': 1742210897, + 'upload_date': '20250317', + }, + }] + + def _real_extract(self, url): + display_id = urllib.parse.unquote(self._match_id(url)) + webpage = self._download_webpage(url, display_id) + + data = self._search_json( + r'<script[^>]+\bdata-media-id=[^>]+\btype="application/json"[^>]*>', + webpage, 'audio data', display_id) + + return { + 'id': data['mediaId'], + 'display_id': display_id, + 'vcodec': 'none', + 'title': self._html_extract_title(webpage), + **self._search_json_ld(webpage, display_id, fatal=False), + **traverse_obj(data, { + 'title': ('title', {str}), + 'url': ('sources', ..., 'url', {url_or_none}, any), + 'duration': ('sources', ..., 'duration', {float_or_none}, any), + }), + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/frontendmasters.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/frontendmasters.py new file mode 100644 index 0000000000000000000000000000000000000000..b5176aa9b646cb3c4ed0848aed9d8ad205ba3cd6 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/frontendmasters.py @@ -0,0 +1,249 @@ +import re +import urllib.parse + +from .common import InfoExtractor +from ..utils import ( + ExtractorError, + parse_duration, + url_or_none, + urlencode_postdata, +) + + +class FrontendMastersBaseIE(InfoExtractor): + _API_BASE = 'https://api.frontendmasters.com/v1/kabuki' + _LOGIN_URL = 'https://frontendmasters.com/login/' + + _NETRC_MACHINE = 'frontendmasters' + + _QUALITIES = { + 'low': {'width': 480, 'height': 360}, + 'mid': {'width': 1280, 'height': 720}, + 'high': {'width': 1920, 'height': 1080}, + } + + def _perform_login(self, username, password): + login_page = self._download_webpage( + self._LOGIN_URL, None, 'Downloading login page') + + login_form = self._hidden_inputs(login_page) + + login_form.update({ + 'username': username, + 'password': password, + }) + + post_url = self._search_regex( + r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page, + 'post_url', default=self._LOGIN_URL, group='url') + + if not post_url.startswith('http'): + post_url = urllib.parse.urljoin(self._LOGIN_URL, post_url) + + response = self._download_webpage( + post_url, None, 'Logging in', data=urlencode_postdata(login_form), + headers={'Content-Type': 'application/x-www-form-urlencoded'}) + + # Successful login + if any(p in response for p in ( + 'wp-login.php?action=logout', '>Logout')): + return + + error = self._html_search_regex( + r'class=(["\'])(?:(?!\1).)*\bMessageAlert\b(?:(?!\1).)*\1[^>]*>(?P<error>[^<]+)<', + response, 'error message', default=None, group='error') + if error: + raise ExtractorError(f'Unable to login: {error}', expected=True) + raise ExtractorError('Unable to log in') + + +class FrontendMastersPageBaseIE(FrontendMastersBaseIE): + def _download_course(self, course_name, url): + return self._download_json( + f'{self._API_BASE}/courses/{course_name}', course_name, + 'Downloading course JSON', headers={'Referer': url}) + + @staticmethod + def _extract_chapters(course): + chapters = [] + lesson_elements = course.get('lessonElements') + if isinstance(lesson_elements, list): + chapters = [url_or_none(e) for e in lesson_elements if url_or_none(e)] + return chapters + + @staticmethod + def _extract_lesson(chapters, lesson_id, lesson): + title = lesson.get('title') or lesson_id + display_id = lesson.get('slug') + description = lesson.get('description') + thumbnail = lesson.get('thumbnail') + + chapter_number = None + index = lesson.get('index') + element_index = lesson.get('elementIndex') + if (isinstance(index, int) and isinstance(element_index, int) + and index < element_index): + chapter_number = element_index - index + chapter = (chapters[chapter_number - 1] + if chapter_number - 1 < len(chapters) else None) + + duration = None + timestamp = lesson.get('timestamp') + if isinstance(timestamp, str): + mobj = re.search( + r'(?P<start>\d{1,2}:\d{1,2}:\d{1,2})\s*-(?P<end>\s*\d{1,2}:\d{1,2}:\d{1,2})', + timestamp) + if mobj: + duration = parse_duration(mobj.group('end')) - parse_duration( + mobj.group('start')) + + return { + '_type': 'url_transparent', + 'url': f'frontendmasters:{lesson_id}', + 'ie_key': FrontendMastersIE.ie_key(), + 'id': lesson_id, + 'display_id': display_id, + 'title': title, + 'description': description, + 'thumbnail': thumbnail, + 'duration': duration, + 'chapter': chapter, + 'chapter_number': chapter_number, + } + + +class FrontendMastersIE(FrontendMastersBaseIE): + _VALID_URL = r'(?:frontendmasters:|https?://api\.frontendmasters\.com/v\d+/kabuki/video/)(?P<id>[^/]+)' + _TESTS = [{ + 'url': 'https://api.frontendmasters.com/v1/kabuki/video/a2qogef6ba', + 'md5': '7f161159710d6b7016a4f4af6fcb05e2', + 'info_dict': { + 'id': 'a2qogef6ba', + 'ext': 'mp4', + 'title': 'a2qogef6ba', + }, + 'skip': 'Requires FrontendMasters account credentials', + }, { + 'url': 'frontendmasters:a2qogef6ba', + 'only_matching': True, + }] + + def _real_extract(self, url): + lesson_id = self._match_id(url) + + source_url = f'{self._API_BASE}/video/{lesson_id}/source' + + formats = [] + for ext in ('webm', 'mp4'): + for quality in ('low', 'mid', 'high'): + resolution = self._QUALITIES[quality].copy() + format_id = f'{ext}-{quality}' + format_url = self._download_json( + source_url, lesson_id, + f'Downloading {format_id} source JSON', query={ + 'f': ext, + 'r': resolution['height'], + }, headers={ + 'Referer': url, + }, fatal=False)['url'] + + if not format_url: + continue + + f = resolution.copy() + f.update({ + 'url': format_url, + 'ext': ext, + 'format_id': format_id, + }) + formats.append(f) + + subtitles = { + 'en': [{ + 'url': f'{self._API_BASE}/transcripts/{lesson_id}.vtt', + }], + } + + return { + 'id': lesson_id, + 'title': lesson_id, + 'formats': formats, + 'subtitles': subtitles, + } + + +class FrontendMastersLessonIE(FrontendMastersPageBaseIE): + _VALID_URL = r'https?://(?:www\.)?frontendmasters\.com/courses/(?P<course_name>[^/]+)/(?P<lesson_name>[^/]+)' + _TEST = { + 'url': 'https://frontendmasters.com/courses/web-development/tools', + 'info_dict': { + 'id': 'a2qogef6ba', + 'display_id': 'tools', + 'ext': 'mp4', + 'title': 'Tools', + 'description': 'md5:82c1ea6472e88ed5acd1829fe992e4f7', + 'thumbnail': r're:^https?://.*\.jpg$', + 'chapter': 'Introduction', + 'chapter_number': 1, + }, + 'params': { + 'skip_download': True, + }, + 'skip': 'Requires FrontendMasters account credentials', + } + + def _real_extract(self, url): + mobj = self._match_valid_url(url) + course_name, lesson_name = mobj.group('course_name', 'lesson_name') + + course = self._download_course(course_name, url) + + lesson_id, lesson = next( + (video_id, data) + for video_id, data in course['lessonData'].items() + if data.get('slug') == lesson_name) + + chapters = self._extract_chapters(course) + return self._extract_lesson(chapters, lesson_id, lesson) + + +class FrontendMastersCourseIE(FrontendMastersPageBaseIE): + _VALID_URL = r'https?://(?:www\.)?frontendmasters\.com/courses/(?P<id>[^/]+)' + _TEST = { + 'url': 'https://frontendmasters.com/courses/web-development/', + 'info_dict': { + 'id': 'web-development', + 'title': 'Introduction to Web Development', + 'description': 'md5:9317e6e842098bf725d62360e52d49a6', + }, + 'playlist_count': 81, + 'skip': 'Requires FrontendMasters account credentials', + } + + @classmethod + def suitable(cls, url): + return False if FrontendMastersLessonIE.suitable(url) else super( + FrontendMastersBaseIE, cls).suitable(url) + + def _real_extract(self, url): + course_name = self._match_id(url) + + course = self._download_course(course_name, url) + + chapters = self._extract_chapters(course) + + lessons = sorted( + course['lessonData'].values(), key=lambda data: data['index']) + + entries = [] + for lesson in lessons: + lesson_name = lesson.get('slug') + lesson_id = lesson.get('hash') or lesson.get('statsId') + if not lesson_id or not lesson_name: + continue + entries.append(self._extract_lesson(chapters, lesson_id, lesson)) + + title = course.get('title') + description = course.get('description') + + return self.playlist_result(entries, course_name, title, description) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/fujitv.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/fujitv.py new file mode 100644 index 0000000000000000000000000000000000000000..3319b126811ac2bf8ffdce77850564386762daa5 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/fujitv.py @@ -0,0 +1,73 @@ +from .common import InfoExtractor +from ..networking import HEADRequest + + +class FujiTVFODPlus7IE(InfoExtractor): + _VALID_URL = r'https?://fod\.fujitv\.co\.jp/title/(?P<sid>[0-9a-z]{4})/(?P<id>[0-9a-z]+)' + _BASE_URL = 'https://i.fod.fujitv.co.jp/' + _BITRATE_MAP = { + 300: (320, 180), + 800: (640, 360), + 1200: (1280, 720), + 2000: (1280, 720), + 4000: (1920, 1080), + } + + _TESTS = [{ + 'url': 'https://fod.fujitv.co.jp/title/5d40/5d40110076', + 'info_dict': { + 'id': '5d40110076', + 'ext': 'ts', + 'title': '#1318 『まる子、まぼろしの洋館を見る』の巻', + 'series': 'ちびまる子ちゃん', + 'series_id': '5d40', + 'description': 'md5:b3f51dbfdda162ac4f789e0ff4d65750', + 'thumbnail': 'https://i.fod.fujitv.co.jp/img/program/5d40/episode/5d40110076_a.jpg', + }, + }, { + 'url': 'https://fod.fujitv.co.jp/title/5d40/5d40810083', + 'info_dict': { + 'id': '5d40810083', + 'ext': 'ts', + 'title': '#1324 『まる子とオニの子』の巻/『結成!2月をムダにしない会』の巻', + 'description': 'md5:3972d900b896adc8ab1849e310507efa', + 'series': 'ちびまる子ちゃん', + 'series_id': '5d40', + 'thumbnail': 'https://i.fod.fujitv.co.jp/img/program/5d40/episode/5d40810083_a.jpg'}, + 'skip': 'Video available only in one week', + }] + + def _real_extract(self, url): + series_id, video_id = self._match_valid_url(url).groups() + self._request_webpage(HEADRequest(url), video_id) + json_info = {} + token = self._get_cookies(url).get('CT') + if token: + json_info = self._download_json( + f'https://fod-sp.fujitv.co.jp/apps/api/episode/detail/?ep_id={video_id}&is_premium=false', + video_id, headers={'x-authorization': f'Bearer {token.value}'}, fatal=False) + else: + self.report_warning(f'The token cookie is needed to extract video metadata. {self._login_hint("cookies")}') + formats, subtitles = [], {} + src_json = self._download_json(f'{self._BASE_URL}abrjson_v2/tv_android/{video_id}', video_id) + for src in src_json['video_selector']: + if not src.get('url'): + continue + fmt, subs = self._extract_m3u8_formats_and_subtitles(src['url'], video_id, 'ts') + for f in fmt: + f.update(dict(zip(('height', 'width'), + self._BITRATE_MAP.get(f.get('tbr'), ()), strict=False))) + formats.extend(fmt) + subtitles = self._merge_subtitles(subtitles, subs) + + return { + 'id': video_id, + 'title': json_info.get('ep_title'), + 'series': json_info.get('lu_title'), + 'series_id': series_id, + 'description': json_info.get('ep_description'), + 'formats': formats, + 'subtitles': subtitles, + 'thumbnail': f'{self._BASE_URL}img/program/{series_id}/episode/{video_id}_a.jpg', + '_format_sort_fields': ('tbr', ), + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/funker530.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/funker530.py new file mode 100644 index 0000000000000000000000000000000000000000..5d59e9c9835ec238531625d3a629c3c833988e88 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/funker530.py @@ -0,0 +1,80 @@ +from .common import InfoExtractor +from .rumble import RumbleEmbedIE +from .youtube import YoutubeIE +from ..utils import ExtractorError, clean_html, get_element_by_class, strip_or_none + + +class Funker530IE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?funker530\.com/video/(?P<id>[^/?#]+)' + _TESTS = [{ + 'url': 'https://funker530.com/video/azov-patrol-caught-in-open-under-automatic-grenade-launcher-fire/', + 'md5': '085f50fea27523a388bbc22e123e09c8', + 'info_dict': { + 'id': 'v2qbmu4', + 'ext': 'mp4', + 'title': 'Azov Patrol Caught In Open Under Automatic Grenade Launcher Fire', + 'thumbnail': r're:^https?://.*\.jpg$', + 'uploader': 'Funker530', + 'channel': 'Funker530', + 'channel_url': 'https://rumble.com/c/c-1199543', + 'width': 1280, + 'height': 720, + 'fps': 25, + 'duration': 27, + 'upload_date': '20230608', + 'timestamp': 1686241321, + 'live_status': 'not_live', + 'description': 'md5:bea2e1f458095414e04b5ac189c2f980', + }, + }, { + 'url': 'https://funker530.com/video/my-friends-joined-the-russians-civdiv/', + 'md5': 'a42c2933391210662e93e867d7124b70', + 'info_dict': { + 'id': 'k-pk4bOvoac', + 'ext': 'mp4', + 'view_count': int, + 'channel': 'Civ Div', + 'comment_count': int, + 'channel_follower_count': int, + 'thumbnail': 'https://i.ytimg.com/vi/k-pk4bOvoac/maxresdefault.jpg', + 'uploader_id': '@CivDiv', + 'duration': 357, + 'channel_url': 'https://www.youtube.com/channel/UCgsCiwJ88up-YyMHo7hL5-A', + 'tags': [], + 'uploader_url': 'https://www.youtube.com/@CivDiv', + 'channel_id': 'UCgsCiwJ88up-YyMHo7hL5-A', + 'like_count': int, + 'description': 'md5:aef75ec3f59c07a0e39400f609b24429', + 'live_status': 'not_live', + 'age_limit': 0, + 'uploader': 'Civ Div', + 'categories': ['People & Blogs'], + 'title': 'My “Friends” joined the Russians.', + 'availability': 'public', + 'upload_date': '20230608', + 'playable_in_embed': True, + 'heatmap': 'count:100', + }, + }] + + def _real_extract(self, url): + display_id = self._match_id(url) + webpage = self._download_webpage(url, display_id) + info = {} + rumble_url = list(RumbleEmbedIE._extract_embed_urls(url, webpage)) + if rumble_url: + info = {'url': rumble_url[0], 'ie_key': RumbleEmbedIE.ie_key()} + else: + youtube_url = list(YoutubeIE._extract_embed_urls(url, webpage)) + if youtube_url: + info = {'url': youtube_url[0], 'ie_key': YoutubeIE.ie_key()} + if not info: + raise ExtractorError('No videos found on webpage', expected=True) + + return { + **info, + '_type': 'url_transparent', + 'description': strip_or_none(self._search_regex( + r'(?s)(.+)About the Author', clean_html(get_element_by_class('video-desc-paragraph', webpage)), + 'description', default=None)), + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/gaia.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/gaia.py new file mode 100644 index 0000000000000000000000000000000000000000..048ea517ba403f6e01fb5e43d38e2f8244bbb926 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/gaia.py @@ -0,0 +1,120 @@ +import urllib.parse + +from .common import InfoExtractor +from ..utils import ( + ExtractorError, + int_or_none, + str_or_none, + strip_or_none, + try_get, + urlencode_postdata, +) + + +class GaiaIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?gaia\.com/video/(?P<id>[^/?]+).*?\bfullplayer=(?P<type>feature|preview)' + _TESTS = [{ + 'url': 'https://www.gaia.com/video/connecting-universal-consciousness?fullplayer=feature', + 'info_dict': { + 'id': '89356', + 'ext': 'mp4', + 'title': 'Connecting with Universal Consciousness', + 'description': 'md5:844e209ad31b7d31345f5ed689e3df6f', + 'upload_date': '20151116', + 'timestamp': 1447707266, + 'duration': 936, + }, + 'params': { + # m3u8 download + 'skip_download': True, + }, + }, { + 'url': 'https://www.gaia.com/video/connecting-universal-consciousness?fullplayer=preview', + 'info_dict': { + 'id': '89351', + 'ext': 'mp4', + 'title': 'Connecting with Universal Consciousness', + 'description': 'md5:844e209ad31b7d31345f5ed689e3df6f', + 'upload_date': '20151116', + 'timestamp': 1447707266, + 'duration': 53, + }, + 'params': { + # m3u8 download + 'skip_download': True, + }, + }] + _NETRC_MACHINE = 'gaia' + _jwt = None + + def _real_initialize(self): + auth = self._get_cookies('https://www.gaia.com/').get('auth') + if auth: + auth = self._parse_json(urllib.parse.unquote(auth.value), None, fatal=False) + self._jwt = auth.get('jwt') + + def _perform_login(self, username, password): + if self._jwt: + return + auth = self._download_json( + 'https://auth.gaia.com/v1/login', + None, data=urlencode_postdata({ + 'username': username, + 'password': password, + })) + if auth.get('success') is False: + raise ExtractorError(', '.join(auth['messages']), expected=True) + self._jwt = auth.get('jwt') + + def _real_extract(self, url): + display_id, vtype = self._match_valid_url(url).groups() + node_id = self._download_json( + 'https://brooklyn.gaia.com/pathinfo', display_id, query={ + 'path': 'video/' + display_id, + })['id'] + node = self._download_json( + 'https://brooklyn.gaia.com/node/%d' % node_id, node_id) + vdata = node[vtype] + media_id = str(vdata['nid']) + title = node['title'] + + headers = None + if self._jwt: + headers = {'Authorization': 'Bearer ' + self._jwt} + media = self._download_json( + 'https://brooklyn.gaia.com/media/' + media_id, + media_id, headers=headers) + formats = self._extract_m3u8_formats( + media['mediaUrls']['bcHLS'], media_id, 'mp4') + + subtitles = {} + text_tracks = media.get('textTracks', {}) + for key in ('captions', 'subtitles'): + for lang, sub_url in text_tracks.get(key, {}).items(): + subtitles.setdefault(lang, []).append({ + 'url': sub_url, + }) + + fivestar = node.get('fivestar', {}) + fields = node.get('fields', {}) + + def get_field_value(key, value_key='value'): + return try_get(fields, lambda x: x[key][0][value_key]) + + return { + 'id': media_id, + 'display_id': display_id, + 'title': title, + 'formats': formats, + 'description': strip_or_none(get_field_value('body') or get_field_value('teaser')), + 'timestamp': int_or_none(node.get('created')), + 'subtitles': subtitles, + 'duration': int_or_none(vdata.get('duration')), + 'like_count': int_or_none(try_get(fivestar, lambda x: x['up_count']['value'])), + 'dislike_count': int_or_none(try_get(fivestar, lambda x: x['down_count']['value'])), + 'comment_count': int_or_none(node.get('comment_count')), + 'series': try_get(node, lambda x: x['series']['title'], str), + 'season_number': int_or_none(get_field_value('season')), + 'season_id': str_or_none(get_field_value('series_nid', 'nid')), + 'episode_number': int_or_none(get_field_value('episode')), + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/gamedevtv.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/gamedevtv.py new file mode 100644 index 0000000000000000000000000000000000000000..06e8b7356d6cb544539e11d850c28339d5ceb19f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/gamedevtv.py @@ -0,0 +1,141 @@ +import json + +from .common import InfoExtractor +from ..networking.exceptions import HTTPError +from ..utils import ( + ExtractorError, + clean_html, + int_or_none, + join_nonempty, + parse_iso8601, + str_or_none, + url_or_none, +) +from ..utils.traversal import traverse_obj + + +class GameDevTVDashboardIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?gamedev\.tv/dashboard/courses/(?P<course_id>\d+)(?:/(?P<lecture_id>\d+))?' + _NETRC_MACHINE = 'gamedevtv' + _TESTS = [{ + 'url': 'https://www.gamedev.tv/dashboard/courses/25', + 'info_dict': { + 'id': '25', + 'title': 'Complete Blender Creator 3: Learn 3D Modelling for Beginners', + 'tags': ['blender', 'course', 'all', 'box modelling', 'sculpting'], + 'categories': ['Blender', '3D Art'], + 'thumbnail': 'https://gamedev-files.b-cdn.net/courses/qisc9pmu1jdc.jpg', + 'upload_date': '20220516', + 'timestamp': 1652694420, + 'modified_date': '20241027', + 'modified_timestamp': 1730049658, + }, + 'playlist_count': 100, + }, { + 'url': 'https://www.gamedev.tv/dashboard/courses/63/2279', + 'info_dict': { + 'id': 'df04f4d8-68a4-4756-a71b-9ca9446c3a01', + 'ext': 'mp4', + 'modified_timestamp': 1701695752, + 'upload_date': '20230504', + 'episode': 'MagicaVoxel Community Course Introduction', + 'series_id': '63', + 'title': 'MagicaVoxel Community Course Introduction', + 'timestamp': 1683195397, + 'modified_date': '20231204', + 'categories': ['3D Art', 'MagicaVoxel'], + 'season': 'MagicaVoxel Community Course', + 'tags': ['MagicaVoxel', 'all', 'course'], + 'series': 'MagicaVoxel 3D Art Mini Course', + 'duration': 1405, + 'episode_number': 1, + 'season_number': 1, + 'season_id': '219', + 'description': 'md5:a378738c5bbec1c785d76c067652d650', + 'display_id': '63-219-2279', + 'alt_title': '1_CC_MVX MagicaVoxel Community Course Introduction.mp4', + 'thumbnail': 'https://vz-23691c65-6fa.b-cdn.net/df04f4d8-68a4-4756-a71b-9ca9446c3a01/thumbnail.jpg', + }, + }] + _API_HEADERS = {} + + def _perform_login(self, username, password): + try: + response = self._download_json( + 'https://api.gamedev.tv/api/students/login', None, 'Logging in', + headers={'Content-Type': 'application/json'}, + data=json.dumps({ + 'email': username, + 'password': password, + 'cart_items': [], + }).encode()) + except ExtractorError as e: + if isinstance(e.cause, HTTPError) and e.cause.status == 401: + raise ExtractorError('Invalid username/password', expected=True) + raise + + self._API_HEADERS['Authorization'] = f'{response["token_type"]} {response["access_token"]}' + + def _real_initialize(self): + if not self._API_HEADERS.get('Authorization'): + self.raise_login_required( + 'This content is only available with purchase', method='password') + + def _entries(self, data, course_id, course_info, selected_lecture): + for section in traverse_obj(data, ('sections', ..., {dict})): + section_info = traverse_obj(section, { + 'season_id': ('id', {str_or_none}), + 'season': ('title', {str}), + 'season_number': ('order', {int_or_none}), + }) + for lecture in traverse_obj(section, ('lectures', lambda _, v: url_or_none(v['video']['playListUrl']))): + if selected_lecture and str(lecture.get('id')) != selected_lecture: + continue + display_id = join_nonempty(course_id, section_info.get('season_id'), lecture.get('id')) + formats, subtitles = self._extract_m3u8_formats_and_subtitles( + lecture['video']['playListUrl'], display_id, 'mp4', m3u8_id='hls') + yield { + **course_info, + **section_info, + 'id': display_id, # fallback + 'display_id': display_id, + 'formats': formats, + 'subtitles': subtitles, + 'series': course_info.get('title'), + 'series_id': course_id, + **traverse_obj(lecture, { + 'id': ('video', 'guid', {str}), + 'title': ('title', {str}), + 'alt_title': ('video', 'title', {str}), + 'description': ('description', {clean_html}), + 'episode': ('title', {str}), + 'episode_number': ('order', {int_or_none}), + 'duration': ('video', 'duration_in_sec', {int_or_none}), + 'timestamp': ('video', 'created_at', {parse_iso8601}), + 'modified_timestamp': ('video', 'updated_at', {parse_iso8601}), + 'thumbnail': ('video', 'thumbnailUrl', {url_or_none}), + }), + } + + def _real_extract(self, url): + course_id, lecture_id = self._match_valid_url(url).group('course_id', 'lecture_id') + data = self._download_json( + f'https://api.gamedev.tv/api/courses/my/{course_id}', course_id, + headers=self._API_HEADERS)['data'] + + course_info = traverse_obj(data, { + 'title': ('title', {str}), + 'tags': ('tags', ..., 'name', {str}), + 'categories': ('categories', ..., 'title', {str}), + 'timestamp': ('created_at', {parse_iso8601}), + 'modified_timestamp': ('updated_at', {parse_iso8601}), + 'thumbnail': ('image', {url_or_none}), + }) + + entries = self._entries(data, course_id, course_info, lecture_id) + if lecture_id: + lecture = next(entries, None) + if not lecture: + raise ExtractorError('Lecture not found') + return lecture + return self.playlist_result(entries, course_id, **course_info) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/gamestar.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/gamestar.py new file mode 100644 index 0000000000000000000000000000000000000000..8e3b8a5da719dfd6192b156b085aa99e093cac57 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/gamestar.py @@ -0,0 +1,60 @@ +from .common import InfoExtractor +from ..utils import ( + int_or_none, + remove_end, +) + + +class GameStarIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?game(?P<site>pro|star)\.de/videos/.*,(?P<id>[0-9]+)\.html' + _TESTS = [{ + 'url': 'http://www.gamestar.de/videos/trailer,3/hobbit-3-die-schlacht-der-fuenf-heere,76110.html', + 'md5': 'ee782f1f8050448c95c5cacd63bc851c', + 'info_dict': { + 'id': '76110', + 'ext': 'mp4', + 'title': 'Hobbit 3: Die Schlacht der Fünf Heere - Teaser-Trailer zum dritten Teil', + 'description': 'Der Teaser-Trailer zu Hobbit 3: Die Schlacht der Fünf Heere zeigt einige Szenen aus dem dritten Teil der Saga und kündigt den...', + 'thumbnail': r're:^https?://.*\.jpg$', + 'timestamp': 1406542380, + 'upload_date': '20140728', + 'duration': 17, + }, + }, { + 'url': 'http://www.gamepro.de/videos/top-10-indie-spiele-fuer-nintendo-switch-video-tolle-nindies-games-zum-download,95316.html', + 'only_matching': True, + }, { + 'url': 'http://www.gamestar.de/videos/top-10-indie-spiele-fuer-nintendo-switch-video-tolle-nindies-games-zum-download,95316.html', + 'only_matching': True, + }] + + def _real_extract(self, url): + mobj = self._match_valid_url(url) + site = mobj.group('site') + video_id = mobj.group('id') + + webpage = self._download_webpage(url, video_id) + + # TODO: there are multiple ld+json objects in the webpage, + # while _search_json_ld finds only the first one + json_ld = self._parse_json(self._search_regex( + r'(?s)<script[^>]+type=(["\'])application/ld\+json\1[^>]*>(?P<json_ld>[^<]+VideoObject[^<]+)</script>', + webpage, 'JSON-LD', group='json_ld'), video_id) + info_dict = self._json_ld(json_ld, video_id) + info_dict['title'] = remove_end( + info_dict['title'], f' - Game{site.title()}') + + view_count = int_or_none(json_ld.get('interactionCount')) + comment_count = int_or_none(self._html_search_regex( + r'<span>Kommentare</span>\s*<span[^>]+class=["\']count[^>]+>\s*\(\s*([0-9]+)', + webpage, 'comment count', fatal=False)) + + info_dict.update({ + 'id': video_id, + 'url': 'http://gamestar.de/_misc/videos/portal/getVideoUrl.cfm?premium=0&videoId=' + video_id, + 'ext': 'mp4', + 'view_count': view_count, + 'comment_count': comment_count, + }) + + return info_dict diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/genius.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/genius.py new file mode 100644 index 0000000000000000000000000000000000000000..57c25e71ef5e6b8d3ea34948343b28344c63aa9f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/genius.py @@ -0,0 +1,145 @@ +from .common import InfoExtractor +from ..utils import ( + ExtractorError, + js_to_json, + smuggle_url, + str_or_none, + traverse_obj, + unescapeHTML, +) + + +class GeniusIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?genius\.com/(?:videos|(?P<article>a))/(?P<id>[^?/#]+)' + _TESTS = [{ + 'url': 'https://genius.com/videos/Vince-staples-breaks-down-the-meaning-of-when-sparks-fly', + 'md5': '64c2ad98cfafcfda23bfa0ad0c512f4c', + 'info_dict': { + 'id': '6313303597112', + 'ext': 'mp4', + 'title': 'Vince Staples Breaks Down The Meaning Of “When Sparks Fly”', + 'description': 'md5:bc15e00342c537c0039d414423ae5752', + 'tags': 'count:1', + 'uploader_id': '4863540648001', + 'duration': 388.416, + 'upload_date': '20221005', + 'timestamp': 1664982341, + 'thumbnail': r're:^https?://.*\.jpg$', + }, + }, { + 'url': 'https://genius.com/videos/Breaking-down-drakes-certified-lover-boy-kanye-beef-way-2-sexy-cudi', + 'md5': 'b8ed87a5efd1473bd027c20a969d4060', + 'info_dict': { + 'id': '6271792014001', + 'ext': 'mp4', + 'title': 'md5:c6355f7fa8a70bc86492a3963919fc15', + 'description': 'md5:1774638c31548b31b037c09e9b821393', + 'tags': 'count:3', + 'uploader_id': '4863540648001', + 'duration': 2685.099, + 'upload_date': '20210909', + 'timestamp': 1631209167, + 'thumbnail': r're:^https?://.*\.jpg$', + }, + }, { + 'url': 'https://genius.com/a/cordae-anderson-paak-break-down-the-meaning-of-two-tens', + 'md5': 'f98a4e03b16b0a2821bd6e52fb3cc9d7', + 'info_dict': { + 'id': '6321509903112', + 'ext': 'mp4', + 'title': 'Cordae & Anderson .Paak Breaks Down The Meaning Of “Two Tens”', + 'description': 'md5:1255f0e1161d07342ce56a8464ac339d', + 'tags': ['song id: 5457554'], + 'uploader_id': '4863540648001', + 'duration': 361.813, + 'upload_date': '20230301', + 'timestamp': 1677703908, + 'thumbnail': r're:^https?://.*\.jpg$', + }, + }] + + def _real_extract(self, url): + display_id, is_article = self._match_valid_url(url).group('id', 'article') + webpage = self._download_webpage(url, display_id) + + metadata = self._search_json( + r'<meta content="', webpage, 'metadata', display_id, + end_pattern=r'"\s+itemprop="page_data"', transform_source=unescapeHTML) + video_id = traverse_obj(metadata, ( + (('article', 'media', ...), ('video', None)), + ('provider_id', ('dfp_kv', lambda _, v: v['name'] == 'brightcove_video_id', 'values', ...))), + get_all=False) + if not video_id: + # Not all article pages have videos, expect the error + raise ExtractorError('Brightcove video ID not found in webpage', expected=bool(is_article)) + + config = self._search_json(r'var\s*APP_CONFIG\s*=', webpage, 'config', video_id, default={}) + account_id = config.get('brightcove_account_id', '4863540648001') + player_id = traverse_obj( + config, 'brightcove_standard_web_player_id', 'brightcove_standard_no_autoplay_web_player_id', + 'brightcove_modal_web_player_id', 'brightcove_song_story_web_player_id', default='S1ZcmcOC1x') + + return self.url_result( + smuggle_url( + f'https://players.brightcove.net/{account_id}/{player_id}_default/index.html?videoId={video_id}', + {'referrer': url}), 'BrightcoveNew', video_id) + + +class GeniusLyricsIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?genius\.com/(?P<id>[^?/#]+)-lyrics(?:[?/#]|$)' + _TESTS = [{ + 'url': 'https://genius.com/Lil-baby-heyy-lyrics', + 'playlist_mincount': 2, + 'info_dict': { + 'id': '8454545', + 'title': 'Heyy', + 'description': 'Heyy by Lil Baby', + }, + }, { + 'url': 'https://genius.com/Outkast-two-dope-boyz-in-a-cadillac-lyrics', + 'playlist_mincount': 1, + 'info_dict': { + 'id': '36239', + 'title': 'Two Dope Boyz (In a Cadillac)', + 'description': 'Two Dope Boyz (In a Cadillac) by OutKast', + }, + }, { + 'url': 'https://genius.com/Playboi-carti-rip-lyrics', + 'playlist_mincount': 1, + 'info_dict': { + 'id': '3710582', + 'title': 'R.I.P.', + 'description': 'R.I.P. by Playboi Carti', + }, + }] + + def _real_extract(self, url): + display_id = self._match_id(url) + webpage = self._download_webpage(url, display_id) + + json_string = self._search_json( + r'window\.__PRELOADED_STATE__\s*=\s*JSON\.parse\(', webpage, 'json string', + display_id, transform_source=js_to_json, contains_pattern=r'\'{(?s:.+)}\'') + song_info = self._parse_json(json_string, display_id) + song_id = str_or_none(traverse_obj(song_info, ('songPage', 'song'))) + if not song_id: + raise ExtractorError('Song id not found in webpage') + + title = traverse_obj( + song_info, ('songPage', 'trackingData', lambda _, x: x['key'] == 'Title', 'value'), + get_all=False, default='untitled') + artist = traverse_obj( + song_info, ('songPage', 'trackingData', lambda _, x: x['key'] == 'Primary Artist', 'value'), + get_all=False, default='unknown artist') + media = traverse_obj( + song_info, ('entities', 'songs', song_id, 'media'), expected_type=list, default=[]) + + entries = [] + for m in media: + if m.get('type') in ('video', 'audio') and m.get('url'): + if m.get('provider') == 'spotify': + self.to_screen(f'{song_id}: Skipping Spotify audio embed') + else: + entries.append(self.url_result(m['url'])) + + return self.playlist_result(entries, song_id, title, f'{title} by {artist}') diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/globalplayer.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/globalplayer.py new file mode 100644 index 0000000000000000000000000000000000000000..3d4a9304ca371c89752730b0b2be8071992756c6 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/globalplayer.py @@ -0,0 +1,254 @@ +from .common import InfoExtractor +from ..utils import ( + clean_html, + join_nonempty, + parse_duration, + str_or_none, + traverse_obj, + unified_strdate, + unified_timestamp, + urlhandle_detect_ext, +) + + +class GlobalPlayerBaseIE(InfoExtractor): + def _get_page_props(self, url, video_id): + webpage = self._download_webpage(url, video_id) + return self._search_nextjs_data(webpage, video_id)['props']['pageProps'] + + def _request_ext(self, url, video_id): + return urlhandle_detect_ext(self._request_webpage( # Server rejects HEAD requests + url, video_id, note='Determining source extension')) + + def _extract_audio(self, episode, series): + return { + 'vcodec': 'none', + **traverse_obj(series, { + 'series': 'title', + 'series_id': 'id', + 'thumbnail': 'imageUrl', + 'uploader': 'itunesAuthor', # podcasts only + }), + **traverse_obj(episode, { + 'id': 'id', + 'description': ('description', {clean_html}), + 'duration': ('duration', {parse_duration}), + 'thumbnail': 'imageUrl', + 'url': 'streamUrl', + 'timestamp': (('pubDate', 'startDate'), {unified_timestamp}), + 'title': 'title', + }, get_all=False), + } + + +class GlobalPlayerLiveIE(GlobalPlayerBaseIE): + _VALID_URL = r'https?://www\.globalplayer\.com/live/(?P<id>\w+)/\w+' + _TESTS = [{ + 'url': 'https://www.globalplayer.com/live/smoothchill/uk/', + 'info_dict': { + 'id': '2mx1E', + 'ext': 'aac', + 'display_id': 'smoothchill-uk', + 'title': 're:^Smooth Chill.+$', + 'thumbnail': 'https://herald.musicradio.com/media/f296ade8-50c9-4f60-911f-924e96873620.png', + 'description': 'Music To Chill To', + 'live_status': 'is_live', + }, + }, { + # national station + 'url': 'https://www.globalplayer.com/live/heart/uk/', + 'info_dict': { + 'id': '2mwx4', + 'ext': 'aac', + 'description': 'turn up the feel good!', + 'thumbnail': 'https://herald.musicradio.com/media/49b9e8cb-15bf-4bf2-8c28-a4850cc6b0f3.png', + 'live_status': 'is_live', + 'title': 're:^Heart UK.+$', + 'display_id': 'heart-uk', + }, + }, { + # regional variation + 'url': 'https://www.globalplayer.com/live/heart/london/', + 'info_dict': { + 'id': 'AMqg', + 'ext': 'aac', + 'thumbnail': 'https://herald.musicradio.com/media/49b9e8cb-15bf-4bf2-8c28-a4850cc6b0f3.png', + 'title': 're:^Heart London.+$', + 'live_status': 'is_live', + 'display_id': 'heart-london', + 'description': 'turn up the feel good!', + }, + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + station = self._get_page_props(url, video_id)['station'] + stream_url = station['streamUrl'] + + return { + 'id': station['id'], + 'display_id': join_nonempty('brandSlug', 'slug', from_dict=station) or station.get('legacyStationPrefix'), + 'url': stream_url, + 'ext': self._request_ext(stream_url, video_id), + 'vcodec': 'none', + 'is_live': True, + **traverse_obj(station, { + 'title': (('name', 'brandName'), {str_or_none}), + 'description': 'tagline', + 'thumbnail': 'brandLogo', + }, get_all=False), + } + + +class GlobalPlayerLivePlaylistIE(GlobalPlayerBaseIE): + _VALID_URL = r'https?://www\.globalplayer\.com/playlists/(?P<id>\w+)' + _TESTS = [{ + # "live playlist" + 'url': 'https://www.globalplayer.com/playlists/8bLk/', + 'info_dict': { + 'id': '8bLk', + 'ext': 'aac', + 'live_status': 'is_live', + 'description': 'md5:e10f5e10b01a7f2c14ba815509fbb38d', + 'thumbnail': 'https://images.globalplayer.com/images/551379?width=450&signature=oMLPZIoi5_dBSHnTMREW0Xg76mA=', + 'title': 're:^Classic FM Hall of Fame.+$', + }, + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + station = self._get_page_props(url, video_id)['playlistData'] + stream_url = station['streamUrl'] + + return { + 'id': video_id, + 'url': stream_url, + 'ext': self._request_ext(stream_url, video_id), + 'vcodec': 'none', + 'is_live': True, + **traverse_obj(station, { + 'title': 'title', + 'description': 'description', + 'thumbnail': 'image', + }), + } + + +class GlobalPlayerAudioIE(GlobalPlayerBaseIE): + _VALID_URL = r'https?://www\.globalplayer\.com/(?:(?P<podcast>podcasts)/|catchup/\w+/\w+/)(?P<id>\w+)/?(?:$|[?#])' + _TESTS = [{ + # podcast + 'url': 'https://www.globalplayer.com/podcasts/42KuaM/', + 'playlist_mincount': 5, + 'info_dict': { + 'id': '42KuaM', + 'title': 'Filthy Ritual', + 'thumbnail': 'md5:60286e7d12d795bd1bbc9efc6cee643e', + 'categories': ['Society & Culture', 'True Crime'], + 'uploader': 'Global', + 'description': 'md5:da5b918eac9ae319454a10a563afacf9', + }, + }, { + # radio catchup + 'url': 'https://www.globalplayer.com/catchup/lbc/uk/46vyD7z/', + 'playlist_mincount': 3, + 'info_dict': { + 'id': '46vyD7z', + 'description': 'Nick Ferrari At Breakfast is Leading Britain\'s Conversation.', + 'title': 'Nick Ferrari', + 'thumbnail': 'md5:4df24d8a226f5b2508efbcc6ae874ebf', + }, + }] + + def _real_extract(self, url): + video_id, podcast = self._match_valid_url(url).group('id', 'podcast') + props = self._get_page_props(url, video_id) + series = props['podcastInfo'] if podcast else props['catchupInfo'] + + return { + '_type': 'playlist', + 'id': video_id, + 'entries': [self._extract_audio(ep, series) for ep in traverse_obj( + series, ('episodes', lambda _, v: v['id'] and v['streamUrl']))], + 'categories': traverse_obj(series, ('categories', ..., 'name')) or None, + **traverse_obj(series, { + 'description': 'description', + 'thumbnail': 'imageUrl', + 'title': 'title', + 'uploader': 'itunesAuthor', # podcasts only + }), + } + + +class GlobalPlayerAudioEpisodeIE(GlobalPlayerBaseIE): + _VALID_URL = r'https?://www\.globalplayer\.com/(?:(?P<podcast>podcasts)|catchup/\w+/\w+)/episodes/(?P<id>\w+)/?(?:$|[?#])' + _TESTS = [{ + # podcast + 'url': 'https://www.globalplayer.com/podcasts/episodes/7DrfNnE/', + 'info_dict': { + 'id': '7DrfNnE', + 'ext': 'mp3', + 'title': 'Filthy Ritual - Trailer', + 'description': 'md5:1f1562fd0f01b4773b590984f94223e0', + 'thumbnail': 'md5:60286e7d12d795bd1bbc9efc6cee643e', + 'duration': 225.0, + 'timestamp': 1681254900, + 'series': 'Filthy Ritual', + 'series_id': '42KuaM', + 'upload_date': '20230411', + 'uploader': 'Global', + }, + }, { + # radio catchup + 'url': 'https://www.globalplayer.com/catchup/lbc/uk/episodes/2zGq26Vcv1fCWhddC4JAwETXWe/', + 'info_dict': { + 'id': '2zGq26Vcv1fCWhddC4JAwETXWe', + 'ext': 'm4a', + 'timestamp': 1682056800, + 'series': 'Nick Ferrari', + 'thumbnail': 'md5:4df24d8a226f5b2508efbcc6ae874ebf', + 'upload_date': '20230421', + 'series_id': '46vyD7z', + 'description': 'Nick Ferrari At Breakfast is Leading Britain\'s Conversation.', + 'title': 'Nick Ferrari', + 'duration': 10800.0, + }, + }] + + def _real_extract(self, url): + video_id, podcast = self._match_valid_url(url).group('id', 'podcast') + props = self._get_page_props(url, video_id) + episode = props['podcastEpisode'] if podcast else props['catchupEpisode'] + + return self._extract_audio( + episode, traverse_obj(episode, 'podcast', 'show', expected_type=dict) or {}) + + +class GlobalPlayerVideoIE(GlobalPlayerBaseIE): + _VALID_URL = r'https?://www\.globalplayer\.com/videos/(?P<id>\w+)' + _TESTS = [{ + 'url': 'https://www.globalplayer.com/videos/2JsSZ7Gm2uP/', + 'info_dict': { + 'id': '2JsSZ7Gm2uP', + 'ext': 'mp4', + 'description': 'md5:6a9f063c67c42f218e42eee7d0298bfd', + 'thumbnail': 'md5:d4498af48e15aae4839ce77b97d39550', + 'upload_date': '20230420', + 'title': 'Treble Malakai Bayoh sings a sublime Handel aria at Classic FM Live', + }, + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + meta = self._get_page_props(url, video_id)['videoData'] + + return { + 'id': video_id, + **traverse_obj(meta, { + 'url': 'url', + 'thumbnail': ('image', 'url'), + 'title': 'title', + 'upload_date': ('publish_date', {unified_strdate}), + 'description': 'description', + }), + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/gofile.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/gofile.py new file mode 100644 index 0000000000000000000000000000000000000000..e2144d7ecacfed8627f14649b1a779babe4424fc --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/gofile.py @@ -0,0 +1,104 @@ +import hashlib + +from .common import InfoExtractor +from ..utils import ExtractorError, try_get + + +class GofileIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?gofile\.io/d/(?P<id>[^/]+)' + _TESTS = [{ + 'url': 'https://gofile.io/d/AMZyDw', + 'info_dict': { + 'id': 'AMZyDw', + }, + 'playlist_mincount': 2, + 'playlist': [{ + 'info_dict': { + 'id': 'de571ac1-5edc-42e2-8ec2-bdac83ad4a31', + 'filesize': 928116, + 'ext': 'mp4', + 'title': 'nuuh', + 'release_timestamp': 1638338704, + 'release_date': '20211201', + }, + }], + }, { + 'url': 'https://gofile.io/d/is8lKr', + 'info_dict': { + 'id': 'TMjXd9', + 'ext': 'mp4', + }, + 'playlist_count': 0, + 'skip': 'No video/audio found at provided URL.', + }, { + 'url': 'https://gofile.io/d/TMjXd9', + 'info_dict': { + 'id': 'TMjXd9', + }, + 'playlist_count': 1, + }, { + 'url': 'https://gofile.io/d/gqOtRf', + 'info_dict': { + 'id': 'gqOtRf', + }, + 'playlist_mincount': 1, + 'params': { + 'videopassword': 'password', + }, + }] + _STATIC_TOKEN = '4fd6sg89d7s6' # From https://gofile.io/dist/js/config.js + _TOKEN = None + + def _real_initialize(self): + token = self._get_cookies('https://gofile.io/').get('accountToken') + if token: + self._TOKEN = token.value + return + + account_data = self._download_json( + 'https://api.gofile.io/accounts', None, 'Getting a new guest account', data=b'{}') + self._TOKEN = account_data['data']['token'] + self._set_cookie('.gofile.io', 'accountToken', self._TOKEN) + + def _entries(self, file_id): + query_params = {} + if password := self.get_param('videopassword'): + query_params['password'] = hashlib.sha256(password.encode()).hexdigest() + + files = self._download_json( + f'https://api.gofile.io/contents/{file_id}', file_id, 'Getting filelist', + query=query_params, headers={ + 'Authorization': f'Bearer {self._TOKEN}', + 'X-Website-Token': self._STATIC_TOKEN, + }) + + status = files['status'] + if status == 'error-passwordRequired': + raise ExtractorError( + 'This video is protected by a password, use the --video-password option', expected=True) + elif status != 'ok': + raise ExtractorError(f'{self.IE_NAME} said: status {status}', expected=True) + + found_files = False + for file in (try_get(files, lambda x: x['data']['children'], dict) or {}).values(): + file_type, file_format = file.get('mimetype').split('/', 1) + if file_type not in ('video', 'audio') and file_format != 'vnd.mts': + continue + + found_files = True + file_url = file.get('link') + if file_url: + yield { + 'id': file['id'], + 'title': file['name'].rsplit('.', 1)[0], + 'url': file_url, + 'filesize': file.get('size'), + 'release_timestamp': file.get('createTime'), + } + + if not found_files: + raise ExtractorError('No video/audio found at provided URL.', expected=True) + + def _real_extract(self, url): + file_id = self._match_id(url) + return self.playlist_result(self._entries(file_id), playlist_id=file_id) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/hearthisat.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/hearthisat.py new file mode 100644 index 0000000000000000000000000000000000000000..eb0a77952ea627f2dfdc4f3c4e3f0b968f3cbc08 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/hearthisat.py @@ -0,0 +1,130 @@ +from .common import InfoExtractor +from ..utils import ( + KNOWN_EXTENSIONS, + determine_ext, + str_to_int, +) + + +class HearThisAtIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?hearthis\.at/(?P<artist>[^/?#]+)/(?P<title>[\w.-]+)' + _PLAYLIST_URL = 'https://hearthis.at/playlist.php' + _TESTS = [{ + 'url': 'https://hearthis.at/moofi/dr-kreep', + 'md5': 'ab6ec33c8fed6556029337c7885eb4e0', + 'info_dict': { + 'id': '150939', + 'display_id': 'moofi - dr-kreep', + 'ext': 'wav', + 'title': 'Moofi - Dr. Kreep', + 'thumbnail': r're:^https?://.*\.jpg$', + 'timestamp': 1421564134, + 'description': 'md5:1adb0667b01499f9d27e97ddfd53852a', + 'upload_date': '20150118', + 'view_count': int, + 'duration': 70, + 'genres': ['Experimental'], + }, + }, { + # 'download' link redirects to the original webpage + 'url': 'https://hearthis.at/twitchsf/dj-jim-hopkins-totally-bitchin-80s-dance-mix/', + 'md5': '5980ceb7c461605d30f1f039df160c6e', + 'info_dict': { + 'id': '811296', + 'display_id': 'twitchsf - dj-jim-hopkins-totally-bitchin-80s-dance-mix', + 'ext': 'mp3', + 'title': 'TwitchSF - DJ Jim Hopkins - Totally Bitchin\' 80\'s Dance Mix!', + 'description': 'md5:ef26815ca8f483272a87b137ff175be2', + 'upload_date': '20160328', + 'timestamp': 1459186146, + 'thumbnail': r're:^https?://.*\.jpg$', + 'view_count': int, + 'duration': 4360, + 'genres': ['Dance'], + }, + }, { + 'url': 'https://hearthis.at/tindalos/0001-tindalos-gnrique/eQd/', + 'md5': 'cd08e51911f147f6da2d9678905b0bd9', + 'info_dict': { + 'id': '2685222', + 'ext': 'mp3', + 'duration': 86, + 'view_count': int, + 'timestamp': 1545471670, + 'display_id': 'tindalos - 0001-tindalos-gnrique', + 'thumbnail': r're:^https?://.*\.jpg$', + 'genres': ['Other'], + 'title': 'Tindalos - Tindalos - générique n°1', + 'description': '', + 'upload_date': '20181222', + }, + }, { + 'url': 'https://hearthis.at/sithi2/biochip-c-classics-set-wolle-xdp-tresor.core-special-tresor-globus-berlin-13.07.20011/', + 'md5': 'b45ac60f0c8111eef6ddc10ec232e312', + 'info_dict': { + 'id': '7145959', + 'ext': 'mp3', + 'description': 'md5:d7ae36a453d78903f6b7ed6eb2fce1f2', + 'duration': 8986, + 'thumbnail': r're:^https?://.*\.jpg$', + 'title': 'md5:62669ce5b1b67f45c6f846033f37d3b9', + 'timestamp': 1588699409, + 'display_id': 'sithi2 - biochip-c-classics-set-wolle-xdp-tresor.core-special-tresor-globus-berlin-13.07.20011', + 'view_count': int, + 'upload_date': '20200505', + 'genres': ['Other'], + }, + }] + + def _real_extract(self, url): + m = self._match_valid_url(url) + display_id = '{artist:s} - {title:s}'.format(**m.groupdict()) + api_url = url.replace('www.', '').replace('hearthis.at', 'api-v2.hearthis.at') + data_json = self._download_json(api_url, display_id) + track_id = data_json.get('id') + artist_json = data_json.get('user') + title = '{} - {}'.format(artist_json.get('username'), data_json.get('title')) + genre = data_json.get('genre') + description = data_json.get('description') + thumbnail = data_json.get('artwork_url') or data_json.get('thumb') + view_count = str_to_int(data_json.get('playback_count')) + duration = str_to_int(data_json.get('duration')) + timestamp = data_json.get('release_timestamp') + + formats = [] + mp3_url = data_json.get('stream_url') + + if mp3_url: + formats.append({ + 'format_id': 'mp3', + 'vcodec': 'none', + 'acodec': 'mp3', + 'url': mp3_url, + 'ext': 'mp3', + }) + + if data_json.get('download_url'): + download_url = data_json['download_url'] + ext = determine_ext(data_json['download_filename']) + if ext in KNOWN_EXTENSIONS: + formats.append({ + 'format_id': ext, + 'vcodec': 'none', + 'ext': ext, + 'url': download_url, + 'acodec': ext, + 'quality': 2, # Usually better quality + }) + + return { + 'id': track_id, + 'display_id': display_id, + 'title': title, + 'formats': formats, + 'thumbnail': thumbnail, + 'description': description, + 'duration': duration, + 'timestamp': timestamp, + 'view_count': view_count, + 'genre': genre, + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/hypergryph.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/hypergryph.py new file mode 100644 index 0000000000000000000000000000000000000000..f405d14b540800f6fe9c2b0a8eb76eb8b45d2bc3 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/hypergryph.py @@ -0,0 +1,66 @@ +from .common import InfoExtractor +from ..utils import ( + ExtractorError, + clean_html, + url_or_none, +) +from ..utils.traversal import subs_list_to_dict, traverse_obj + + +class MonsterSirenHypergryphMusicIE(InfoExtractor): + IE_NAME = 'monstersiren' + IE_DESC = '塞壬唱片' + _API_BASE = 'https://monster-siren.hypergryph.com/api' + _VALID_URL = r'https?://monster-siren\.hypergryph\.com/music/(?P<id>\d+)' + _TESTS = [{ + 'url': 'https://monster-siren.hypergryph.com/music/514562', + 'info_dict': { + 'id': '514562', + 'ext': 'wav', + 'title': 'Flame Shadow', + 'album': 'Flame Shadow', + 'artists': ['塞壬唱片-MSR'], + 'description': 'md5:19e2acfcd1b65b41b29e8079ab948053', + 'thumbnail': r're:https?://web\.hycdn\.cn/siren/pic/.+\.jpg', + }, + }, { + 'url': 'https://monster-siren.hypergryph.com/music/514518', + 'info_dict': { + 'id': '514518', + 'ext': 'wav', + 'title': 'Heavenly Me (Instrumental)', + 'album': 'Heavenly Me', + 'artists': ['塞壬唱片-MSR', 'AIYUE blessed : 理名'], + 'description': 'md5:ce790b41c932d1ad72eb791d1d8ae598', + 'thumbnail': r're:https?://web\.hycdn\.cn/siren/pic/.+\.jpg', + }, + }] + + def _real_extract(self, url): + audio_id = self._match_id(url) + song = self._download_json(f'{self._API_BASE}/song/{audio_id}', audio_id) + if traverse_obj(song, 'code') != 0: + msg = traverse_obj(song, ('msg', {str}, filter)) + raise ExtractorError( + msg or 'API returned an error response', expected=bool(msg)) + + album = None + if album_id := traverse_obj(song, ('data', 'albumCid', {str})): + album = self._download_json( + f'{self._API_BASE}/album/{album_id}/detail', album_id, fatal=False) + + return { + 'id': audio_id, + 'vcodec': 'none', + **traverse_obj(song, ('data', { + 'title': ('name', {str}), + 'artists': ('artists', ..., {str}), + 'subtitles': ({'url': 'lyricUrl'}, all, {subs_list_to_dict(lang='en')}), + 'url': ('sourceUrl', {url_or_none}), + })), + **traverse_obj(album, ('data', { + 'album': ('name', {str}), + 'description': ('intro', {clean_html}), + 'thumbnail': ('coverUrl', {url_or_none}), + })), + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/idolplus.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/idolplus.py new file mode 100644 index 0000000000000000000000000000000000000000..3c905b071234ffd5f7ee5f4db9544fbb01684969 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/idolplus.py @@ -0,0 +1,115 @@ +from .common import InfoExtractor +from ..utils import traverse_obj, try_call, url_or_none + + +class IdolPlusIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?idolplus\.com/z[us]/(?:concert/|contents/?\?(?:[^#]+&)?albumId=)(?P<id>\w+)' + _TESTS = [{ + 'url': 'https://idolplus.com/zs/contents?albumId=M012077298PPV00', + 'md5': '2ace3f4661c943a2f7e79f0b88cea1e7', + 'info_dict': { + 'id': 'M012077298PPV00', + 'ext': 'mp4', + 'title': '[MultiCam] Aegyo on Top of Aegyo (IZ*ONE EATING TRIP)', + 'release_date': '20200707', + 'formats': 'count:65', + }, + 'params': {'format': '532-KIM_MINJU'}, + }, { + 'url': 'https://idolplus.com/zs/contents?albumId=M01232H058PPV00&catId=E9TX5', + 'info_dict': { + 'id': 'M01232H058PPV00', + 'ext': 'mp4', + 'title': 'YENA (CIRCLE CHART MUSIC AWARDS 2022 RED CARPET)', + 'release_date': '20230218', + 'formats': 'count:5', + }, + 'params': {'skip_download': 'm3u8'}, + }, { + # live stream + 'url': 'https://idolplus.com/zu/contents?albumId=M012323174PPV00', + 'info_dict': { + 'id': 'M012323174PPV00', + 'ext': 'mp4', + 'title': 'Hanteo Music Awards 2022 DAY2', + 'release_date': '20230211', + 'formats': 'count:5', + }, + 'params': {'skip_download': 'm3u8'}, + }, { + 'url': 'https://idolplus.com/zs/concert/M012323039PPV00', + 'info_dict': { + 'id': 'M012323039PPV00', + 'ext': 'mp4', + 'title': 'CIRCLE CHART MUSIC AWARDS 2022', + 'release_date': '20230218', + 'formats': 'count:5', + }, + 'params': {'skip_download': 'm3u8'}, + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + data_list = traverse_obj(self._download_json( + 'https://idolplus.com/api/zs/viewdata/ruleset/build', video_id, + headers={'App_type': 'web', 'Country_Code': 'KR'}, query={ + 'rulesetId': 'contents', + 'albumId': video_id, + 'distribute': 'PRD', + 'loggedIn': 'false', + 'region': 'zs', + 'countryGroup': '00010', + 'lang': 'en', + 'saId': '999999999998', + }), ('data', 'viewData', ...)) + + player_data = {} + while data_list: + player_data = data_list.pop() + if traverse_obj(player_data, 'type') == 'player': + break + elif traverse_obj(player_data, ('dataList', ...)): + data_list += player_data['dataList'] + + formats = self._extract_m3u8_formats(traverse_obj(player_data, ( + 'vodPlayerList', 'vodProfile', 0, 'vodServer', 0, 'video_url', {url_or_none})), video_id) + + subtitles = {} + for caption in traverse_obj(player_data, ('vodPlayerList', 'caption')) or []: + subtitles.setdefault(caption.get('lang') or 'und', []).append({ + 'url': caption.get('smi_url'), + 'ext': 'vtt', + }) + + # Add member multicams as alternative formats + if (traverse_obj(player_data, ('detail', 'has_cuesheet')) == 'Y' + and traverse_obj(player_data, ('detail', 'is_omni_member')) == 'Y'): + cuesheet = traverse_obj(self._download_json( + 'https://idolplus.com/gapi/contents/v1.0/content/cuesheet', video_id, + 'Downloading JSON metadata for member multicams', + headers={'App_type': 'web', 'Country_Code': 'KR'}, query={ + 'ALBUM_ID': video_id, + 'COUNTRY_GRP': '00010', + 'LANG': 'en', + 'SA_ID': '999999999998', + 'COUNTRY_CODE': 'KR', + }), ('data', 'cuesheet_item', 0)) + + for member in traverse_obj(cuesheet, ('members', ...)): + index = try_call(lambda: int(member['omni_view_index']) - 1) + member_video_url = traverse_obj(cuesheet, ('omni_view', index, 'cdn_url', 0, 'url', {url_or_none})) + if not member_video_url: + continue + member_formats = self._extract_m3u8_formats( + member_video_url, video_id, note=f'Downloading m3u8 for multicam {member["name"]}') + for mf in member_formats: + mf['format_id'] = f'{mf["format_id"]}-{member["name"].replace(" ", "_")}' + formats.extend(member_formats) + + return { + 'id': video_id, + 'title': traverse_obj(player_data, ('detail', 'albumName')), + 'formats': formats, + 'subtitles': subtitles, + 'release_date': traverse_obj(player_data, ('detail', 'broadcastDate')), + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/ilpost.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/ilpost.py new file mode 100644 index 0000000000000000000000000000000000000000..da203cf5ff23c3f031b3272265d4633965bbbd75 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/ilpost.py @@ -0,0 +1,68 @@ + +from .common import InfoExtractor +from ..utils import ( + ExtractorError, + float_or_none, + int_or_none, + url_or_none, + urlencode_postdata, +) +from ..utils.traversal import traverse_obj + + +class IlPostIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?ilpost\.it/episodes/(?P<id>[^/?#]+)' + _TESTS = [{ + 'url': 'https://www.ilpost.it/episodes/1-avis-akvasas-ka/', + 'md5': '43649f002d85e1c2f319bb478d479c40', + 'info_dict': { + 'id': '2972047', + 'ext': 'mp3', + 'display_id': '1-avis-akvasas-ka', + 'title': '1. Avis akvasas ka', + 'url': 'https://www.ilpost.it/wp-content/uploads/2023/12/28/1703781217-l-invasione-pt1-v6.mp3', + 'timestamp': 1703835014, + 'upload_date': '20231229', + 'duration': 2495.0, + 'availability': 'public', + 'series_id': '235598', + 'description': '', + }, + }] + + def _real_extract(self, url): + display_id = self._match_id(url) + webpage = self._download_webpage(url, display_id) + + endpoint_metadata = self._search_json( + r'var\s+ilpostpodcast\s*=', webpage, 'metadata', display_id) + episode_id = endpoint_metadata['post_id'] + podcast_id = endpoint_metadata['podcast_id'] + podcast_metadata = self._download_json( + endpoint_metadata['ajax_url'], display_id, data=urlencode_postdata({ + 'action': 'checkpodcast', + 'cookie': endpoint_metadata['cookie'], + 'post_id': episode_id, + 'podcast_id': podcast_id, + })) + + episode = traverse_obj(podcast_metadata, ( + 'data', 'postcastList', lambda _, v: str(v['id']) == episode_id, {dict}), get_all=False) + if not episode: + raise ExtractorError('Episode could not be extracted') + + return { + 'id': episode_id, + 'display_id': display_id, + 'series_id': podcast_id, + 'vcodec': 'none', + **traverse_obj(episode, { + 'title': ('title', {str}), + 'description': ('description', {str}), + 'url': ('podcast_raw_url', {url_or_none}), + 'thumbnail': ('image', {url_or_none}), + 'timestamp': ('timestamp', {int_or_none}), + 'duration': ('milliseconds', {float_or_none(scale=1000)}), + 'availability': ('free', {lambda v: 'public' if v else 'subscriber_only'}), + }), + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/internetvideoarchive.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/internetvideoarchive.py new file mode 100644 index 0000000000000000000000000000000000000000..9d2574cb068d6931be2e1d5e043a18aff024e21a --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/internetvideoarchive.py @@ -0,0 +1,58 @@ +import json +import re + +from .common import InfoExtractor +from ..utils import parse_qs + + +class InternetVideoArchiveIE(InfoExtractor): + _VALID_URL = r'https?://video\.internetvideoarchive\.net/(?:player|flash/players)/.*?\?.*?publishedid.*?' + + _TEST = { + 'url': 'http://video.internetvideoarchive.net/player/6/configuration.ashx?customerid=69249&publishedid=194487&reporttag=vdbetatitle&playerid=641&autolist=0&domain=www.videodetective.com&maxrate=high&minrate=low&socialplayer=false', + 'info_dict': { + 'id': '194487', + 'ext': 'mp4', + 'title': 'Kick-Ass 2', + 'description': 'md5:c189d5b7280400630a1d3dd17eaa8d8a', + }, + 'params': { + # m3u8 download + 'skip_download': True, + }, + } + + @staticmethod + def _build_json_url(query): + return 'http://video.internetvideoarchive.net/player/6/configuration.ashx?' + query + + def _real_extract(self, url): + query = parse_qs(url) + video_id = query['publishedid'][0] + data = self._download_json( + 'https://video.internetvideoarchive.net/videojs7/videojs7.ivasettings.ashx', + video_id, data=json.dumps({ + 'customerid': query['customerid'][0], + 'publishedid': video_id, + }).encode()) + title = data['Title'] + formats = self._extract_m3u8_formats( + data['VideoUrl'], video_id, 'mp4', + 'm3u8_native', m3u8_id='hls', fatal=False) + file_url = formats[0]['url'] + if '.ism/' in file_url: + replace_url = lambda x: re.sub(r'\.ism/[^?]+', '.ism/' + x, file_url) + formats.extend(self._extract_f4m_formats( + replace_url('.f4m'), video_id, f4m_id='hds', fatal=False)) + formats.extend(self._extract_mpd_formats( + replace_url('.mpd'), video_id, mpd_id='dash', fatal=False)) + formats.extend(self._extract_ism_formats( + replace_url('Manifest'), video_id, ism_id='mss', fatal=False)) + + return { + 'id': video_id, + 'title': title, + 'formats': formats, + 'thumbnail': data.get('PosterUrl'), + 'description': data.get('Description'), + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/islamchannel.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/islamchannel.py new file mode 100644 index 0000000000000000000000000000000000000000..f70c3add4733f822e72f14e996ee83854645651d --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/islamchannel.py @@ -0,0 +1,81 @@ +import re + +from .common import InfoExtractor +from ..utils import traverse_obj, urljoin + + +class IslamChannelIE(InfoExtractor): + _VALID_URL = r'https?://watch\.islamchannel\.tv/watch/(?P<id>\d+)' + _TESTS = [{ + 'url': 'https://watch.islamchannel.tv/watch/38604310', + 'info_dict': { + 'id': '38604310', + 'title': 'Omar - Young Omar', + 'description': 'md5:5cc7ddecef064ea7afe52eb5e0e33b55', + 'thumbnail': r're:https?://.+', + 'ext': 'mp4', + }, + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + webpage = self._download_webpage(url, video_id) + + thumbnail = self._search_regex( + r'data-poster="([^"]+)"', webpage, 'data poster', fatal=False) or \ + self._html_search_meta(('og:image', 'twitter:image'), webpage) + + headers = { + 'Token': self._search_regex(r'data-token="([^"]+)"', webpage, 'data token'), + 'Token-Expiry': self._search_regex(r'data-expiry="([^"]+)"', webpage, 'data expiry'), + 'Uvid': video_id, + } + show_stream = self._download_json( + f'https://v2-streams-elb.simplestreamcdn.com/api/show/stream/{video_id}', video_id, + query={ + 'key': self._search_regex(r'data-key="([^"]+)"', webpage, 'data key'), + 'platform': 'chrome', + }, headers=headers) + # TODO: show_stream['stream'] and show_stream['drm'] may contain something interesting + streams = self._download_json( + traverse_obj(show_stream, ('response', 'tokenization', 'url')), video_id, + headers=headers) + formats, subs = self._extract_m3u8_formats_and_subtitles(traverse_obj(streams, ('Streams', 'Adaptive')), video_id, 'mp4') + + return { + 'id': video_id, + 'title': self._html_search_meta(('og:title', 'twitter:title'), webpage), + 'description': self._html_search_meta(('og:description', 'twitter:description', 'description'), webpage), + 'formats': formats, + 'subtitles': subs, + 'thumbnails': [{ + 'id': 'unscaled', + 'url': thumbnail.split('?')[0], + 'ext': 'jpg', + 'preference': 2, + }, { + 'id': 'orig', + 'url': thumbnail, + 'ext': 'jpg', + 'preference': 1, + }] if thumbnail else None, + } + + +class IslamChannelSeriesIE(InfoExtractor): + _VALID_URL = r'https?://watch\.islamchannel\.tv/series/(?P<id>[a-f\d-]+)' + _TESTS = [{ + 'url': 'https://watch.islamchannel.tv/series/a6cccef3-3ef1-11eb-bc19-06b69c2357cd', + 'info_dict': { + 'id': 'a6cccef3-3ef1-11eb-bc19-06b69c2357cd', + }, + 'playlist_mincount': 31, + }] + + def _real_extract(self, url): + pl_id = self._match_id(url) + webpage = self._download_webpage(url, pl_id) + + return self.playlist_from_matches( + re.finditer(r'<a\s+href="(/watch/\d+)"[^>]+?data-video-type="show">', webpage), + pl_id, getter=lambda x: urljoin(url, x.group(1)), ie=IslamChannelIE) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/jixie.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/jixie.py new file mode 100644 index 0000000000000000000000000000000000000000..4830e61c1bdb5e5d20e6cd7d1e9067b89a3416f4 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/jixie.py @@ -0,0 +1,47 @@ +from .common import InfoExtractor +from ..utils import clean_html, float_or_none, traverse_obj, try_call + + +class JixieBaseIE(InfoExtractor): + """ + API Reference: + https://jixie.atlassian.net/servicedesk/customer/portal/2/article/1339654214?src=-1456335525, + https://scripts.jixie.media/jxvideo.3.1.min.js + """ + + def _extract_data_from_jixie_id(self, display_id, video_id, webpage): + json_data = self._download_json( + 'https://apidam.jixie.io/api/public/stream', display_id, + query={'metadata': 'full', 'video_id': video_id})['data'] + + formats, subtitles = [], {} + for stream in json_data['streams']: + if stream.get('type') == 'HLS': + fmt, sub = self._extract_m3u8_formats_and_subtitles(stream.get('url'), display_id, ext='mp4') + if json_data.get('drm'): + for f in fmt: + f['has_drm'] = True + formats.extend(fmt) + self._merge_subtitles(sub, target=subtitles) + else: + formats.append({ + 'url': stream.get('url'), + 'width': stream.get('width'), + 'height': stream.get('height'), + 'ext': 'mp4', + }) + + return { + 'id': video_id, + 'display_id': display_id, + 'formats': formats, + 'subtitles': subtitles, + 'title': json_data.get('title') or self._html_search_meta(['og:title', 'twitter:title'], webpage), + 'description': (clean_html(traverse_obj(json_data, ('metadata', 'description'))) + or self._html_search_meta(['description', 'og:description', 'twitter:description'], webpage)), + 'thumbnails': traverse_obj(json_data, ('metadata', 'thumbnails')), + 'duration': float_or_none(traverse_obj(json_data, ('metadata', 'duration'))), + 'tags': try_call(lambda: (json_data['metadata']['keywords'] or None).split(',')), + 'categories': try_call(lambda: (json_data['metadata']['categories'] or None).split(',')), + 'uploader_id': json_data.get('owner_id'), + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/jtbc.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/jtbc.py new file mode 100644 index 0000000000000000000000000000000000000000..7532983f7bef8f135778b41d907e0700fd3a47f0 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/jtbc.py @@ -0,0 +1,156 @@ +import re + +from .common import InfoExtractor +from ..utils import ( + int_or_none, + parse_duration, + url_or_none, +) +from ..utils.traversal import traverse_obj + + +class JTBCIE(InfoExtractor): + IE_DESC = 'jtbc.co.kr' + _VALID_URL = r'''(?x) + https?://(?: + vod\.jtbc\.co\.kr/player/(?:program|clip) + |tv\.jtbc\.co\.kr/(?:replay|trailer|clip)/pr\d+/pm\d+ + )/(?P<id>(?:ep|vo)\d+)''' + _GEO_COUNTRIES = ['KR'] + + _TESTS = [{ + 'url': 'https://tv.jtbc.co.kr/replay/pr10011629/pm10067930/ep20216321/view', + 'md5': 'e6ade71d8c8685bbfd6e6ce4167c6a6c', + 'info_dict': { + 'id': 'VO10721192', + 'display_id': 'ep20216321', + 'ext': 'mp4', + 'title': '힘쎈여자 강남순 2회 다시보기', + 'description': 'md5:043c1d9019100ce271dba09995dbd1e2', + 'duration': 3770.0, + 'release_date': '20231008', + 'age_limit': 15, + 'thumbnail': 'https://fs.jtbc.co.kr//joydata/CP00000001/prog/drama/stronggirlnamsoon/img/20231008_163541_522_1.jpg', + 'series': '힘쎈여자 강남순', + }, + }, { + 'url': 'https://vod.jtbc.co.kr/player/program/ep20216733', + 'md5': '217a6d190f115a75e4bda0ceaa4cd7f4', + 'info_dict': { + 'id': 'VO10721429', + 'display_id': 'ep20216733', + 'ext': 'mp4', + 'title': '헬로 마이 닥터 친절한 진료실 149회 다시보기', + 'description': 'md5:1d70788a982dd5de26874a92fcffddb8', + 'duration': 2720.0, + 'release_date': '20231009', + 'age_limit': 15, + 'thumbnail': 'https://fs.jtbc.co.kr//joydata/CP00000001/prog/culture/hellomydoctor/img/20231009_095002_528_1.jpg', + 'series': '헬로 마이 닥터 친절한 진료실', + }, + }, { + 'url': 'https://vod.jtbc.co.kr/player/clip/vo10721270', + 'md5': '05782e2dc22a9c548aebefe62ae4328a', + 'info_dict': { + 'id': 'VO10721270', + 'display_id': 'vo10721270', + 'ext': 'mp4', + 'title': '뭉쳐야 찬다3 2회 예고편 - A매치로 향하는 마지막 관문💥', + 'description': 'md5:d48b51a8655c84843b4ed8d0c39aae68', + 'duration': 46.0, + 'release_date': '20231015', + 'age_limit': 15, + 'thumbnail': 'https://fs.jtbc.co.kr//joydata/CP00000001/prog/enter/soccer3/img/20231008_210957_775_1.jpg', + 'series': '뭉쳐야 찬다3', + }, + }, { + 'url': 'https://tv.jtbc.co.kr/trailer/pr10010392/pm10032526/vo10720912/view', + 'md5': '367d480eb3ef54a9cd7a4b4d69c4b32d', + 'info_dict': { + 'id': 'VO10720912', + 'display_id': 'vo10720912', + 'ext': 'mp4', + 'title': '아는 형님 404회 예고편 | 10월 14일(토) 저녁 8시 50분 방송!', + 'description': 'md5:2743bb1079ceb85bb00060f2ad8f0280', + 'duration': 148.0, + 'release_date': '20231014', + 'age_limit': 15, + 'thumbnail': 'https://fs.jtbc.co.kr//joydata/CP00000001/prog/enter/jtbcbros/img/20231006_230023_802_1.jpg', + 'series': '아는 형님', + }, + }] + + def _real_extract(self, url): + display_id = self._match_id(url) + + if display_id.startswith('vo'): + video_id = display_id.upper() + else: + webpage = self._download_webpage(url, display_id) + video_id = self._search_regex(r'data-vod="(VO\d+)"', webpage, 'vod id') + + playback_data = self._download_json( + f'https://api.jtbc.co.kr/vod/{video_id}', video_id, note='Downloading VOD playback data') + + subtitles = {} + for sub in traverse_obj(playback_data, ('tracks', lambda _, v: v['file'])): + subtitles.setdefault(sub.get('label', 'und'), []).append({'url': sub['file']}) + + formats = [] + for stream_url in traverse_obj(playback_data, ('sources', 'HLS', ..., 'file', {url_or_none})): + stream_url = re.sub(r'/playlist_pd\d+\.m3u8', '/playlist.m3u8', stream_url) + formats.extend(self._extract_m3u8_formats(stream_url, video_id, fatal=False)) + + metadata = self._download_json( + 'https://now-api.jtbc.co.kr/v1/vod/detail', video_id, + note='Downloading mobile details', fatal=False, query={'vodFileId': video_id}) + return { + 'id': video_id, + 'display_id': display_id, + **traverse_obj(metadata, ('vodDetail', { + 'title': 'vodTitleView', + 'series': 'programTitle', + 'age_limit': ('watchAge', {int_or_none}), + 'release_date': ('broadcastDate', {lambda x: re.match(r'\d{8}', x.replace('.', ''))}, 0), + 'description': 'episodeContents', + 'thumbnail': ('imgFileUrl', {url_or_none}), + })), + 'duration': parse_duration(playback_data.get('playTime')), + 'formats': formats, + 'subtitles': subtitles, + } + + +class JTBCProgramIE(InfoExtractor): + IE_NAME = 'JTBC:program' + _VALID_URL = r'https?://(?:vod\.jtbc\.co\.kr/program|tv\.jtbc\.co\.kr/replay)/(?P<id>pr\d+)/(?:replay|pm\d+)/?(?:$|[?#])' + + _TESTS = [{ + 'url': 'https://tv.jtbc.co.kr/replay/pr10010392/pm10032710', + 'info_dict': { + '_type': 'playlist', + 'id': 'pr10010392', + }, + 'playlist_count': 398, + }, { + 'url': 'https://vod.jtbc.co.kr/program/pr10011491/replay', + 'info_dict': { + '_type': 'playlist', + 'id': 'pr10011491', + }, + 'playlist_count': 59, + }] + + def _real_extract(self, url): + program_id = self._match_id(url) + + vod_list = self._download_json( + 'https://now-api.jtbc.co.kr/v1/vodClip/programHome/programReplayVodList', program_id, + note='Downloading program replay list', query={ + 'programId': program_id, + 'rowCount': '10000', + }) + + entries = [self.url_result(f'https://vod.jtbc.co.kr/player/program/{video_id}', JTBCIE, video_id) + for video_id in traverse_obj(vod_list, ('programReplayVodList', ..., 'episodeId'))] + return self.playlist_result(entries, program_id) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/learningonscreen.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/learningonscreen.py new file mode 100644 index 0000000000000000000000000000000000000000..aff59e0684bebfba373655480f9fc492899eea4f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/learningonscreen.py @@ -0,0 +1,72 @@ +import functools +import re + +from .common import InfoExtractor +from ..utils import ( + ExtractorError, + clean_html, + extract_attributes, + join_nonempty, + parse_duration, + unified_timestamp, +) +from ..utils.traversal import find_element, traverse_obj + + +class LearningOnScreenIE(InfoExtractor): + _VALID_URL = r'https?://learningonscreen\.ac\.uk/ondemand/index\.php/prog/(?P<id>\w+)' + _TESTS = [{ + 'url': 'https://learningonscreen.ac.uk/ondemand/index.php/prog/005D81B2?bcast=22757013', + 'info_dict': { + 'id': '005D81B2', + 'ext': 'mp4', + 'title': 'Planet Earth', + 'duration': 3600.0, + 'timestamp': 1164567600.0, + 'upload_date': '20061126', + 'thumbnail': 'https://stream.learningonscreen.ac.uk/trilt-cover-images/005D81B2-Planet-Earth-2006-11-26T190000Z-BBC4.jpg', + }, + }] + + def _real_initialize(self): + if not self._get_cookies('https://learningonscreen.ac.uk/').get('PHPSESSID-LOS-LIVE'): + self.raise_login_required(method='session_cookies') + + def _real_extract(self, url): + video_id = self._match_id(url) + webpage = self._download_webpage(url, video_id) + + details = traverse_obj(webpage, ( + {find_element(id='programme-details', html=True)}, { + 'title': ({find_element(tag='h2')}, {clean_html}), + 'timestamp': ( + {find_element(cls='broadcast-date')}, + {functools.partial(re.match, r'([^<]+)')}, 1, {unified_timestamp}), + 'duration': ( + {find_element(cls='prog-running-time')}, {clean_html}, {parse_duration}), + })) + + title = details.pop('title', None) or traverse_obj(webpage, ( + {find_element(id='add-to-existing-playlist', html=True)}, + {extract_attributes}, 'data-record-title', {clean_html})) + + entries = self._parse_html5_media_entries( + 'https://stream.learningonscreen.ac.uk', webpage, video_id, m3u8_id='hls', mpd_id='dash', + _headers={'Origin': 'https://learningonscreen.ac.uk', 'Referer': 'https://learningonscreen.ac.uk/'}) + if not entries: + raise ExtractorError('No video found') + + if len(entries) > 1: + duration = details.pop('duration', None) + for idx, entry in enumerate(entries, start=1): + entry.update(details) + entry['id'] = join_nonempty(video_id, idx) + entry['title'] = join_nonempty(title, idx) + return self.playlist_result(entries, video_id, title, duration=duration) + + return { + **entries[0], + **details, + 'id': video_id, + 'title': title, + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/libsyn.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/libsyn.py new file mode 100644 index 0000000000000000000000000000000000000000..8772fb76325a79376b850493ffb4422962986505 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/libsyn.py @@ -0,0 +1,111 @@ +from .common import InfoExtractor +from ..utils import ( + clean_html, + get_element_by_class, + parse_duration, + strip_or_none, + unified_strdate, +) + + +class LibsynIE(InfoExtractor): + _VALID_URL = r'(?P<mainurl>https?://html5-player\.libsyn\.com/embed/episode/id/(?P<id>[0-9]+))' + _EMBED_REGEX = [r'<iframe[^>]+src=(["\'])(?P<url>(?:https?:)?//html5-player\.libsyn\.com/embed/.+?)\1'] + + _TESTS = [{ + 'url': 'http://html5-player.libsyn.com/embed/episode/id/6385796/', + 'md5': '2a55e75496c790cdeb058e7e6c087746', + 'info_dict': { + 'id': '6385796', + 'ext': 'mp3', + 'title': 'The Allistair McCaw Podcast - Developing a Growth Mindset', + 'duration': 834.0, + 'thumbnail': r're:https?://assets\.libsyn\.com/.+', + 'upload_date': '20180320', + }, + }, { + 'url': 'https://html5-player.libsyn.com/embed/episode/id/3727166/height/75/width/200/theme/standard/direction/no/autoplay/no/autonext/no/thumbnail/no/preload/no/no_addthis/no/', + 'md5': '6c5cb21acd622d754d3b1a92b582ce42', + 'info_dict': { + 'id': '3727166', + 'ext': 'mp3', + 'title': 'Clients From Hell Podcast - How a Sex Toy Company Kickstarted my Freelance Career', + 'thumbnail': r're:https?://assets\.libsyn\.com/.+', + 'upload_date': '20150818', + }, + 'skip': 'Invalid URL', + }] + _WEBPAGE_TESTS = [{ + 'url': 'https://html5-player.libsyn.com/', + 'md5': '50cff329596b8f674d4449ed077ef2f9', + 'info_dict': { + 'id': '2378831', + 'ext': 'mp3', + 'title': 'md5:54108b15f98e1b4056612c10b50106b2', + 'duration': 3561.0, + 'thumbnail': r're:https?://assets\.libsyn\.com/.+', + 'upload_date': '20130630', + }, + }, { + 'url': 'https://undergroundwellness.com/podcasts/306-5-steps-to-permanent-gut-healing/', + 'md5': '23576952577f9604520a730d90371761', + 'info_dict': { + 'id': '3793998', + 'ext': 'mp3', + 'title': 'Underground Wellness Radio - Jack Tips: 5 Steps to Permanent Gut Healing', + 'duration': 3989.0, + 'thumbnail': r're:https?://assets\.libsyn\.com/.+', + 'upload_date': '20141126', + }, + }] + + def _real_extract(self, url): + url, video_id = self._match_valid_url(url).groups() + webpage = self._download_webpage(url, video_id) + + data = self._parse_json(self._search_regex( + r'var\s+playlistItem\s*=\s*({.+?});', + webpage, 'JSON data block'), video_id) + + episode_title = data.get('item_title') or get_element_by_class('episode-title', webpage) + if not episode_title: + self._search_regex( + [r'data-title="([^"]+)"', r'<title>(.+?)'], + webpage, 'episode title') + episode_title = episode_title.strip() + + podcast_title = strip_or_none(clean_html(self._search_regex( + r'

([^<]+)

', webpage, 'podcast title', + default=None) or get_element_by_class('podcast-title', webpage))) + + title = f'{podcast_title} - {episode_title}' if podcast_title else episode_title + + formats = [] + for k, format_id in (('media_url_libsyn', 'libsyn'), ('media_url', 'main'), ('download_link', 'download')): + f_url = data.get(k) + if not f_url: + continue + formats.append({ + 'url': f_url, + 'format_id': format_id, + }) + + description = self._html_search_regex( + r'(.+?)

', webpage, + 'description', default=None) + if description: + # Strip non-breaking and normal spaces + description = description.replace('\u00A0', ' ').strip() + release_date = unified_strdate(self._search_regex( + r'
Released: ([^<]+)<', + webpage, 'release date', default=None) or data.get('release_date')) + + return { + 'id': video_id, + 'title': title, + 'description': description, + 'thumbnail': data.get('thumbnail_url'), + 'upload_date': release_date, + 'duration': parse_duration(data.get('duration')), + 'formats': formats, + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/livejournal.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/livejournal.py new file mode 100644 index 0000000000000000000000000000000000000000..ee2dfca0d0873ff3efd3455a337351887946acdf --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/livejournal.py @@ -0,0 +1,39 @@ +from .common import InfoExtractor +from ..utils import int_or_none + + +class LiveJournalIE(InfoExtractor): + _WORKING = False + _VALID_URL = r'https?://(?:[^.]+\.)?livejournal\.com/video/album/\d+.+?\bid=(?P\d+)' + _TEST = { + 'url': 'https://andrei-bt.livejournal.com/video/album/407/?mode=view&id=51272', + 'md5': 'adaf018388572ced8a6f301ace49d4b2', + 'info_dict': { + 'id': '1263729', + 'ext': 'mp4', + 'title': 'Истребители против БПЛА', + 'upload_date': '20190624', + 'timestamp': 1561406715, + }, + } + + def _real_extract(self, url): + video_id = self._match_id(url) + webpage = self._download_webpage(url, video_id) + record = self._parse_json(self._search_regex( + r'Site\.page\s*=\s*({.+?});', webpage, + 'page data'), video_id)['video']['record'] + storage_id = str(record['storageid']) + title = record.get('name') + if title: + # remove filename extension(.mp4, .mov, etc...) + title = title.rsplit('.', 1)[0] + return { + '_type': 'url_transparent', + 'id': video_id, + 'title': title, + 'thumbnail': record.get('thumbnail'), + 'timestamp': int_or_none(record.get('timecreate')), + 'url': 'eagleplatform:vc.videos.livejournal.com:' + storage_id, + 'ie_key': 'EaglePlatform', + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/manyvids.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/manyvids.py new file mode 100644 index 0000000000000000000000000000000000000000..1356169bfd447175e5727e537eecb90c8ce567ff --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/manyvids.py @@ -0,0 +1,108 @@ +from .common import InfoExtractor +from ..utils import ( + clean_html, + determine_ext, + int_or_none, + join_nonempty, + parse_count, + parse_duration, + parse_iso8601, + url_or_none, +) +from ..utils.traversal import traverse_obj + + +class ManyVidsIE(InfoExtractor): + _VALID_URL = r'(?i)https?://(?:www\.)?manyvids\.com/video/(?P\d+)' + _TESTS = [{ + # preview video + 'url': 'https://www.manyvids.com/Video/530341/mv-tips-tricks', + 'md5': '738dc723f7735ee9602f7ea352a6d058', + 'info_dict': { + 'id': '530341-preview', + 'ext': 'mp4', + 'title': 'MV Tips & Tricks (Preview)', + 'description': r're:I will take you on a tour around .{1313}$', + 'thumbnail': r're:https://cdn5\.manyvids\.com/php_uploads/video_images/DestinyDiaz/.+\.jpg', + 'uploader': 'DestinyDiaz', + 'view_count': int, + 'like_count': int, + 'release_timestamp': 1508419904, + 'tags': ['AdultSchool', 'BBW', 'SFW', 'TeacherFetish'], + 'release_date': '20171019', + 'duration': 3167.0, + }, + 'expected_warnings': ['Only extracting preview'], + }, { + # full video + 'url': 'https://www.manyvids.com/Video/935718/MY-FACE-REVEAL/', + 'md5': 'bb47bab0e0802c2a60c24ef079dfe60f', + 'info_dict': { + 'id': '935718', + 'ext': 'mp4', + 'title': 'MY FACE REVEAL', + 'description': r're:Today is the day!! I am finally taking off my mask .{445}$', + 'thumbnail': r're:https://ods\.manyvids\.com/1001061960/3aa5397f2a723ec4597e344df66ab845/screenshots/.+\.jpg', + 'uploader': 'Sarah Calanthe', + 'view_count': int, + 'like_count': int, + 'release_date': '20181110', + 'tags': ['EyeContact', 'Interviews', 'MaskFetish', 'MouthFetish', 'Redhead'], + 'release_timestamp': 1541851200, + 'duration': 224.0, + }, + }] + _API_BASE = 'https://www.manyvids.com/bff/store/video' + + def _real_extract(self, url): + video_id = self._match_id(url) + video_data = self._download_json(f'{self._API_BASE}/{video_id}/private', video_id)['data'] + formats, preview_only = [], True + + for format_id, path in [ + ('preview', ['teaser', 'filepath']), + ('transcoded', ['transcodedFilepath']), + ('filepath', ['filepath']), + ]: + format_url = traverse_obj(video_data, (*path, {url_or_none})) + if not format_url: + continue + if determine_ext(format_url) == 'm3u8': + formats.extend(self._extract_m3u8_formats(format_url, video_id, 'mp4', m3u8_id=format_id)) + else: + formats.append({ + 'url': format_url, + 'format_id': format_id, + 'preference': -10 if format_id == 'preview' else None, + 'quality': 10 if format_id == 'filepath' else None, + 'height': int_or_none( + self._search_regex(r'_(\d{2,3}[02468])_', format_url, 'height', default=None)), + }) + if format_id != 'preview': + preview_only = False + + metadata = traverse_obj( + self._download_json(f'{self._API_BASE}/{video_id}', video_id, fatal=False), 'data') + title = traverse_obj(metadata, ('title', {clean_html})) + + if preview_only: + title = join_nonempty(title, '(Preview)', delim=' ') + video_id += '-preview' + self.report_warning( + f'Only extracting preview. Video may be paid or subscription only. {self._login_hint()}') + + return { + 'id': video_id, + 'title': title, + 'formats': formats, + **traverse_obj(metadata, { + 'description': ('description', {clean_html}), + 'uploader': ('model', 'displayName', {clean_html}), + 'thumbnail': (('screenshot', 'thumbnail'), {url_or_none}, any), + 'view_count': ('views', {parse_count}), + 'like_count': ('likes', {parse_count}), + 'release_timestamp': ('launchDate', {parse_iso8601}), + 'duration': ('videoDuration', {parse_duration}), + 'tags': ('tagList', ..., 'label', {str}, filter, all, filter), + }), + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/markiza.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/markiza.py new file mode 100644 index 0000000000000000000000000000000000000000..088b60d554043d69d1549e47389f4331457fcebe --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/markiza.py @@ -0,0 +1,123 @@ +import re + +from .common import InfoExtractor +from ..utils import ( + orderedSet, + parse_duration, + try_get, +) + + +class MarkizaIE(InfoExtractor): + _WORKING = False + _VALID_URL = r'https?://(?:www\.)?videoarchiv\.markiza\.sk/(?:video/(?:[^/]+/)*|embed/)(?P\d+)(?:[_/]|$)' + _TESTS = [{ + 'url': 'http://videoarchiv.markiza.sk/video/oteckovia/84723_oteckovia-109', + 'md5': 'ada4e9fad038abeed971843aa028c7b0', + 'info_dict': { + 'id': '139078', + 'ext': 'mp4', + 'title': 'Oteckovia 109', + 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e', + 'thumbnail': r're:^https?://.*\.jpg$', + 'duration': 2760, + }, + }, { + 'url': 'http://videoarchiv.markiza.sk/video/televizne-noviny/televizne-noviny/85430_televizne-noviny', + 'info_dict': { + 'id': '85430', + 'title': 'Televízne noviny', + }, + 'playlist_count': 23, + }, { + 'url': 'http://videoarchiv.markiza.sk/video/oteckovia/84723', + 'only_matching': True, + }, { + 'url': 'http://videoarchiv.markiza.sk/video/84723', + 'only_matching': True, + }, { + 'url': 'http://videoarchiv.markiza.sk/video/filmy/85190_kamenak', + 'only_matching': True, + }, { + 'url': 'http://videoarchiv.markiza.sk/video/reflex/zo-zakulisia/84651_pribeh-alzbetky', + 'only_matching': True, + }, { + 'url': 'http://videoarchiv.markiza.sk/embed/85295', + 'only_matching': True, + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + + data = self._download_json( + 'http://videoarchiv.markiza.sk/json/video_jwplayer7.json', + video_id, query={'id': video_id}) + + info = self._parse_jwplayer_data(data, m3u8_id='hls', mpd_id='dash') + + if info.get('_type') == 'playlist': + info.update({ + 'id': video_id, + 'title': try_get( + data, lambda x: x['details']['name'], str), + }) + else: + info['duration'] = parse_duration( + try_get(data, lambda x: x['details']['duration'], str)) + return info + + +class MarkizaPageIE(InfoExtractor): + _WORKING = False + _VALID_URL = r'https?://(?:www\.)?(?:(?:[^/]+\.)?markiza|tvnoviny)\.sk/(?:[^/]+/)*(?P\d+)_' + _TESTS = [{ + 'url': 'http://www.markiza.sk/soubiz/zahranicny/1923705_oteckovia-maju-svoj-den-ti-slavni-nie-su-o-nic-menej-rozkosni', + 'md5': 'ada4e9fad038abeed971843aa028c7b0', + 'info_dict': { + 'id': '139355', + 'ext': 'mp4', + 'title': 'Oteckovia 110', + 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e', + 'thumbnail': r're:^https?://.*\.jpg$', + 'duration': 2604, + }, + 'params': { + 'skip_download': True, + }, + }, { + 'url': 'http://dajto.markiza.sk/filmy-a-serialy/1774695_frajeri-vo-vegas', + 'only_matching': True, + }, { + 'url': 'http://superstar.markiza.sk/aktualne/1923870_to-je-ale-telo-spevacka-ukazala-sexy-postavicku-v-bikinach', + 'only_matching': True, + }, { + 'url': 'http://hybsa.markiza.sk/aktualne/1923790_uzasna-atmosfera-na-hybsa-v-poprade-superstaristi-si-prve-koncerty-pred-davom-ludi-poriadne-uzili', + 'only_matching': True, + }, { + 'url': 'http://doma.markiza.sk/filmy/1885250_moja-vysnivana-svadba', + 'only_matching': True, + }, { + 'url': 'http://www.tvnoviny.sk/domace/1923887_po-smrti-manzela-ju-cakalo-poriadne-prekvapenie', + 'only_matching': True, + }] + + @classmethod + def suitable(cls, url): + return False if MarkizaIE.suitable(url) else super().suitable(url) + + def _real_extract(self, url): + playlist_id = self._match_id(url) + + webpage = self._download_webpage( + # Downloading for some hosts (e.g. dajto, doma) fails with 500 + # although everything seems to be OK, so considering 500 + # status code to be expected. + url, playlist_id, expected_status=500) + + entries = [ + self.url_result(f'http://videoarchiv.markiza.sk/video/{video_id}') + for video_id in orderedSet(re.findall( + r'(?:initPlayer_|data-entity=["\']|id=["\']player_)(\d+)', + webpage))] + + return self.playlist_result(entries, playlist_id) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/megatvcom.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/megatvcom.py new file mode 100644 index 0000000000000000000000000000000000000000..826a9a3b1fc2242fecb24117f261a5843a9d58f5 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/megatvcom.py @@ -0,0 +1,172 @@ +import re + +from .common import InfoExtractor +from ..networking import HEADRequest +from ..utils import ( + ExtractorError, + clean_html, + determine_ext, + extract_attributes, + get_element_by_class, + get_element_html_by_id, + parse_qs, + unescapeHTML, + unified_timestamp, +) + + +class MegaTVComBaseIE(InfoExtractor): + _PLAYER_DIV_ID = 'player_div_id' + + def _extract_player_attrs(self, webpage): + player_el = get_element_html_by_id(self._PLAYER_DIV_ID, webpage) + return { + re.sub(r'^data-(?:kwik_)?', '', k): v + for k, v in extract_attributes(player_el).items() + if k not in ('id',) + } + + +class MegaTVComIE(MegaTVComBaseIE): + IE_NAME = 'megatvcom' + IE_DESC = 'megatv.com videos' + _VALID_URL = r'https?://(?:www\.)?megatv\.com/(?:\d{4}/\d{2}/\d{2}|[^/]+/(?P\d+))/(?P[^/]+)' + _TESTS = [{ + # FIXME: Unable to extract article id + 'url': 'https://www.megatv.com/2021/10/23/egkainia-gia-ti-nea-skini-omega-tou-dimotikou-theatrou-peiraia/', + 'info_dict': { + 'id': '520979', + 'ext': 'mp4', + 'title': 'md5:70eef71a9cd2c1ecff7ee428354dded2', + 'description': 'md5:0209fa8d318128569c0d256a5c404db1', + 'timestamp': 1634975747, + 'upload_date': '20211023', + 'display_id': 'egkainia-gia-ti-nea-skini-omega-tou-dimotikou-theatrou-peiraia', + 'thumbnail': r're:https?://www\.megatv\.com/wp-content/uploads/.+\.jpg', + }, + }, { + 'url': 'https://www.megatv.com/tvshows/527800/epeisodio-65-12/', + 'info_dict': { + 'id': '527800', + 'ext': 'mp4', + 'title': 'Η Γη της Ελιάς: Επεισόδιο 65 - A\' ΚΥΚΛΟΣ ', + 'description': 'md5:b2b7ed3690a78f2a0156eb790fdc00df', + 'timestamp': 1636048859, + 'upload_date': '20211104', + 'display_id': 'epeisodio-65-12', + 'thumbnail': r're:https?://www\.megatv\.com/wp-content/uploads/.+\.jpg', + }, + }] + + def _real_extract(self, url): + video_id, display_id = self._match_valid_url(url).group('id', 'slug') + _is_article = video_id is None + webpage = self._download_webpage(url, video_id or display_id) + if _is_article: + video_id = self._search_regex( + r']*\sid=["\']Article_(\d+)["\']', webpage, 'article id') + player_attrs = self._extract_player_attrs(webpage) + title = player_attrs.get('label') or self._og_search_title(webpage) + description = get_element_by_class( + 'article-wrapper' if _is_article else 'story_content', + webpage) + description = clean_html(re.sub(r']*>[^<]+', '', description)) + if not description: + description = self._og_search_description(webpage) + thumbnail = player_attrs.get('image') or self._og_search_thumbnail(webpage) + timestamp = unified_timestamp(self._html_search_meta( + 'article:published_time', webpage)) + source = player_attrs.get('source') + if not source: + raise ExtractorError('No source found', video_id=video_id) + if determine_ext(source) == 'm3u8': + formats, subs = self._extract_m3u8_formats_and_subtitles(source, video_id, 'mp4') + else: + formats, subs = [{'url': source}], {} + if player_attrs.get('subs'): + self._merge_subtitles({'und': [{'url': player_attrs['subs']}]}, target=subs) + return { + 'id': video_id, + 'display_id': display_id, + 'title': title, + 'description': description, + 'thumbnail': thumbnail, + 'timestamp': timestamp, + 'formats': formats, + 'subtitles': subs, + } + + +class MegaTVComEmbedIE(MegaTVComBaseIE): + IE_NAME = 'megatvcom:embed' + IE_DESC = 'megatv.com embedded videos' + _VALID_URL = r'(?:https?:)?//(?:www\.)?megatv\.com/embed/?\?p=(?P\d+)' + _EMBED_REGEX = [rf''']+?src=(?P<_q1>["'])(?P{_VALID_URL})(?P=_q1)'''] + _TESTS = [{ + # FIXME: Unable to extract article id + 'url': 'https://www.megatv.com/embed/?p=2020520979', + 'md5': '6546a1a37fff0dd51c9dce5f490b7d7d', + 'info_dict': { + 'id': '520979', + 'ext': 'mp4', + 'title': 'md5:70eef71a9cd2c1ecff7ee428354dded2', + 'description': 'md5:0209fa8d318128569c0d256a5c404db1', + 'timestamp': 1634975747, + 'upload_date': '20211023', + 'display_id': 'egkainia-gia-ti-nea-skini-omega-tou-dimotikou-theatrou-peiraia', + 'thumbnail': 'https://www.megatv.com/wp-content/uploads/2021/10/ΠΕΙΡΑΙΑΣ-1024x450.jpg', + }, + }, { + # FIXME: Unable to extract article id + 'url': 'https://www.megatv.com/embed/?p=2020534081', + 'md5': '6ac8b3ce4dc6120c802f780a1e6b3812', + 'info_dict': { + 'id': '534081', + 'ext': 'mp4', + 'title': 'md5:062e9d5976ef854d8bdc1f5724d9b2d0', + 'description': 'md5:36dbe4c3762d2ede9513eea8d07f6d52', + 'timestamp': 1636376351, + 'upload_date': '20211108', + 'display_id': 'neo-rekor-stin-timi-tou-ilektrikou-reymatos-pano-apo-ta-200e-i-xondriki-timi-tou-ilektrikou', + 'thumbnail': 'https://www.megatv.com/wp-content/uploads/2021/11/Capture-266.jpg', + }, + }] + _WEBPAGE_TESTS = [{ + # FIXME: Unable to extract article id + 'url': 'https://www.in.gr/2021/12/18/greece/apokalypsi-mega-poios-parelave-tin-ereyna-tsiodra-ek-merous-tis-kyvernisis-o-prothypourgos-telika-gnorize/', + 'info_dict': { + 'id': 'apokalypsi-mega-poios-parelave-tin-ereyna-tsiodra-ek-merous-tis-kyvernisis-o-prothypourgos-telika-gnorize', + 'title': 'md5:5e569cf996ec111057c2764ec272848f', + }, + 'playlist_count': 2, + }] + + def _match_canonical_url(self, webpage): + LINK_RE = r'''(?x) + ["'])(?Pcanonical)(?P=_q1)| + href=(?P<_q2>["'])(?P(?:(?!(?P=_q2)).)+)(?P=_q2)| + [^>]*? + )+> + ''' + for mobj in re.finditer(LINK_RE, webpage): + canonical, href = mobj.group('canonical', 'href') + if canonical and href: + return unescapeHTML(href) + + def _real_extract(self, url): + video_id = self._match_id(url) + webpage = self._download_webpage(url, video_id) + player_attrs = self._extract_player_attrs(webpage) + canonical_url = player_attrs.get('share_url') or self._match_canonical_url(webpage) + if not canonical_url: + raise ExtractorError('canonical URL not found') + video_id = parse_qs(canonical_url)['p'][0] + + # Defer to megatvcom as the metadata extracted from the embeddable page some + # times are slightly different, for the same video + canonical_url = self._request_webpage( + HEADRequest(canonical_url), video_id, + note='Resolve canonical URL', + errnote='Could not resolve canonical URL').url + return self.url_result(canonical_url, MegaTVComIE.ie_key(), video_id) diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/moviepilot.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/moviepilot.py new file mode 100644 index 0000000000000000000000000000000000000000..3b20232263455989e93422c85092da76013483ba --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/moviepilot.py @@ -0,0 +1,97 @@ +from .common import InfoExtractor +from .dailymotion import DailymotionIE + + +class MoviepilotIE(InfoExtractor): + IE_NAME = 'moviepilot' + IE_DESC = 'Moviepilot trailer' + _VALID_URL = r'https?://(?:www\.)?moviepilot\.de/movies/(?P[^/]+)' + + _TESTS = [{ + 'url': 'https://www.moviepilot.de/movies/interstellar-2/', + 'info_dict': { + 'id': 'x7xdpkk', + 'display_id': 'interstellar-2', + 'ext': 'mp4', + 'title': 'Interstellar', + 'thumbnail': r're:https://\w+\.dmcdn\.net/v/SaV-q1.*/x1080', + 'timestamp': 1605010596, + 'description': 'md5:0ae9cb452af52610c9ffc60f2fd0474c', + 'uploader': 'Moviepilot', + 'like_count': int, + 'view_count': int, + 'uploader_id': 'x6nd9k', + 'upload_date': '20201110', + 'duration': 97, + 'age_limit': 0, + 'tags': ['Alle Trailer', 'Movie', 'Verleih'], + }, + }, { + 'url': 'https://www.moviepilot.de/movies/interstellar-2/trailer', + 'only_matching': True, + }, { + 'url': 'https://www.moviepilot.de/movies/interstellar-2/kinoprogramm/berlin', + 'only_matching': True, + }, { + 'url': 'https://www.moviepilot.de/movies/queen-slim/trailer', + 'info_dict': { + 'id': 'x7xj6o7', + 'display_id': 'queen-slim', + 'title': 'Queen & Slim', + 'ext': 'mp4', + 'thumbnail': r're:https://\w+\.dmcdn\.net/v/SbUM71ZeG2N975lf2/x1080', + 'timestamp': 1605555825, + 'description': 'md5:83228bb86f5367dd181447fdc4873989', + 'uploader': 'Moviepilot', + 'like_count': int, + 'view_count': int, + 'uploader_id': 'x6nd9k', + 'upload_date': '20201116', + 'duration': 138, + 'age_limit': 0, + 'tags': ['Movie', 'Verleih', 'Neue Trailer'], + }, + }, { + 'url': 'https://www.moviepilot.de/movies/der-geiger-von-florenz/trailer', + 'info_dict': { + 'id': 'der-geiger-von-florenz', + 'title': 'Der Geiger von Florenz', + 'ext': 'mp4', + }, + 'skip': 'No trailer for this movie.', + }, { + 'url': 'https://www.moviepilot.de/movies/muellers-buero/', + 'info_dict': { + 'id': 'x7xcw1i', + 'display_id': 'muellers-buero', + 'title': 'Müllers Büro', + 'ext': 'mp4', + 'description': 'md5:4d23a8f4ca035196cd4523863c4fe5a4', + 'timestamp': 1604958457, + 'age_limit': 0, + 'duration': 82, + 'upload_date': '20201109', + 'thumbnail': r're:https://\w+\.dmcdn\.net/v/SaMes1Z.*/x1080', + 'uploader': 'Moviepilot', + 'like_count': int, + 'view_count': int, + 'tags': ['Alle Trailer', 'Movie', 'Verleih'], + 'uploader_id': 'x6nd9k', + }, + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + + webpage = self._download_webpage(f'https://www.moviepilot.de/movies/{video_id}/trailer', video_id) + + clip = self._search_nextjs_data(webpage, video_id)['props']['initialProps']['pageProps'] + + return { + '_type': 'url_transparent', + 'ie_key': DailymotionIE.ie_key(), + 'display_id': video_id, + 'title': clip.get('title'), + 'url': f'https://www.dailymotion.com/video/{clip["video"]["remoteId"]}', + 'description': clip.get('summary'), + } diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/msn.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/msn.py new file mode 100644 index 0000000000000000000000000000000000000000..6ede7c5cfc40c3fef57c80d2078842317f5f124f --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/msn.py @@ -0,0 +1,215 @@ +from .common import InfoExtractor +from ..utils import ( + ExtractorError, + clean_html, + determine_ext, + int_or_none, + parse_iso8601, + url_or_none, +) +from ..utils.traversal import traverse_obj + + +class MSNIE(InfoExtractor): + _VALID_URL = r'https?://(?:(?:www|preview)\.)?msn\.com/(?P[a-z]{2}-[a-z]{2})/(?:[^/?#]+/)+(?P[^/?#]+)/[a-z]{2}-(?P[\da-zA-Z]+)' + _TESTS = [{ + 'url': 'https://www.msn.com/en-gb/video/news/president-macron-interrupts-trump-over-ukraine-funding/vi-AA1zMcD7', + 'info_dict': { + 'id': 'AA1zMcD7', + 'ext': 'mp4', + 'display_id': 'president-macron-interrupts-trump-over-ukraine-funding', + 'title': 'President Macron interrupts Trump over Ukraine funding', + 'description': 'md5:5fd3857ac25849e7a56cb25fbe1a2a8b', + 'uploader': 'k! News UK', + 'uploader_id': 'BB1hz5Rj', + 'duration': 59, + 'thumbnail': 'https://img-s-msn-com.akamaized.net/tenant/amp/entityid/AA1zMagX.img', + 'tags': 'count:14', + 'timestamp': 1740510914, + 'upload_date': '20250225', + 'release_timestamp': 1740513600, + 'release_date': '20250225', + 'modified_timestamp': 1741413241, + 'modified_date': '20250308', + }, + }, { + 'url': 'https://www.msn.com/en-gb/video/watch/films-success-saved-adam-pearsons-acting-career/vi-AA1znZGE?ocid=hpmsn', + 'info_dict': { + 'id': 'AA1znZGE', + 'ext': 'mp4', + 'display_id': 'films-success-saved-adam-pearsons-acting-career', + 'title': "Films' success saved Adam Pearson's acting career", + 'description': 'md5:98c05f7bd9ab4f9c423400f62f2d3da5', + 'uploader': 'Sky News', + 'uploader_id': 'AA2eki', + 'duration': 52, + 'thumbnail': 'https://img-s-msn-com.akamaized.net/tenant/amp/entityid/AA1zo7nU.img', + 'timestamp': 1739993965, + 'upload_date': '20250219', + 'release_timestamp': 1739977753, + 'release_date': '20250219', + 'modified_timestamp': 1742076259, + 'modified_date': '20250315', + }, + }, { + 'url': 'https://www.msn.com/en-us/entertainment/news/rock-frontman-replacements-you-might-not-know-happened/vi-AA1yLVcD', + 'info_dict': { + 'id': 'AA1yLVcD', + 'ext': 'mp4', + 'display_id': 'rock-frontman-replacements-you-might-not-know-happened', + 'title': 'Rock Frontman Replacements You Might Not Know Happened', + 'description': 'md5:451a125496ff0c9f6816055bb1808da9', + 'uploader': 'Grunge (Video)', + 'uploader_id': 'BB1oveoV', + 'duration': 596, + 'thumbnail': 'https://img-s-msn-com.akamaized.net/tenant/amp/entityid/AA1yM4OJ.img', + 'timestamp': 1739223456, + 'upload_date': '20250210', + 'release_timestamp': 1739219731, + 'release_date': '20250210', + 'modified_timestamp': 1741427272, + 'modified_date': '20250308', + }, + }, { + # Dailymotion Embed + 'url': 'https://www.msn.com/de-de/nachrichten/other/the-first-descendant-gameplay-trailer-zu-serena-der-neuen-gefl%C3%BCgelten-nachfahrin/vi-AA1B1d06', + 'info_dict': { + 'id': 'x9g6oli', + 'ext': 'mp4', + 'title': 'The First Descendant: Gameplay-Trailer zu Serena, der neuen geflügelten Nachfahrin', + 'description': '', + 'uploader': 'MeinMMO', + 'uploader_id': 'x2mvqi4', + 'view_count': int, + 'like_count': int, + 'age_limit': 0, + 'duration': 60, + 'thumbnail': 'https://s1.dmcdn.net/v/Y3fO61drj56vPB9SS/x1080', + 'tags': ['MeinMMO', 'The First Descendant'], + 'timestamp': 1742124877, + 'upload_date': '20250316', + }, + }, { + # Youtube Embed + 'url': 'https://www.msn.com/en-gb/video/webcontent/web-content/vi-AA1ybFaJ', + 'info_dict': { + 'id': 'kQSChWu95nE', + 'ext': 'mp4', + 'title': '7 Daily Habits to Nurture Your Personal Growth', + 'description': 'md5:6f233c68341b74dee30c8c121924e827', + 'uploader': 'TopThink', + 'uploader_id': '@TopThink', + 'uploader_url': 'https://www.youtube.com/@TopThink', + 'channel': 'TopThink', + 'channel_id': 'UCMlGmHokrQRp-RaNO7aq4Uw', + 'channel_url': 'https://www.youtube.com/channel/UCMlGmHokrQRp-RaNO7aq4Uw', + 'channel_is_verified': True, + 'channel_follower_count': int, + 'comment_count': int, + 'view_count': int, + 'like_count': int, + 'age_limit': 0, + 'duration': 705, + 'thumbnail': 'https://i.ytimg.com/vi/kQSChWu95nE/maxresdefault.jpg', + 'categories': ['Howto & Style'], + 'tags': ['topthink', 'top think', 'personal growth'], + 'timestamp': 1722711620, + 'upload_date': '20240803', + 'playable_in_embed': True, + 'availability': 'public', + 'live_status': 'not_live', + }, + }, { + # Article with social embed + 'url': 'https://www.msn.com/en-in/news/techandscience/watch-earth-sets-and-rises-behind-moon-in-breathtaking-blue-ghost-video/ar-AA1zKoAc', + 'info_dict': { + 'id': 'AA1zKoAc', + 'title': 'Watch: Earth sets and rises behind Moon in breathtaking Blue Ghost video', + 'description': 'md5:0ad51cfa77e42e7f0c46cf98a619dbbf', + 'uploader': 'India Today', + 'uploader_id': 'AAyFWG', + 'tags': 'count:11', + 'timestamp': 1740485034, + 'upload_date': '20250225', + 'release_timestamp': 1740484875, + 'release_date': '20250225', + 'modified_timestamp': 1740488561, + 'modified_date': '20250225', + }, + 'playlist_count': 1, + }] + + def _real_extract(self, url): + locale, display_id, page_id = self._match_valid_url(url).group('locale', 'display_id', 'id') + + json_data = self._download_json( + f'https://assets.msn.com/content/view/v2/Detail/{locale}/{page_id}', page_id) + + common_metadata = traverse_obj(json_data, { + 'title': ('title', {str}), + 'description': (('abstract', ('body', {clean_html})), {str}, filter, any), + 'timestamp': ('createdDateTime', {parse_iso8601}), + 'release_timestamp': ('publishedDateTime', {parse_iso8601}), + 'modified_timestamp': ('updatedDateTime', {parse_iso8601}), + 'thumbnail': ('thumbnail', 'image', 'url', {url_or_none}), + 'duration': ('videoMetadata', 'playTime', {int_or_none}), + 'tags': ('keywords', ..., {str}), + 'uploader': ('provider', 'name', {str}), + 'uploader_id': ('provider', 'id', {str}), + }) + + page_type = json_data['type'] + source_url = traverse_obj(json_data, ('sourceHref', {url_or_none})) + if page_type == 'video': + if traverse_obj(json_data, ('thirdPartyVideoPlayer', 'enabled')) and source_url: + return self.url_result(source_url) + formats = [] + subtitles = {} + for file in traverse_obj(json_data, ('videoMetadata', 'externalVideoFiles', lambda _, v: url_or_none(v['url']))): + file_url = file['url'] + ext = determine_ext(file_url) + if ext == 'm3u8': + fmts, subs = self._extract_m3u8_formats_and_subtitles( + file_url, page_id, 'mp4', m3u8_id='hls', fatal=False) + formats.extend(fmts) + self._merge_subtitles(subs, target=subtitles) + elif ext == 'mpd': + fmts, subs = self._extract_mpd_formats_and_subtitles( + file_url, page_id, mpd_id='dash', fatal=False) + formats.extend(fmts) + self._merge_subtitles(subs, target=subtitles) + else: + formats.append( + traverse_obj(file, { + 'url': 'url', + 'format_id': ('format', {str}), + 'filesize': ('fileSize', {int_or_none}), + 'height': ('height', {int_or_none}), + 'width': ('width', {int_or_none}), + })) + for caption in traverse_obj(json_data, ('videoMetadata', 'closedCaptions', lambda _, v: url_or_none(v['href']))): + lang = caption.get('locale') or 'en-us' + subtitles.setdefault(lang, []).append({ + 'url': caption['href'], + 'ext': 'ttml', + }) + + return { + 'id': page_id, + 'display_id': display_id, + 'formats': formats, + 'subtitles': subtitles, + **common_metadata, + } + elif page_type == 'webcontent': + if not source_url: + raise ExtractorError('Could not find source URL') + return self.url_result(source_url) + elif page_type == 'article': + entries = [] + for embed_url in traverse_obj(json_data, ('socialEmbeds', ..., 'postUrl', {url_or_none})): + entries.append(self.url_result(embed_url)) + + return self.playlist_result(entries, page_id, **common_metadata) + + raise ExtractorError(f'Unsupported page type: {page_type}') diff --git a/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/museai.py b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/museai.py new file mode 100644 index 0000000000000000000000000000000000000000..7f66928c72008e2a437956985c958f64b92cb9b9 --- /dev/null +++ b/hientran/sythetic_crawl_data/crawl/lib64/python3.12/site-packages/yt_dlp/extractor/museai.py @@ -0,0 +1,112 @@ +import re + +from .common import InfoExtractor +from ..utils import ( + ExtractorError, + determine_ext, + float_or_none, + int_or_none, + js_to_json, + traverse_obj, + url_or_none, +) + + +class MuseAIIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?muse\.ai/(?:v|embed)/(?P\w+)' + _TESTS = [{ + 'url': 'https://muse.ai/embed/YdTWvUW', + 'md5': 'f994f9a38be1c3aaf9e37cbd7d76fe7c', + 'info_dict': { + 'id': 'YdTWvUW', + 'ext': 'mp4', + 'title': '2023-05-28-Grabien-1941111 (1)', + 'description': '', + 'uploader': 'Today News Africa', + 'uploader_id': 'TodayNewsAfrica', + 'upload_date': '20230528', + 'timestamp': 1685285044, + 'duration': 1291.3, + 'view_count': int, + 'availability': 'public', + }, + }, { + 'url': 'https://muse.ai/v/gQ4gGAA-0756', + 'md5': '52dbfc78e865e56dc19a1715badc35e8', + 'info_dict': { + 'id': 'gQ4gGAA', + 'ext': 'mp4', + 'title': '0756', + 'description': 'md5:0ca1483f9aac423e9a96ad00bb3a0785', + 'uploader': 'Aerial.ie', + 'uploader_id': 'aerial', + 'upload_date': '20210306', + 'timestamp': 1615072842, + 'duration': 21.4, + 'view_count': int, + 'availability': 'public', + }, + }] + _WEBPAGE_TESTS = [{ + 'url': 'https://muse.ai/docs', + 'playlist_mincount': 4, + 'info_dict': { + 'id': 'docs', + 'title': 'muse.ai | docs', + 'description': 'md5:6c0293431481582739c82ee8902687fa', + 'age_limit': 0, + 'thumbnail': 'https://muse.ai/static/imgs/poster-img-docs.png', + }, + 'params': {'allowed_extractors': ['all', '-html5']}, + }] + _EMBED_REGEX = [r']*\bsrc=["\'](?Phttps://muse\.ai/embed/\w+)'] + + @classmethod + def _extract_embed_urls(cls, url, webpage): + yield from super()._extract_embed_urls(url, webpage) + for embed_id in re.findall(r'