byterover 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. byterover/__init__.py +6 -0
  2. byterover/__main__.py +18 -0
  3. byterover/_utils/__init__.py +0 -0
  4. byterover/_utils/async_utils.py +31 -0
  5. byterover/_utils/deprecation.py +5 -0
  6. byterover/_utils/http_utils.py +69 -0
  7. byterover/_utils/logger.py +19 -0
  8. byterover/api/__init__.py +0 -0
  9. byterover/api/client.py +145 -0
  10. byterover/api/core/__init__.py +0 -0
  11. byterover/api/core/api_error.py +15 -0
  12. byterover/api/core/client_wrapper.py +97 -0
  13. byterover/api/core/datetime_utils.py +28 -0
  14. byterover/api/core/file.py +43 -0
  15. byterover/api/core/http_client.py +383 -0
  16. byterover/api/core/jsonable_encoder.py +106 -0
  17. byterover/api/core/pydantic_utilities.py +26 -0
  18. byterover/api/core/query_encoder.py +37 -0
  19. byterover/api/core/remove_none_from_dict.py +9 -0
  20. byterover/api/core/request_options.py +32 -0
  21. byterover/api/listen_socket.py +112 -0
  22. byterover/api/resource/__init__.py +0 -0
  23. byterover/api/resource/llm_keys/__init__.py +0 -0
  24. byterover/api/resource/llm_keys/client.py +90 -0
  25. byterover/api/resource/llm_keys/types/__init__.py +0 -0
  26. byterover/api/resource/llm_keys/types/llm_key.py +12 -0
  27. byterover/api/resource/notes/__init__.py +0 -0
  28. byterover/api/resource/notes/client.py +177 -0
  29. byterover/api/resource/notes/types/__init__.py +0 -0
  30. byterover/api/resource/notes/types/note_check.py +6 -0
  31. byterover/api/resource/organizations/__init__.py +5 -0
  32. byterover/api/resource/organizations/client.py +139 -0
  33. byterover/api/resource/organizations/types/__init__.py +5 -0
  34. byterover/api/resource/organizations/types/organization.py +14 -0
  35. byterover/api/resource/organizations/types/organizations.py +14 -0
  36. byterover/api/resource/projects/__init__.py +0 -0
  37. byterover/api/resource/projects/client.py +91 -0
  38. byterover/api/resource/projects/types/__init__.py +0 -0
  39. byterover/api/resource/projects/types/project.py +12 -0
  40. byterover/api/resource/tokens/__init__.py +3 -0
  41. byterover/api/resource/tokens/client.py +98 -0
  42. byterover/api/resource/tokens/types/__init__.py +3 -0
  43. byterover/api/resource/tokens/types/verify_token_request.py +17 -0
  44. byterover/api/resource/tokens/types/verify_token_response.py +18 -0
  45. byterover/cli/__init__.py +0 -0
  46. byterover/cli/_traceback.py +46 -0
  47. byterover/cli/entry_point.py +48 -0
  48. byterover/cli/llm_key.py +82 -0
  49. byterover/cli/profile.py +32 -0
  50. byterover/cli/project.py +76 -0
  51. byterover/cli/run.py +138 -0
  52. byterover/cli/token.py +66 -0
  53. byterover/cli/utils.py +28 -0
  54. byterover/config.py +216 -0
  55. byterover/exception.py +75 -0
  56. byterover/token_flow.py +51 -0
  57. byterover-0.1.0.dist-info/LICENSE +201 -0
  58. byterover-0.1.0.dist-info/METADATA +28 -0
  59. byterover-0.1.0.dist-info/RECORD +65 -0
  60. byterover-0.1.0.dist-info/WHEEL +5 -0
  61. byterover-0.1.0.dist-info/entry_points.txt +2 -0
  62. byterover-0.1.0.dist-info/top_level.txt +2 -0
  63. byterover_version/__init__.py +10 -0
  64. byterover_version/__main__.py +4 -0
  65. byterover_version/_version_generated.py +2 -0
byterover/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ if sys.version_info[:2] < (3, 11):
4
+ raise RuntimeError("This version of Byterover requires at least Python 3.9")
5
+ if sys.version_info[:2] >= (3, 14):
6
+ raise RuntimeError("This version of Byterover does not support Python 3.14+")
byterover/__main__.py ADDED
@@ -0,0 +1,18 @@
1
+ from byterover.cli.entry_point import entrypoint_cli
2
+ from byterover.config import config
3
+ from byterover.exception import _CliUserExecutionError
4
+ from byterover.cli._traceback import highlight_byterover_deprecation_warnings
5
+
6
+
7
+ def main():
8
+ highlight_byterover_deprecation_warnings()
9
+
10
+ try:
11
+ entrypoint_cli()
12
+
13
+ except _CliUserExecutionError as exc:
14
+ if config.get("traceback"):
15
+ raise
16
+
17
+ if __name__ == "__main__":
18
+ main()
File without changes
@@ -0,0 +1,31 @@
1
+ import asyncio
2
+ import inspect
3
+ import synchronicity
4
+ from typing import TypeVar
5
+
6
+ synchronizer = synchronicity.Synchronizer()
7
+
8
+
9
+ _shutdown_tasks = []
10
+
11
+ def synchronize_api(obj, target_module=None):
12
+ if inspect.isclass(obj) or inspect.isfunction(obj):
13
+ blocking_name = obj.__name__.lstrip("_")
14
+ elif isinstance(obj, TypeVar):
15
+ blocking_name = "_BLOCKING_" + obj.__name__
16
+ else:
17
+ blocking_name = None
18
+ if target_module is None:
19
+ target_module = obj.__module__
20
+ return synchronizer.create_blocking(obj, blocking_name, target_module=target_module)
21
+
22
+ def on_shutdown(coro):
23
+ # hook into event loop shutdown when all active tasks get cancelled
24
+ async def wrapper():
25
+ try:
26
+ await asyncio.sleep(1e10) # never awake except for exceptions
27
+ finally:
28
+ await coro
29
+ raise
30
+
31
+ _shutdown_tasks.append(asyncio.create_task(wrapper()))
@@ -0,0 +1,5 @@
1
+ from byterover.exception import DeprecationError
2
+ from datetime import date
3
+
4
+ def deprecation_error(deprecated_on: tuple[int, int, int], msg: str):
5
+ raise DeprecationError(f"Deprecated on {date(*deprecated_on)}: {msg}")
@@ -0,0 +1,69 @@
1
+ import contextlib
2
+ from typing import TYPE_CHECKING, Optional
3
+
4
+ if TYPE_CHECKING:
5
+ from aiohttp import ClientSession
6
+ from aiohttp.web import Application
7
+
8
+ from .async_utils import on_shutdown
9
+
10
+ def _http_client_with_tls(timeout: Optional[float]) -> "ClientSession":
11
+ """Create a new HTTP client session with standard, bundled TLS certificates.
12
+
13
+ This is necessary to prevent client issues on some system where Python does
14
+ not come pre-installed with specific TLS certificates that are necessary to
15
+ connect to AWS S3 bucket URLs.
16
+
17
+ Specifically: the error "unable to get local issuer certificate" when making
18
+ an aiohttp request.
19
+ """
20
+ import ssl
21
+
22
+ import certifi
23
+ from aiohttp import ClientSession, ClientTimeout, TCPConnector
24
+
25
+ ssl_context = ssl.create_default_context(cafile=certifi.where())
26
+ connector = TCPConnector(ssl=ssl_context)
27
+ return ClientSession(connector=connector, timeout=ClientTimeout(total=timeout))
28
+
29
+
30
+ class ClientSessionRegistry:
31
+ _client_session: "ClientSession"
32
+ _client_session_active: bool = False
33
+
34
+ @staticmethod
35
+ def get_session():
36
+ if not ClientSessionRegistry._client_session_active:
37
+ ClientSessionRegistry._client_session = _http_client_with_tls(timeout=None)
38
+ ClientSessionRegistry._client_session_active = True
39
+ on_shutdown(ClientSessionRegistry.close_session())
40
+ return ClientSessionRegistry._client_session
41
+
42
+ @staticmethod
43
+ async def close_session():
44
+ if ClientSessionRegistry._client_session_active:
45
+ await ClientSessionRegistry._client_session.close()
46
+ ClientSessionRegistry._client_session_active = False
47
+
48
+
49
+ @contextlib.asynccontextmanager
50
+ async def run_temporary_http_server(app: "Application"):
51
+ # Allocates a random port, runs a server in a context manager
52
+ # This is used in various tests
53
+ import socket
54
+
55
+ from aiohttp.web_runner import AppRunner, SockSite
56
+
57
+ sock = socket.socket()
58
+ sock.bind(("", 0))
59
+ port = sock.getsockname()[1]
60
+ host = f"http://127.0.0.1:{port}"
61
+
62
+ runner = AppRunner(app)
63
+ await runner.setup()
64
+ site = SockSite(runner, sock=sock)
65
+ await site.start()
66
+ try:
67
+ yield host
68
+ finally:
69
+ await runner.cleanup()
@@ -0,0 +1,19 @@
1
+ import logging
2
+ import os
3
+
4
+
5
+ def configure_logger(logger: logging.Logger, log_level: str, log_format: str):
6
+ ch = logging.StreamHandler()
7
+ log_level_numeric = logging.getLevelName(log_level.upper())
8
+ logger.setLevel(log_level_numeric)
9
+ ch.setLevel(log_level_numeric)
10
+ ch.setFormatter(logging.Formatter("[%(threadName)s] %(asctime)s %(message)s", datefmt="%Y-%m-%dT%H:%M:%S%z"))
11
+
12
+ logger.addHandler(ch)
13
+
14
+
15
+ log_level = os.environ.get("BYTEROVER_LOGLEVEL", "WARNING")
16
+ log_format = os.environ.get("BYTEROVER_LOG_FORMAT", "STRING")
17
+
18
+ logger = logging.getLogger("byterover-_utils")
19
+ configure_logger(logger, log_level, log_format)
File without changes
@@ -0,0 +1,145 @@
1
+ import httpx
2
+
3
+ import typing
4
+
5
+ from byterover.api.resource.llm_keys.client import AsyncLlmKeysClient, LlmKeysClient
6
+ from byterover.api.resource.notes.client import AsyncNotesClient
7
+ from byterover.api.resource.organizations.client import OrganizationsClient, AsyncOrganizationsClient
8
+ from byterover.api.resource.projects.client import ProjectsClient, AsyncProjectsClient
9
+ from byterover.api.resource.tokens.client import TokensClient, AsyncTokensClient
10
+ from byterover.api.core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
11
+ from byterover.config import _check_config, config
12
+ from byterover.config import BYTEROVER_SERVER_URL, STARGATE_SERVER_URL
13
+
14
+ class ByteroverClient:
15
+ def __init__(
16
+ self,
17
+ *,
18
+ base_url: str,
19
+ public_token: typing.Optional[str] = None,
20
+ secret_token: typing.Optional[str] = None,
21
+ username: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None,
22
+ timeout: typing.Optional[float] = None,
23
+ follow_redirects: typing.Optional[bool] = True,
24
+ httpx_client: typing.Optional[httpx.Client] = None
25
+ ):
26
+
27
+ _defaulted_timeout=(
28
+ timeout if timeout is not None else 60 if httpx_client is None else None
29
+ )
30
+ self._client_wrapper = SyncClientWrapper(
31
+ base_url=base_url,
32
+ public_token=public_token,
33
+ secret_token=secret_token,
34
+ username=username,
35
+ httpx_client=httpx_client
36
+ if httpx_client is not None
37
+ else httpx.Client(
38
+ timeout=_defaulted_timeout,
39
+ follow_redirects=follow_redirects,
40
+ ),
41
+ timeout=_defaulted_timeout,
42
+ )
43
+ self.tokens = TokensClient(client_wrapper=self._client_wrapper)
44
+ self.organizations = OrganizationsClient(client_wrapper=self._client_wrapper)
45
+ self.projects = ProjectsClient(client_wrapper=self._client_wrapper)
46
+ self.llm_keys = LlmKeysClient(client_wrapper=self._client_wrapper)
47
+ @classmethod
48
+ async def from_env(cls) -> "ByteroverClient":
49
+ base_url = BYTEROVER_SERVER_URL
50
+ _check_config()
51
+ c = config
52
+ public_token = c.get("public_token")
53
+ secret_token = c.get("secret_token")
54
+ username = c.get("user_name")
55
+ return cls(
56
+ base_url=base_url,
57
+ public_token=public_token,
58
+ secret_token=secret_token,
59
+ username=username,
60
+ )
61
+
62
+
63
+
64
+ class AsyncByteroverClient:
65
+ def __init__(
66
+ self,
67
+ *,
68
+ base_url: str,
69
+ public_token: typing.Optional[str] = None,
70
+ secret_token: typing.Optional[str] = None,
71
+ username: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None,
72
+ timeout: typing.Optional[float] = None,
73
+ follow_redirects: typing.Optional[bool] = True,
74
+ httpx_client: typing.Optional[httpx.AsyncClient] = None
75
+ ):
76
+ _defaulted_timeout=(
77
+ timeout if timeout is not None else 60 if httpx_client is None else None
78
+ )
79
+
80
+ self._client_wrapper = AsyncClientWrapper(
81
+ base_url=base_url,
82
+ public_token=public_token,
83
+ secret_token=secret_token,
84
+ username=username,
85
+ httpx_client=httpx_client
86
+ if httpx_client is not None
87
+ else httpx.AsyncClient(
88
+ timeout=_defaulted_timeout,
89
+ follow_redirects=follow_redirects,
90
+ ),
91
+ timeout=_defaulted_timeout,
92
+ )
93
+ self.tokens = AsyncTokensClient(client_wrapper=self._client_wrapper)
94
+ self.organizations = AsyncOrganizationsClient(client_wrapper=self._client_wrapper)
95
+ self.projects = AsyncProjectsClient(client_wrapper=self._client_wrapper)
96
+ self.llm_keys = AsyncLlmKeysClient(client_wrapper=self._client_wrapper)
97
+ self.notes = AsyncNotesClient(client_wrapper=self._client_wrapper)
98
+
99
+ @classmethod
100
+ def from_env(cls) -> "AsyncByteroverClient":
101
+ base_url = BYTEROVER_SERVER_URL
102
+ _check_config()
103
+ c = config
104
+ public_token = c.get("public_token")
105
+ secret_token = c.get("secret_token")
106
+ username = c.get("user_name")
107
+ return cls(
108
+ base_url=base_url,
109
+ public_token=public_token,
110
+ secret_token=secret_token,
111
+ username=username,
112
+ )
113
+
114
+ class AsyncStargateClient:
115
+ def __init__(
116
+ self,
117
+ httpx_client: typing.Optional[httpx.AsyncClient] = None,
118
+ timeout: typing.Optional[float] = None,
119
+ follow_redirects: bool = True,
120
+ ):
121
+ # If no client is passed, create a default one with a fallback timeout.
122
+ if httpx_client is None:
123
+ _default_timeout = 60 if timeout is None else timeout
124
+ httpx_client = httpx.AsyncClient(
125
+ timeout=_default_timeout,
126
+ follow_redirects=follow_redirects,
127
+ )
128
+
129
+ self._client_wrapper = AsyncClientWrapper(
130
+ base_url=STARGATE_SERVER_URL,
131
+ public_token=config.get("public_token"),
132
+ secret_token=config.get("secret_token"),
133
+ username=config.get("user_name"),
134
+ httpx_client=httpx_client,
135
+ timeout=timeout,
136
+ )
137
+ self.notes = AsyncNotesClient(client_wrapper=self._client_wrapper)
138
+
139
+ @classmethod
140
+ def from_env(cls) -> "AsyncStargateClient":
141
+ """
142
+ Create a StargateClient from environment/config settings.
143
+ No external httpx_client passed => we'll auto-create one.
144
+ """
145
+ return cls()
File without changes
@@ -0,0 +1,15 @@
1
+ import typing
2
+
3
+
4
+ class ApiError(Exception):
5
+ status_code: typing.Optional[int]
6
+ body: typing.Any
7
+
8
+ def __init__(
9
+ self, *, status_code: typing.Optional[int] = None, body: typing.Any = None
10
+ ):
11
+ self.status_code = status_code
12
+ self.body = body
13
+
14
+ def __str__(self) -> str:
15
+ return f"status_code: {self.status_code}, body: {self.body}"
@@ -0,0 +1,97 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ import typing
4
+
5
+ import httpx
6
+
7
+ from byterover.api.core.http_client import HttpClient, AsyncHttpClient
8
+
9
+
10
+ class BaseClientWrapper:
11
+ def __init__(
12
+ self,
13
+ *,
14
+ public_token: typing.Optional[str] = None,
15
+ secret_token: typing.Optional[str] = None,
16
+ username: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None,
17
+ base_url: str,
18
+ timeout: typing.Optional[float] = None,
19
+ ):
20
+ self._public_token = public_token
21
+ self._secret_token = secret_token
22
+ self._username = username
23
+ self._base_url = base_url
24
+ self._timeout = timeout
25
+
26
+ def get_headers(self) -> typing.Dict[str, str]:
27
+ headers: typing.Dict[str, str] = {"Content-Type": "application/json"}
28
+ public_token = self._public_token
29
+ if self._public_token is not None:
30
+ headers["x-byterover-Public-Key"] = public_token
31
+ if self._secret_token is not None:
32
+ headers["x-byterover-Secret-Key"] = self._secret_token
33
+ return headers
34
+
35
+ def _get_username(self) -> typing.Optional[str]:
36
+ if isinstance(self._username, str) or self._username is None:
37
+ return self._username
38
+ else:
39
+ return self._username()
40
+
41
+ def get_base_url(self) -> str:
42
+ return self._base_url
43
+
44
+ def get_timeout(self) -> typing.Optional[float]:
45
+ return self._timeout
46
+
47
+
48
+ class SyncClientWrapper(BaseClientWrapper):
49
+ def __init__(
50
+ self,
51
+ *,
52
+ public_token: typing.Optional[str] = None,
53
+ secret_token: typing.Optional[str] = None,
54
+ username: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None,
55
+ base_url: str,
56
+ timeout: typing.Optional[float] = None,
57
+ httpx_client: httpx.Client,
58
+ ):
59
+ super().__init__(
60
+ public_token=public_token,
61
+ secret_token=secret_token,
62
+ username=username,
63
+ base_url=base_url,
64
+ timeout=timeout,
65
+ )
66
+ self.httpx_client = HttpClient(
67
+ httpx_client=httpx_client,
68
+ base_headers=self.get_headers(),
69
+ base_timeout=self.get_timeout(),
70
+ base_url=self.get_base_url(),
71
+ )
72
+
73
+
74
+ class AsyncClientWrapper(BaseClientWrapper):
75
+ def __init__(
76
+ self,
77
+ *,
78
+ public_token: typing.Optional[str] = None,
79
+ secret_token: typing.Optional[str] = None,
80
+ username: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None,
81
+ base_url: str,
82
+ timeout: typing.Optional[float] = None,
83
+ httpx_client: httpx.AsyncClient,
84
+ ):
85
+ super().__init__(
86
+ public_token=public_token,
87
+ secret_token=secret_token,
88
+ username=username,
89
+ base_url=base_url,
90
+ timeout=timeout,
91
+ )
92
+ self.httpx_client = AsyncHttpClient(
93
+ httpx_client=httpx_client,
94
+ base_headers=self.get_headers(),
95
+ base_timeout=self.get_timeout(),
96
+ base_url=self.get_base_url(),
97
+ )
@@ -0,0 +1,28 @@
1
+ import datetime as dt
2
+
3
+
4
+ def serialize_datetime(v: dt.datetime) -> str:
5
+ """
6
+ Serialize a datetime including timezone info.
7
+
8
+ Uses the timezone info provided if present, otherwise uses the current runtime's timezone info.
9
+
10
+ UTC datetimes end in "Z" while all other timezones are represented as offset from UTC, e.g. +05:00.
11
+ """
12
+
13
+ def _serialize_zoned_datetime(v: dt.datetime) -> str:
14
+ if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(
15
+ None
16
+ ):
17
+ # UTC is a special case where we use "Z" at the end instead of "+00:00"
18
+ return v.isoformat().replace("+00:00", "Z")
19
+ else:
20
+ # Delegate to the typical +/- offset format
21
+ return v.isoformat()
22
+
23
+ if v.tzinfo is not None:
24
+ return _serialize_zoned_datetime(v)
25
+ else:
26
+ local_tz = dt.datetime.now().astimezone().tzinfo
27
+ localized_dt = v.replace(tzinfo=local_tz)
28
+ return _serialize_zoned_datetime(localized_dt)
@@ -0,0 +1,43 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ import typing
4
+
5
+ # File typing inspired by the flexibility of types within the httpx library
6
+ # https://github.com/encode/httpx/blob/master/httpx/_types.py
7
+ FileContent = typing.Union[typing.IO[bytes], bytes, str]
8
+ File = typing.Union[
9
+ # file (or bytes)
10
+ FileContent,
11
+ # (filename, file (or bytes))
12
+ typing.Tuple[typing.Optional[str], FileContent],
13
+ # (filename, file (or bytes), content_type)
14
+ typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]],
15
+ # (filename, file (or bytes), content_type, headers)
16
+ typing.Tuple[
17
+ typing.Optional[str],
18
+ FileContent,
19
+ typing.Optional[str],
20
+ typing.Mapping[str, str],
21
+ ],
22
+ ]
23
+
24
+
25
+ def convert_file_dict_to_httpx_tuples(
26
+ d: typing.Dict[str, typing.Union[File, typing.List[File]]],
27
+ ) -> typing.List[typing.Tuple[str, File]]:
28
+ """
29
+ The format we use is a list of tuples, where the first element is the
30
+ name of the file and the second is the file object. Typically HTTPX wants
31
+ a dict, but to be able to send lists of files, you have to use the list
32
+ approach (which also works for non-lists)
33
+ https://github.com/encode/httpx/pull/1032
34
+ """
35
+
36
+ httpx_tuples = []
37
+ for key, file_like in d.items():
38
+ if isinstance(file_like, list):
39
+ for file_like_item in file_like:
40
+ httpx_tuples.append((key, file_like_item))
41
+ else:
42
+ httpx_tuples.append((key, file_like))
43
+ return httpx_tuples