clearideas-agent-runtime 1.0.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.
- clearideas_agent_runtime/__init__.py +114 -0
- clearideas_agent_runtime/_js/__init__.py +8 -0
- clearideas_agent_runtime/_js/abort.py +147 -0
- clearideas_agent_runtime/_js/base64.py +31 -0
- clearideas_agent_runtime/_js/collation.py +27 -0
- clearideas_agent_runtime/_js/errors.py +57 -0
- clearideas_agent_runtime/_js/fetch.py +130 -0
- clearideas_agent_runtime/_js/json.py +293 -0
- clearideas_agent_runtime/_js/json_syntax.py +313 -0
- clearideas_agent_runtime/_js/ops.py +240 -0
- clearideas_agent_runtime/_js/regex.py +18 -0
- clearideas_agent_runtime/_js/strings.py +129 -0
- clearideas_agent_runtime/_js/time.py +95 -0
- clearideas_agent_runtime/_js/url.py +48 -0
- clearideas_agent_runtime/_js/yaml.py +151 -0
- clearideas_agent_runtime/agent.py +104 -0
- clearideas_agent_runtime/artifacts.py +208 -0
- clearideas_agent_runtime/cli.py +641 -0
- clearideas_agent_runtime/conditions/__init__.py +5 -0
- clearideas_agent_runtime/conditions/jexl.py +202 -0
- clearideas_agent_runtime/conditions/jexl_parser.py +532 -0
- clearideas_agent_runtime/config/__init__.py +56 -0
- clearideas_agent_runtime/config/compose.py +163 -0
- clearideas_agent_runtime/config/composite_tools.py +70 -0
- clearideas_agent_runtime/config/mcp_integrity.py +92 -0
- clearideas_agent_runtime/config/mcp_tools.py +652 -0
- clearideas_agent_runtime/config/messages.py +37 -0
- clearideas_agent_runtime/config/providers.py +274 -0
- clearideas_agent_runtime/config/run_sandbox.py +49 -0
- clearideas_agent_runtime/config/schema.py +446 -0
- clearideas_agent_runtime/config/values.py +54 -0
- clearideas_agent_runtime/config/workspace_tools.py +213 -0
- clearideas_agent_runtime/config/workspaces.py +106 -0
- clearideas_agent_runtime/contracts/__init__.py +201 -0
- clearideas_agent_runtime/contracts/_zod.py +953 -0
- clearideas_agent_runtime/contracts/schemas.py +1429 -0
- clearideas_agent_runtime/contracts/types.py +54 -0
- clearideas_agent_runtime/core/__init__.py +28 -0
- clearideas_agent_runtime/core/errors.py +206 -0
- clearideas_agent_runtime/core/execution_plan.py +97 -0
- clearideas_agent_runtime/core/limits.py +302 -0
- clearideas_agent_runtime/core/messages.py +860 -0
- clearideas_agent_runtime/core/policies.py +64 -0
- clearideas_agent_runtime/core/ports.py +241 -0
- clearideas_agent_runtime/core/runtime.py +2562 -0
- clearideas_agent_runtime/core/state.py +78 -0
- clearideas_agent_runtime/core/templates.py +42 -0
- clearideas_agent_runtime/core/testing.py +112 -0
- clearideas_agent_runtime/core/version.py +3 -0
- clearideas_agent_runtime/execution/__init__.py +22 -0
- clearideas_agent_runtime/execution/_records.py +68 -0
- clearideas_agent_runtime/execution/child_process.py +157 -0
- clearideas_agent_runtime/execution/client.py +70 -0
- clearideas_agent_runtime/execution/contracts.py +57 -0
- clearideas_agent_runtime/execution/in_process.py +244 -0
- clearideas_agent_runtime/execution/remote.py +210 -0
- clearideas_agent_runtime/execution/secure_invocation.py +306 -0
- clearideas_agent_runtime/execution/worker_protocol.py +184 -0
- clearideas_agent_runtime/models/__init__.py +6 -0
- clearideas_agent_runtime/models/ai_sdk/__init__.py +7 -0
- clearideas_agent_runtime/models/ai_sdk/anthropic.py +562 -0
- clearideas_agent_runtime/models/ai_sdk/capture.py +351 -0
- clearideas_agent_runtime/models/ai_sdk/chat_completions.py +404 -0
- clearideas_agent_runtime/models/ai_sdk/cohere_chat.py +159 -0
- clearideas_agent_runtime/models/ai_sdk/core.py +721 -0
- clearideas_agent_runtime/models/ai_sdk/errors.py +268 -0
- clearideas_agent_runtime/models/ai_sdk/google.py +357 -0
- clearideas_agent_runtime/models/ai_sdk/openai_responses.py +424 -0
- clearideas_agent_runtime/models/ai_sdk/results.py +123 -0
- clearideas_agent_runtime/models/ai_sdk/shape.py +62 -0
- clearideas_agent_runtime/models/ai_sdk/tool_calls.py +262 -0
- clearideas_agent_runtime/models/ai_sdk/xai_responses.py +341 -0
- clearideas_agent_runtime/models/cohere.py +191 -0
- clearideas_agent_runtime/models/google.py +37 -0
- clearideas_agent_runtime/models/groq.py +45 -0
- clearideas_agent_runtime/models/openai.py +109 -0
- clearideas_agent_runtime/models/provider_options.py +350 -0
- clearideas_agent_runtime/models/providers.py +173 -0
- clearideas_agent_runtime/models/pydantic_ai.py +1116 -0
- clearideas_agent_runtime/models/responses_input.py +190 -0
- clearideas_agent_runtime/sandbox/__init__.py +9 -0
- clearideas_agent_runtime/sandbox/_process.py +169 -0
- clearideas_agent_runtime/sandbox/assets/agent-fs.py +555 -0
- clearideas_agent_runtime/sandbox/bubblewrap.py +344 -0
- clearideas_agent_runtime/sandbox/contracts.py +82 -0
- clearideas_agent_runtime/sandbox/docker.py +179 -0
- clearideas_agent_runtime/sandbox/modal.py +62 -0
- clearideas_agent_runtime/sandbox/policy.py +774 -0
- clearideas_agent_runtime/sandbox/provider_adapter.py +192 -0
- clearideas_agent_runtime/sandbox/run_sandbox.py +942 -0
- clearideas_agent_runtime/sandbox/testing.py +231 -0
- clearideas_agent_runtime/steps/__init__.py +1 -0
- clearideas_agent_runtime/steps/loop.py +401 -0
- clearideas_agent_runtime/steps/prompt/__init__.py +110 -0
- clearideas_agent_runtime/steps/prompt/context/__init__.py +1 -0
- clearideas_agent_runtime/steps/prompt/context/errors.py +194 -0
- clearideas_agent_runtime/steps/prompt/context/measure.py +122 -0
- clearideas_agent_runtime/steps/prompt/context/opening.py +165 -0
- clearideas_agent_runtime/steps/prompt/context/prune.py +188 -0
- clearideas_agent_runtime/steps/prompt/context/summarize.py +252 -0
- clearideas_agent_runtime/steps/prompt/context/template.py +88 -0
- clearideas_agent_runtime/steps/prompt/context/transcript.py +239 -0
- clearideas_agent_runtime/steps/prompt/execution.py +2132 -0
- clearideas_agent_runtime/steps/prompt/helpers.py +266 -0
- clearideas_agent_runtime/steps/prompt/history_compactor.py +359 -0
- clearideas_agent_runtime/steps/standard.py +844 -0
- clearideas_agent_runtime/stores/__init__.py +1 -0
- clearideas_agent_runtime/stores/local/__init__.py +40 -0
- clearideas_agent_runtime/stores/local/files.py +299 -0
- clearideas_agent_runtime/stores/local/run_stores.py +386 -0
- clearideas_agent_runtime/stores/local/workspaces.py +338 -0
- clearideas_agent_runtime/stores/sqlite.py +282 -0
- clearideas_agent_runtime/telemetry.py +280 -0
- clearideas_agent_runtime-1.0.0.dist-info/METADATA +227 -0
- clearideas_agent_runtime-1.0.0.dist-info/RECORD +119 -0
- clearideas_agent_runtime-1.0.0.dist-info/WHEEL +4 -0
- clearideas_agent_runtime-1.0.0.dist-info/entry_points.txt +2 -0
- clearideas_agent_runtime-1.0.0.dist-info/licenses/LICENSE +201 -0
- clearideas_agent_runtime-1.0.0.dist-info/licenses/NOTICE +8 -0
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Clear Ideas Agent Runtime for Python.
|
|
2
|
+
|
|
3
|
+
Like ``@clearideas/agent-runtime``, the top-level package is the standard
|
|
4
|
+
composition (``create_agent_runtime``, ``define_agent``) and re-exports the
|
|
5
|
+
public API of every subpackage, so hosts can write::
|
|
6
|
+
|
|
7
|
+
from clearideas_agent_runtime import AgentRuntime, FileRunStore, compose_runtime
|
|
8
|
+
|
|
9
|
+
The subpackages mirror the TypeScript packages: ``contracts``, ``core``,
|
|
10
|
+
``conditions``, ``steps`` (``prompt``, ``loop``, ``standard``), ``stores``
|
|
11
|
+
(``local``, ``sqlite``), ``models``, ``config``, ``sandbox``, ``artifacts``,
|
|
12
|
+
``execution``, and ``telemetry``. The pydantic-ai model adapter
|
|
13
|
+
(``PydanticAIModelAdapter`` and its helpers) needs the ``providers`` extra and
|
|
14
|
+
is imported on first use.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import importlib
|
|
20
|
+
import types as _types
|
|
21
|
+
from typing import TYPE_CHECKING, Any
|
|
22
|
+
|
|
23
|
+
from ._js.abort import AbortController, AbortError, AbortSignal
|
|
24
|
+
from .agent import create_agent_runtime, define_agent
|
|
25
|
+
from .core.version import RUNTIME_VERSION
|
|
26
|
+
|
|
27
|
+
# The packages ``@clearideas/agent-runtime`` re-exports, in the same order.
|
|
28
|
+
_EAGER = (
|
|
29
|
+
"conditions",
|
|
30
|
+
"config",
|
|
31
|
+
"contracts",
|
|
32
|
+
"core",
|
|
33
|
+
"execution",
|
|
34
|
+
"sandbox",
|
|
35
|
+
"steps.loop",
|
|
36
|
+
"steps.prompt",
|
|
37
|
+
"steps.standard",
|
|
38
|
+
"stores.local",
|
|
39
|
+
)
|
|
40
|
+
# Imported on first use: they need the ``providers`` extra.
|
|
41
|
+
_LAZY = ("models.pydantic_ai", "models.providers")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _public_names(module: _types.ModuleType) -> list[str]:
|
|
45
|
+
names = getattr(module, "__all__", None)
|
|
46
|
+
if names is None:
|
|
47
|
+
names = [name for name in vars(module) if not name.startswith("_")]
|
|
48
|
+
# Submodules and typing aliases such as ``JsonObject`` are not part of the API.
|
|
49
|
+
return [
|
|
50
|
+
name
|
|
51
|
+
for name in names
|
|
52
|
+
if name not in ("JsonObject", "annotations") and not isinstance(getattr(module, name, None), _types.ModuleType)
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _eager_exports() -> dict[str, Any]:
|
|
57
|
+
exports: dict[str, Any] = {}
|
|
58
|
+
for name in _EAGER:
|
|
59
|
+
module = importlib.import_module(f".{name}", __name__)
|
|
60
|
+
for export in _public_names(module):
|
|
61
|
+
exports.setdefault(export, getattr(module, export))
|
|
62
|
+
return exports
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
_exports = _eager_exports()
|
|
66
|
+
globals().update(_exports)
|
|
67
|
+
|
|
68
|
+
_lazy_names: dict[str, str] | None = None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def __getattr__(name: str) -> Any:
|
|
72
|
+
global _lazy_names
|
|
73
|
+
if _lazy_names is None:
|
|
74
|
+
_lazy_names = {}
|
|
75
|
+
for module_name in _LAZY:
|
|
76
|
+
try:
|
|
77
|
+
module = importlib.import_module(f".{module_name}", __name__)
|
|
78
|
+
except ImportError:
|
|
79
|
+
continue
|
|
80
|
+
for export in _public_names(module):
|
|
81
|
+
_lazy_names.setdefault(export, module_name)
|
|
82
|
+
module_name = _lazy_names.get(name)
|
|
83
|
+
if module_name is None:
|
|
84
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
85
|
+
value = getattr(importlib.import_module(f".{module_name}", __name__), name)
|
|
86
|
+
globals()[name] = value
|
|
87
|
+
return value
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
if TYPE_CHECKING:
|
|
91
|
+
from .conditions import *
|
|
92
|
+
from .config import *
|
|
93
|
+
from .contracts import *
|
|
94
|
+
from .core import *
|
|
95
|
+
from .execution import *
|
|
96
|
+
from .models.providers import create_model_factory
|
|
97
|
+
from .models.pydantic_ai import *
|
|
98
|
+
from .sandbox import *
|
|
99
|
+
from .steps.loop import *
|
|
100
|
+
from .steps.prompt import *
|
|
101
|
+
from .steps.standard import *
|
|
102
|
+
from .stores.local import *
|
|
103
|
+
|
|
104
|
+
# Assigned through globals() so type checkers read the public names from the
|
|
105
|
+
# imports above rather than from a computed list.
|
|
106
|
+
globals()["__all__"] = [
|
|
107
|
+
"RUNTIME_VERSION",
|
|
108
|
+
"AbortController",
|
|
109
|
+
"AbortError",
|
|
110
|
+
"AbortSignal",
|
|
111
|
+
"create_agent_runtime",
|
|
112
|
+
"define_agent",
|
|
113
|
+
*sorted(_exports),
|
|
114
|
+
]
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""JavaScript-compatible primitives.
|
|
2
|
+
|
|
3
|
+
The TypeScript runtime's observable output (hashes, checkpoints, events, error
|
|
4
|
+
text) depends on JavaScript semantics: JSON.stringify key order and number
|
|
5
|
+
formatting, UTF-16 string lengths, ICU collation, YAML 1.2, WHATWG URLs. These
|
|
6
|
+
modules reproduce those semantics on top of maintained libraries so the Python
|
|
7
|
+
runtime produces byte-identical results.
|
|
8
|
+
"""
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""AbortController / AbortSignal for asyncio.
|
|
2
|
+
|
|
3
|
+
The TypeScript runtime passes an ``AbortSignal`` through every layer and uses
|
|
4
|
+
``signal.reason`` to carry suspension and interruption errors. This module
|
|
5
|
+
provides the same contract.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import contextlib
|
|
12
|
+
from collections.abc import Awaitable, Callable, Iterable
|
|
13
|
+
from typing import Any, TypeVar
|
|
14
|
+
|
|
15
|
+
T = TypeVar("T")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AbortError(Exception):
|
|
19
|
+
"""DOMException AbortError equivalent."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, message: str = "This operation was aborted") -> None:
|
|
22
|
+
super().__init__(message)
|
|
23
|
+
self.name = "AbortError"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class TimeoutError_(Exception):
|
|
27
|
+
def __init__(self, message: str = "The operation was aborted due to timeout") -> None:
|
|
28
|
+
super().__init__(message)
|
|
29
|
+
self.name = "TimeoutError"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class AbortSignal:
|
|
33
|
+
def __init__(self) -> None:
|
|
34
|
+
self._aborted = False
|
|
35
|
+
self._reason: Any = None
|
|
36
|
+
self._listeners: list[Callable[[], None]] = []
|
|
37
|
+
self._event: asyncio.Event | None = None
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def aborted(self) -> bool:
|
|
41
|
+
return self._aborted
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def reason(self) -> Any:
|
|
45
|
+
return self._reason
|
|
46
|
+
|
|
47
|
+
def throw_if_aborted(self) -> None:
|
|
48
|
+
if self._aborted:
|
|
49
|
+
reason = self._reason
|
|
50
|
+
if isinstance(reason, BaseException):
|
|
51
|
+
raise reason
|
|
52
|
+
raise AbortError()
|
|
53
|
+
|
|
54
|
+
def add_listener(self, listener: Callable[[], None]) -> Callable[[], None]:
|
|
55
|
+
"""Registers ``listener`` for the abort event; returns a remover."""
|
|
56
|
+
if self._aborted:
|
|
57
|
+
listener()
|
|
58
|
+
return lambda: None
|
|
59
|
+
self._listeners.append(listener)
|
|
60
|
+
|
|
61
|
+
def remove() -> None:
|
|
62
|
+
with contextlib.suppress(ValueError):
|
|
63
|
+
self._listeners.remove(listener)
|
|
64
|
+
|
|
65
|
+
return remove
|
|
66
|
+
|
|
67
|
+
def _abort(self, reason: Any) -> None:
|
|
68
|
+
if self._aborted:
|
|
69
|
+
return
|
|
70
|
+
self._aborted = True
|
|
71
|
+
self._reason = AbortError() if reason is None else reason
|
|
72
|
+
if self._event is not None:
|
|
73
|
+
self._event.set()
|
|
74
|
+
listeners, self._listeners = self._listeners, []
|
|
75
|
+
for listener in listeners:
|
|
76
|
+
listener()
|
|
77
|
+
|
|
78
|
+
async def wait(self) -> None:
|
|
79
|
+
if self._aborted:
|
|
80
|
+
return
|
|
81
|
+
if self._event is None:
|
|
82
|
+
self._event = asyncio.Event()
|
|
83
|
+
await self._event.wait()
|
|
84
|
+
|
|
85
|
+
@staticmethod
|
|
86
|
+
def abort(reason: Any = None) -> AbortSignal:
|
|
87
|
+
signal = AbortSignal()
|
|
88
|
+
signal._abort(reason)
|
|
89
|
+
return signal
|
|
90
|
+
|
|
91
|
+
@staticmethod
|
|
92
|
+
def timeout(ms: float) -> AbortSignal:
|
|
93
|
+
signal = AbortSignal()
|
|
94
|
+
loop = asyncio.get_running_loop()
|
|
95
|
+
loop.call_later(ms / 1000, lambda: signal._abort(TimeoutError_()))
|
|
96
|
+
return signal
|
|
97
|
+
|
|
98
|
+
@staticmethod
|
|
99
|
+
def any(signals: Iterable[AbortSignal | None]) -> AbortSignal:
|
|
100
|
+
combined = AbortSignal()
|
|
101
|
+
sources = [signal for signal in signals if signal is not None]
|
|
102
|
+
for source in sources:
|
|
103
|
+
if source.aborted:
|
|
104
|
+
combined._abort(source.reason)
|
|
105
|
+
return combined
|
|
106
|
+
for source in sources:
|
|
107
|
+
source.add_listener(lambda source=source: combined._abort(source.reason))
|
|
108
|
+
return combined
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class AbortController:
|
|
112
|
+
def __init__(self) -> None:
|
|
113
|
+
self.signal = AbortSignal()
|
|
114
|
+
|
|
115
|
+
def abort(self, reason: Any = None) -> None:
|
|
116
|
+
self.signal._abort(reason)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def abort_reason_error(signal: AbortSignal) -> BaseException:
|
|
120
|
+
reason = signal.reason
|
|
121
|
+
return reason if isinstance(reason, BaseException) else AbortError()
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
async def race_abort(awaitable: Awaitable[T], signal: AbortSignal | None) -> T:
|
|
125
|
+
"""Await ``awaitable`` unless ``signal`` aborts first (then raise its reason)."""
|
|
126
|
+
if signal is None:
|
|
127
|
+
return await awaitable
|
|
128
|
+
signal.throw_if_aborted()
|
|
129
|
+
task = asyncio.ensure_future(awaitable)
|
|
130
|
+
waiter = asyncio.ensure_future(signal.wait())
|
|
131
|
+
try:
|
|
132
|
+
done, _ = await asyncio.wait({task, waiter}, return_when=asyncio.FIRST_COMPLETED)
|
|
133
|
+
except BaseException:
|
|
134
|
+
task.cancel()
|
|
135
|
+
waiter.cancel()
|
|
136
|
+
raise
|
|
137
|
+
if task in done:
|
|
138
|
+
waiter.cancel()
|
|
139
|
+
return task.result()
|
|
140
|
+
task.cancel()
|
|
141
|
+
with contextlib.suppress(BaseException):
|
|
142
|
+
await task
|
|
143
|
+
raise abort_reason_error(signal)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
async def sleep(ms: float, signal: AbortSignal | None = None) -> None:
|
|
147
|
+
await race_abort(asyncio.sleep(max(ms, 0) / 1000), signal)
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""``atob``/``btoa`` and base64url helpers with browser semantics."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64 as _base64
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
_ALPHABET = re.compile(r"^[A-Za-z0-9+/]*$")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def atob(value: str) -> bytes:
|
|
12
|
+
"""Forgiving-base64 decode (HTML spec), as ``atob`` performs it."""
|
|
13
|
+
data = re.sub(r"[\t\n\f\r ]", "", value)
|
|
14
|
+
if len(data) % 4 == 0 and data.endswith("="):
|
|
15
|
+
data = data[:-2] if data.endswith("==") else data[:-1]
|
|
16
|
+
if len(data) % 4 == 1 or not _ALPHABET.fullmatch(data):
|
|
17
|
+
raise ValueError("The string to be decoded is not correctly encoded.")
|
|
18
|
+
return _base64.b64decode(data + "=" * (-len(data) % 4))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def btoa(data: bytes) -> str:
|
|
22
|
+
return _base64.b64encode(data).decode("ascii")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def to_base64url(data: bytes) -> str:
|
|
26
|
+
return _base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def from_base64url(value: str) -> bytes:
|
|
30
|
+
normalized = value.replace("-", "+").replace("_", "/")
|
|
31
|
+
return atob(normalized + "=" * ((4 - len(normalized) % 4) % 4))
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""``String.prototype.localeCompare`` with ICU, as Node uses it.
|
|
2
|
+
|
|
3
|
+
The TypeScript manifest hasher orders keys with ``localeCompare``. ICU 77 is the
|
|
4
|
+
version bundled with Node 22, and ``pyicu-wheels`` ships the same version, so
|
|
5
|
+
the comparison is made by the same collation engine.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import functools
|
|
11
|
+
from collections.abc import Iterable
|
|
12
|
+
|
|
13
|
+
import icu
|
|
14
|
+
|
|
15
|
+
_COLLATOR = icu.Collator.createInstance(icu.Locale("en")) # pyright: ignore[reportAttributeAccessIssue]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def locale_compare(left: str, right: str) -> int:
|
|
19
|
+
return _COLLATOR.compare(left, right)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def locale_sorted(values: Iterable[str]) -> list[str]:
|
|
23
|
+
"""``[...values].sort((a, b) => a.localeCompare(b))`` (stable)."""
|
|
24
|
+
return sorted(values, key=functools.cmp_to_key(locale_compare))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
ICU_VERSION: str = icu.ICU_VERSION # pyright: ignore[reportAttributeAccessIssue]
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""JavaScript error identity.
|
|
2
|
+
|
|
3
|
+
The TypeScript runtime classifies errors by ``error.name`` and ``error.code``
|
|
4
|
+
and records ``name`` in ``RunError.details``. Python exceptions carry the same
|
|
5
|
+
attributes: ``Error`` is ``new Error(message)``; subclasses set ``name``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Error(Exception):
|
|
14
|
+
"""``new Error(message)``."""
|
|
15
|
+
|
|
16
|
+
name = "Error"
|
|
17
|
+
|
|
18
|
+
def __init__(self, message: str = "", *, cause: Any = None) -> None:
|
|
19
|
+
super().__init__(message)
|
|
20
|
+
self.message = message
|
|
21
|
+
if cause is not None:
|
|
22
|
+
self.cause = cause
|
|
23
|
+
|
|
24
|
+
def __str__(self) -> str:
|
|
25
|
+
return self.message
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class TypeError_(Error):
|
|
29
|
+
"""``new TypeError(message)``."""
|
|
30
|
+
|
|
31
|
+
name = "TypeError"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class RangeError(Error):
|
|
35
|
+
name = "RangeError"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class SyntaxError_(Error, ValueError):
|
|
39
|
+
"""``new SyntaxError(message)`` (also a ``ValueError``, for Python callers)."""
|
|
40
|
+
|
|
41
|
+
name = "SyntaxError"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def error_name(error: BaseException) -> str:
|
|
45
|
+
"""``error.name``: the JavaScript name, or the Python class name."""
|
|
46
|
+
name = getattr(error, "name", None)
|
|
47
|
+
if isinstance(name, str):
|
|
48
|
+
return name
|
|
49
|
+
return type(error).__name__
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def error_message(error: BaseException) -> str:
|
|
53
|
+
"""``error.message`` (``String(error)`` for values that are not errors)."""
|
|
54
|
+
message = getattr(error, "message", None)
|
|
55
|
+
if isinstance(message, str):
|
|
56
|
+
return message
|
|
57
|
+
return str(error)
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""A ``fetch``-shaped HTTP seam (``Headers``, ``Response``, ``fetch``) backed by httpx.
|
|
2
|
+
|
|
3
|
+
Executors accept any async ``fetch(url, init)`` returning an object with
|
|
4
|
+
``status``, ``ok``, ``headers`` and an async byte stream, like the WHATWG
|
|
5
|
+
``Response`` the TypeScript executors receive.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json as _json
|
|
11
|
+
from collections.abc import AsyncIterator, Iterable, Mapping
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import httpx
|
|
15
|
+
|
|
16
|
+
from .abort import AbortSignal, race_abort
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Headers:
|
|
20
|
+
"""Case-insensitive headers (``new Headers(init)``)."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, init: Mapping[str, str] | Iterable[tuple[str, str]] | Headers | None = None) -> None:
|
|
23
|
+
self._values: dict[str, str] = {}
|
|
24
|
+
if isinstance(init, Headers):
|
|
25
|
+
self._values = dict(init._values)
|
|
26
|
+
elif isinstance(init, Mapping):
|
|
27
|
+
for name, value in init.items():
|
|
28
|
+
self.set(name, value) # pyright: ignore[reportArgumentType]
|
|
29
|
+
elif init is not None:
|
|
30
|
+
for name, value in init:
|
|
31
|
+
self.set(name, value)
|
|
32
|
+
|
|
33
|
+
def get(self, name: str) -> str | None:
|
|
34
|
+
return self._values.get(name.lower())
|
|
35
|
+
|
|
36
|
+
def has(self, name: str) -> bool:
|
|
37
|
+
return name.lower() in self._values
|
|
38
|
+
|
|
39
|
+
def set(self, name: str, value: str) -> None:
|
|
40
|
+
self._values[name.lower()] = str(value)
|
|
41
|
+
|
|
42
|
+
def items(self) -> list[tuple[str, str]]:
|
|
43
|
+
return sorted(self._values.items())
|
|
44
|
+
|
|
45
|
+
def __iter__(self):
|
|
46
|
+
return iter(self.items())
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class Response:
|
|
50
|
+
"""A WHATWG-style response over an async byte stream."""
|
|
51
|
+
|
|
52
|
+
def __init__(
|
|
53
|
+
self,
|
|
54
|
+
body: bytes | str | None = None,
|
|
55
|
+
*,
|
|
56
|
+
status: int = 200,
|
|
57
|
+
headers: Mapping[str, str] | Headers | None = None,
|
|
58
|
+
stream: AsyncIterator[bytes] | None = None,
|
|
59
|
+
on_close: Any = None,
|
|
60
|
+
) -> None:
|
|
61
|
+
self.status = status
|
|
62
|
+
self.headers = headers if isinstance(headers, Headers) else Headers(headers)
|
|
63
|
+
if isinstance(body, str):
|
|
64
|
+
body = body.encode("utf-8")
|
|
65
|
+
self._body = body
|
|
66
|
+
self._stream = stream
|
|
67
|
+
self._on_close = on_close
|
|
68
|
+
self.cancelled = False
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def ok(self) -> bool:
|
|
72
|
+
return 200 <= self.status <= 299
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def has_body(self) -> bool:
|
|
76
|
+
return self._body is not None or self._stream is not None
|
|
77
|
+
|
|
78
|
+
async def iter_bytes(self) -> AsyncIterator[bytes]:
|
|
79
|
+
if self._stream is not None:
|
|
80
|
+
async for chunk in self._stream:
|
|
81
|
+
yield chunk
|
|
82
|
+
elif self._body:
|
|
83
|
+
yield self._body
|
|
84
|
+
|
|
85
|
+
async def cancel(self) -> None:
|
|
86
|
+
"""``response.body.cancel()``."""
|
|
87
|
+
self.cancelled = True
|
|
88
|
+
await self.aclose()
|
|
89
|
+
|
|
90
|
+
async def aclose(self) -> None:
|
|
91
|
+
"""Release the underlying connection (after the body was read)."""
|
|
92
|
+
if self._on_close is not None:
|
|
93
|
+
on_close, self._on_close = self._on_close, None
|
|
94
|
+
await on_close()
|
|
95
|
+
|
|
96
|
+
@staticmethod
|
|
97
|
+
def json(value: Any, *, status: int = 200, headers: Mapping[str, str] | None = None) -> Response:
|
|
98
|
+
merged = {"content-type": "application/json", **(headers or {})}
|
|
99
|
+
return Response(_json.dumps(value), status=status, headers=merged)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
async def fetch(url: str, init: Mapping[str, Any] | None = None) -> Response:
|
|
103
|
+
"""``fetch`` over httpx. Redirects are not followed (``redirect: "manual"``)."""
|
|
104
|
+
init = dict(init or {})
|
|
105
|
+
headers = init.get("headers")
|
|
106
|
+
header_items = headers.items() if isinstance(headers, Headers) else list((headers or {}).items())
|
|
107
|
+
signal: AbortSignal | None = init.get("signal")
|
|
108
|
+
client = httpx.AsyncClient(follow_redirects=False, timeout=None)
|
|
109
|
+
request = client.build_request(init.get("method", "GET"), url, headers=header_items, content=init.get("body"))
|
|
110
|
+
|
|
111
|
+
async def send() -> httpx.Response:
|
|
112
|
+
return await client.send(request, stream=True)
|
|
113
|
+
|
|
114
|
+
try:
|
|
115
|
+
response = await race_abort(send(), signal)
|
|
116
|
+
except BaseException:
|
|
117
|
+
await client.aclose()
|
|
118
|
+
raise
|
|
119
|
+
|
|
120
|
+
async def stream() -> AsyncIterator[bytes]:
|
|
121
|
+
async for chunk in response.aiter_raw():
|
|
122
|
+
yield chunk
|
|
123
|
+
|
|
124
|
+
async def close() -> None:
|
|
125
|
+
await response.aclose()
|
|
126
|
+
await client.aclose()
|
|
127
|
+
|
|
128
|
+
return Response(
|
|
129
|
+
status=response.status_code, headers=Headers(list(response.headers.items())), stream=stream(), on_close=close
|
|
130
|
+
)
|