rexlib-py 0.9.0a1__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 (58) hide show
  1. rexlib/__init__.py +75 -0
  2. rexlib/cli/__init__.py +44 -0
  3. rexlib/cli/commands.py +99 -0
  4. rexlib/cli/console.py +83 -0
  5. rexlib/cli/options.py +47 -0
  6. rexlib/cli/permissions.py +174 -0
  7. rexlib/cli/render.py +78 -0
  8. rexlib/cli/repl.py +97 -0
  9. rexlib/cli/session.py +99 -0
  10. rexlib/container/__init__.py +33 -0
  11. rexlib/container/detect.py +151 -0
  12. rexlib/container/model.py +111 -0
  13. rexlib/container/probe.py +191 -0
  14. rexlib/container/resolve.py +151 -0
  15. rexlib/gateway/__init__.py +56 -0
  16. rexlib/gateway/attempts.py +51 -0
  17. rexlib/gateway/audit.py +173 -0
  18. rexlib/gateway/config.py +383 -0
  19. rexlib/gateway/costs.py +157 -0
  20. rexlib/gateway/keys.py +46 -0
  21. rexlib/gateway/presets.py +59 -0
  22. rexlib/gateway/prices.py +134 -0
  23. rexlib/gateway/router.py +391 -0
  24. rexlib/gateway/stream.py +224 -0
  25. rexlib/loop/__init__.py +63 -0
  26. rexlib/loop/calls.py +220 -0
  27. rexlib/loop/core.py +249 -0
  28. rexlib/loop/options.py +149 -0
  29. rexlib/loop/stream.py +88 -0
  30. rexlib/messages.py +221 -0
  31. rexlib/providers/__init__.py +11 -0
  32. rexlib/providers/anthropic.py +108 -0
  33. rexlib/providers/base.py +53 -0
  34. rexlib/providers/errors.py +191 -0
  35. rexlib/providers/http.py +124 -0
  36. rexlib/providers/openai.py +148 -0
  37. rexlib/providers/transport.py +163 -0
  38. rexlib/py.typed +0 -0
  39. rexlib/storage/__init__.py +30 -0
  40. rexlib/storage/base.py +144 -0
  41. rexlib/storage/contract.py +262 -0
  42. rexlib/storage/registry.py +49 -0
  43. rexlib/storage/sqlite.py +219 -0
  44. rexlib/testing.py +160 -0
  45. rexlib/tools/__init__.py +12 -0
  46. rexlib/tools/base.py +116 -0
  47. rexlib/tools/executor.py +105 -0
  48. rexlib/tools/function_tool.py +168 -0
  49. rexlib/tools/registry.py +66 -0
  50. rexlib/wire/__init__.py +6 -0
  51. rexlib/wire/anthropic_messages.py +300 -0
  52. rexlib/wire/openai_chat.py +134 -0
  53. rexlib/wire/sse.py +85 -0
  54. rexlib_py-0.9.0a1.dist-info/METADATA +251 -0
  55. rexlib_py-0.9.0a1.dist-info/RECORD +58 -0
  56. rexlib_py-0.9.0a1.dist-info/WHEEL +5 -0
  57. rexlib_py-0.9.0a1.dist-info/licenses/LICENSE +21 -0
  58. rexlib_py-0.9.0a1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,191 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2026 Peter Kokosharov <peter.kokosharov@gmail.com>
3
+ # AI models: claude-opus-5-5
4
+ # Licensed under MIT License
5
+ """What detection may look at, behind one injectable ``Probe``: environment, a few small files, parent process
6
+ names, the OS name and the standard streams. No network, no subprocess; every reader returns a neutral value
7
+ instead of raising (best-effort: a hint, never a security fact).
8
+
9
+ Parent process names: Linux reads ``/proc/<pid>/stat`` and ``/proc/<pid>/comm``; Windows walks a
10
+ ``CreateToolhelp32Snapshot`` process list through ``ctypes``; other systems give ``()``.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import stat
17
+ import sys
18
+ from collections.abc import Callable, Mapping
19
+ from dataclasses import dataclass, field
20
+
21
+ MAX_FILE_BYTES = 64 * 1024
22
+ MAX_PARENTS = 6
23
+
24
+
25
+ def read_regular(path: str | os.PathLike[str], limit: int = MAX_FILE_BYTES) -> bytes | None:
26
+ """The first ``limit`` bytes of a REGULAR file, ``None`` when it is missing, unreadable or something else. Opened
27
+ with ``O_NONBLOCK`` (where the OS has it) and checked with ``fstat`` before reading, so a FIFO or device put in
28
+ place of the file can never block detection."""
29
+ try:
30
+ fd = os.open(path, os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0))
31
+ except (OSError, ValueError):
32
+ return None
33
+ try:
34
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
35
+ return None
36
+ chunks: list[bytes] = []
37
+ left = limit
38
+ while left > 0:
39
+ chunk = os.read(fd, left)
40
+ if not chunk:
41
+ break
42
+ chunks.append(chunk)
43
+ left -= len(chunk)
44
+ return b"".join(chunks)
45
+ except (OSError, ValueError):
46
+ return None
47
+ finally:
48
+ os.close(fd)
49
+
50
+
51
+ def read_text(path: str) -> str | None:
52
+ """The first ``MAX_FILE_BYTES`` of a regular text file, ``None`` when it is missing, unreadable or not regular."""
53
+ data = read_regular(path)
54
+ return None if data is None else data.decode("utf-8", errors="replace")
55
+
56
+
57
+ def walk_parents(table: Mapping[int, tuple[int, str]], pid: int, limit: int = MAX_PARENTS) -> tuple[str, ...]:
58
+ """Names of the ancestors of ``pid`` (nearest first) from ``pid -> (parent pid, name)``; stops at a loop."""
59
+ names: list[str] = []
60
+ seen = {pid}
61
+ current = pid
62
+ while len(names) < limit and current in table:
63
+ parent = table[current][0]
64
+ if parent in seen or parent not in table:
65
+ break
66
+ names.append(table[parent][1])
67
+ seen.add(parent)
68
+ current = parent
69
+ return tuple(names)
70
+
71
+
72
+ def linux_parents(read_file: Callable[[str], str | None], pid: int, limit: int = MAX_PARENTS) -> tuple[str, ...]:
73
+ """Ancestor names of ``pid`` from ``/proc`` (``comm``, at most 15 characters), nearest first."""
74
+ names: list[str] = []
75
+ seen = {pid}
76
+ current = pid
77
+ while len(names) < limit:
78
+ stat = read_file(f"/proc/{current}/stat") or ""
79
+ fields = stat.rpartition(")")[2].split()
80
+ if len(fields) < 2 or not fields[1].isdigit():
81
+ break
82
+ parent = int(fields[1])
83
+ if parent <= 0 or parent in seen:
84
+ break
85
+ comm = (read_file(f"/proc/{parent}/comm") or "").strip()
86
+ if not comm:
87
+ break
88
+ names.append(comm)
89
+ seen.add(parent)
90
+ current = parent
91
+ return tuple(names)
92
+
93
+
94
+ def windows_parents(limit: int = MAX_PARENTS) -> tuple[str, ...]:
95
+ """Ancestor executable names of this process (nearest first) from a Toolhelp process snapshot; ``()`` on any
96
+ failure. A fresh ``WinDLL`` object is used, so no shared ``ctypes.windll`` function is changed. Windows reuses
97
+ the PID of an exited parent, so the walk may name an unrelated process: a hint, nothing more."""
98
+ try:
99
+ import ctypes
100
+ from ctypes import wintypes
101
+
102
+ class Entry(ctypes.Structure):
103
+ _fields_ = (("dwSize", wintypes.DWORD), ("cntUsage", wintypes.DWORD),
104
+ ("th32ProcessID", wintypes.DWORD), ("th32DefaultHeapID", ctypes.c_size_t),
105
+ ("th32ModuleID", wintypes.DWORD), ("cntThreads", wintypes.DWORD),
106
+ ("th32ParentProcessID", wintypes.DWORD), ("pcPriClassBase", wintypes.LONG),
107
+ ("dwFlags", wintypes.DWORD), ("szExeFile", ctypes.c_wchar * 260))
108
+
109
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) # type: ignore[attr-defined, unused-ignore]
110
+ snapshot, first, following, close = (kernel32.CreateToolhelp32Snapshot, kernel32.Process32FirstW,
111
+ kernel32.Process32NextW, kernel32.CloseHandle)
112
+ snapshot.restype, snapshot.argtypes = wintypes.HANDLE, (wintypes.DWORD, wintypes.DWORD)
113
+ for function in (first, following):
114
+ function.restype, function.argtypes = wintypes.BOOL, (wintypes.HANDLE, ctypes.POINTER(Entry))
115
+ close.restype, close.argtypes = wintypes.BOOL, (wintypes.HANDLE,)
116
+ handle = snapshot(0x2, 0) # TH32CS_SNAPPROCESS
117
+ if not handle or handle == wintypes.HANDLE(-1).value:
118
+ return ()
119
+ table: dict[int, tuple[int, str]] = {}
120
+ try:
121
+ entry = Entry()
122
+ entry.dwSize = ctypes.sizeof(Entry)
123
+ ok = first(handle, ctypes.byref(entry))
124
+ while ok:
125
+ table[int(entry.th32ProcessID)] = (int(entry.th32ParentProcessID), str(entry.szExeFile))
126
+ ok = following(handle, ctypes.byref(entry))
127
+ finally:
128
+ close(handle)
129
+ return walk_parents(table, os.getpid(), limit)
130
+ except Exception: # best-effort hint: never raise
131
+ return ()
132
+
133
+
134
+ def real_parents(platform: str) -> tuple[str, ...]:
135
+ """Ancestor process names of this process on ``platform`` (``sys.platform``), ``()`` when unknown."""
136
+ try:
137
+ if platform == "win32":
138
+ return windows_parents()
139
+ if platform.startswith("linux"):
140
+ return linux_parents(read_text, os.getpid())
141
+ except Exception: # best-effort hint: never raise
142
+ pass
143
+ return ()
144
+
145
+
146
+ def real_uname(platform: str, env: Mapping[str, str]) -> tuple[str, str, str]:
147
+ """``(system, release, machine)`` without the ``platform`` module (on Windows it may start ``cmd /c ver`` or
148
+ a slow WMI query): ``sys.getwindowsversion`` on Windows, ``os.uname`` elsewhere."""
149
+ try:
150
+ if platform == "win32":
151
+ version = sys.getwindowsversion() # type: ignore[attr-defined, unused-ignore]
152
+ major, build = int(version.major), int(version.build)
153
+ release = "11" if major == 10 and build >= 22000 else str(major)
154
+ machine = env.get("PROCESSOR_ARCHITEW6432") or env.get("PROCESSOR_ARCHITECTURE") or "unknown"
155
+ return "Windows", f"{release} (build {build})", machine
156
+ name = os.uname() # type: ignore[attr-defined, unused-ignore]
157
+ return str(name.sysname), str(name.release), str(name.machine)
158
+ except Exception: # best-effort hint: never raise
159
+ return "unknown", "unknown", "unknown"
160
+
161
+
162
+ def _no_parents() -> tuple[str, ...]:
163
+ return ()
164
+
165
+
166
+ def _no_uname() -> tuple[str, str, str]:
167
+ return "unknown", "unknown", "unknown"
168
+
169
+
170
+ def _no_file(path: str) -> str | None:
171
+ return None
172
+
173
+
174
+ @dataclass(frozen=True)
175
+ class Probe:
176
+ """Everything detection reads; tests pass their own. ``env``: the environment; ``platform``: ``sys.platform``;
177
+ ``read_file(path)``: text or ``None``; ``parents()``: ancestor process names, nearest first; ``uname()``:
178
+ ``(system, release, machine)``; ``streams``: ``(stdin, stdout)`` for ``isatty``. The defaults read nothing."""
179
+ env: Mapping[str, str] = field(default_factory=dict)
180
+ platform: str = "linux"
181
+ read_file: Callable[[str], str | None] = _no_file
182
+ parents: Callable[[], tuple[str, ...]] = _no_parents
183
+ uname: Callable[[], tuple[str, str, str]] = _no_uname
184
+ streams: tuple[object, ...] = ()
185
+
186
+ @classmethod
187
+ def real(cls) -> Probe:
188
+ """The probe of this process: ``os.environ``, the real files, parents, OS and ``sys.stdin``/``stdout``."""
189
+ env, platform = os.environ, sys.platform
190
+ return cls(env=env, platform=platform, read_file=read_text, parents=lambda: real_parents(platform),
191
+ uname=lambda: real_uname(platform, env), streams=(sys.stdin, sys.stdout))
@@ -0,0 +1,151 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2026 Peter Kokosharov <peter.kokosharov@gmail.com>
3
+ # AI models: claude-opus-5-5
4
+ # Licensed under MIT License
5
+ """``detect_container``: code arguments > a container config file > ``REX_CONTAINER`` > detection, per field.
6
+
7
+ The config file (TOML) and ``REX_CONTAINER`` (``key=value;key=value``) are strict: unknown keys, bad values,
8
+ duplicates and empty entries refuse the WHOLE source; ``detect_container`` then ignores it and records an
9
+ ``Evidence("refused", reason, source)`` instead of raising. Arguments in code are checked and raise
10
+ ``ContainerError`` (a programming error). HINTS only: never use the result for a security decision.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import tomllib
17
+ from collections.abc import Callable, Mapping
18
+ from typing import Any, TypeVar
19
+
20
+ from . import detect
21
+ from .model import (DETECTED, SOURCE_CODE, SOURCE_CONFIG, SOURCE_ENV, UNKNOWN, Container,
22
+ ContainerError, Evidence, OsInfo, check_value, shown)
23
+ from .probe import MAX_FILE_BYTES, Probe, read_regular
24
+
25
+ ENV_VAR = "REX_CONTAINER"
26
+ MAX_ENV_CHARS = 1024
27
+ T = TypeVar("T")
28
+
29
+
30
+ def parse_env(text: str) -> dict[str, Any]:
31
+ """Parse ``REX_CONTAINER`` (``channel=gui;host_app=vscode;interactive=false``). Strict: every entry is
32
+ ``key=value`` with a key of ``DECLARABLE`` and an allowed value, no duplicates; raises ``ContainerError``."""
33
+ if len(text) > MAX_ENV_CHARS:
34
+ raise ContainerError(f"{ENV_VAR} is longer than {MAX_ENV_CHARS} characters")
35
+ found: dict[str, Any] = {}
36
+ for number, entry in enumerate(text.split(";"), start=1):
37
+ key, sep, raw = (part.strip() for part in entry.partition("="))
38
+ if not sep or not key:
39
+ raise ContainerError(f"{ENV_VAR} entry {number} is not key=value")
40
+ value: Any = raw
41
+ if key == "interactive":
42
+ value = {"true": True, "false": False}.get(raw, raw)
43
+ check_value(key, value, f"{ENV_VAR} entry {number}") # first: only a known key may be named below
44
+ if key in found:
45
+ raise ContainerError(f"{ENV_VAR} names {shown(key)} twice")
46
+ found[key] = value
47
+ return found
48
+
49
+
50
+ def load_config(path: str | os.PathLike[str]) -> dict[str, Any]:
51
+ """Read a container config file (TOML: top-level ``channel``, ``host_app``, ``mode`` strings and an
52
+ ``interactive`` boolean). Strict; raises ``ContainerError`` and nothing else (deep nesting that makes the TOML
53
+ parser recurse too far, a FIFO, anything) for a missing, large, broken or wrong file."""
54
+ try:
55
+ return _load_config(path)
56
+ except ContainerError:
57
+ raise
58
+ except Exception as exc: # RecursionError, MemoryError, ...: still a refused file, never a crash
59
+ raise ContainerError(f"the container config cannot be read ({type(exc).__name__})") from None
60
+
61
+
62
+ def _load_config(path: str | os.PathLike[str]) -> dict[str, Any]:
63
+ data = read_regular(path, MAX_FILE_BYTES + 1)
64
+ if data is None:
65
+ raise ContainerError("cannot read the container config (missing, unreadable or not a regular file)")
66
+ if len(data) > MAX_FILE_BYTES:
67
+ raise ContainerError(f"the container config is larger than {MAX_FILE_BYTES} bytes")
68
+ try:
69
+ table = tomllib.loads(data.decode("utf-8"))
70
+ except (UnicodeDecodeError, tomllib.TOMLDecodeError) as exc:
71
+ raise ContainerError(f"the container config is not valid TOML: {exc}") from None
72
+ for number, (key, value) in enumerate(table.items(), start=1):
73
+ check_value(key, value, f"config key {number}")
74
+ return dict(table)
75
+
76
+
77
+ def _layers(declared: dict[str, Any], config: str | os.PathLike[str] | None,
78
+ probe: Probe) -> tuple[list[tuple[str, Mapping[str, Any]]], list[Evidence]]:
79
+ """``[(source, values)]`` from highest to lowest precedence, and the refused sources."""
80
+ layers: list[tuple[str, Mapping[str, Any]]] = [(SOURCE_CODE, declared)]
81
+ refused: list[Evidence] = []
82
+ if config is not None and os.path.isfile(config):
83
+ try:
84
+ layers.append((SOURCE_CONFIG, load_config(config)))
85
+ except ContainerError as exc:
86
+ refused.append(Evidence("refused", str(exc), SOURCE_CONFIG))
87
+ except Exception as exc: # the boundary: a source never takes detection down
88
+ refused.append(Evidence("refused", f"failed ({type(exc).__name__})", SOURCE_CONFIG))
89
+ text = _safe(lambda: str(probe.env.get(ENV_VAR) or ""), lambda _: "")
90
+ if text.strip():
91
+ try:
92
+ layers.append((SOURCE_ENV, parse_env(text)))
93
+ except ContainerError as exc:
94
+ refused.append(Evidence("refused", str(exc), SOURCE_ENV))
95
+ except Exception as exc: # the boundary: a source never takes detection down
96
+ refused.append(Evidence("refused", f"failed ({type(exc).__name__})", SOURCE_ENV))
97
+ return layers, refused
98
+
99
+
100
+ def _safe(rule: Callable[[], T], fallback: Callable[[str], T]) -> T:
101
+ """Run a detection rule; on any error ``fallback(source)`` with the error type in the source."""
102
+ try:
103
+ return rule()
104
+ except Exception as exc: # detection never raises
105
+ return fallback(f"{DETECTED}failed ({type(exc).__name__})")
106
+
107
+
108
+ def _pick(field: str, layers: list[tuple[str, Mapping[str, Any]]], detected: Callable[[], tuple[Any, str]],
109
+ evidence: list[Evidence]) -> Any:
110
+ """The value of ``field`` from the first layer that has it, else from ``detected()``; records the source."""
111
+ for source, values in layers:
112
+ if field in values:
113
+ value = values[field]
114
+ evidence.append(Evidence(field, _text(value), source))
115
+ return value
116
+ value, source = detected()
117
+ evidence.append(Evidence(field, _text(value), source))
118
+ return value
119
+
120
+
121
+ def _text(value: object) -> str:
122
+ return ("true" if value else "false") if isinstance(value, bool) else str(value)
123
+
124
+
125
+ def detect_container(*, channel: str | None = None, mode: str | None = None, host_app: str | None = None,
126
+ interactive: bool | None = None, config: str | os.PathLike[str] | None = None,
127
+ probe: Probe | None = None) -> Container:
128
+ """Where this runtime lives. Arguments given here win, then the TOML file ``config`` (the app passes the path
129
+ of its ``container.toml``; a missing file is skipped), then ``REX_CONTAINER``, then detection. ``embedded`` is
130
+ never detected: the host app declares it. Never raises for what it reads (a broken source is refused and
131
+ recorded); bad arguments raise ``ContainerError``. HINTS only: never use them for a security decision."""
132
+ declared = {k: v for k, v in (("channel", channel), ("mode", mode), ("host_app", host_app),
133
+ ("interactive", interactive)) if v is not None}
134
+ for key, value in declared.items():
135
+ check_value(key, value)
136
+ probe = probe if probe is not None else _safe(Probe.real, lambda _: Probe())
137
+ layers, refused = _layers(declared, config, probe)
138
+ info, evidence = _safe(lambda: detect.os_info(probe),
139
+ lambda source: (OsInfo(), [Evidence("os.system", UNKNOWN, source)]))
140
+ tty = _pick("interactive", layers, lambda: _safe(lambda: detect.interactive(probe),
141
+ lambda source: (False, source)), evidence)
142
+ found_app = _pick("host_app", layers, lambda: _safe(lambda: detect.host_app(probe, tty),
143
+ lambda source: (UNKNOWN, source)), evidence)
144
+ seen_mode, mode_source, hint_list = _safe(lambda: detect.mode(probe), lambda source: ("native", source, []))
145
+ found_mode = _pick("mode", layers, lambda: (seen_mode, mode_source), evidence)
146
+ found_channel = _pick("channel", layers, lambda: ("cli", DETECTED + "default (no channel declared)"), evidence)
147
+ hints = tuple(sorted({hint for hint, _ in hint_list}))
148
+ evidence += [Evidence("hint", hint, source) for hint, source in hint_list]
149
+ return Container(os=info, host_app=found_app, mode=found_mode, hints=hints, channel=found_channel,
150
+ interactive=tty, evidence=tuple(evidence + refused))
151
+
@@ -0,0 +1,56 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2026 Peter Kokosharov <peter.kokosharov@gmail.com>
3
+ # AI models: claude-opus-5-5
4
+ # Licensed under MIT License
5
+ """The model gateway tier (rexlib design 2.1): model classes with free names, fallback, costs, audit.
6
+
7
+ Steps G1 (configuration, presets), G2 (router, fallback, cooldown, daily caps, cost records), G3 (price
8
+ table, cost meter, audit events and sinks) and ST2 (streaming).
9
+
10
+ config = GatewayConfig.from_toml("gateway.toml") # or GatewayConfig.from_dict({...})
11
+ config.classes["large"].models # ("sonnet", "gpt"): primary first
12
+ gateway = Gateway(config, GatewayOptions(storage=open_storage("sqlite:///~/.rex/rex.db")))
13
+ gateway.complete("large", ChatRequest([ChatMessage.user("hi")])) # first healthy model, fallback
14
+ rexlib.run(gateway.provider("large"), messages) # a Provider bound to a target
15
+
16
+ - ``GatewayConfig``: ``models`` (``ModelConfig``), ``classes`` (``ClassConfig``), ``timezone``, ``cooldown``,
17
+ ``connect_timeout``, ``read_timeout``; strict keys, ``from_dict`` / ``from_toml``, ``targets()``.
18
+ - ``PRESETS`` (read-only ``name -> Preset``): ``anthropic``, ``openai``, ``openrouter``, ``gemini``, ``nvidia``,
19
+ ``ollama``, ``kiko``, ``cgw``; an app passes an extended table as ``presets=``.
20
+ - ``ConfigError`` (a ``ValueError``): the place of the problem, never a key.
21
+ - ``Gateway(config, options=None)``: ``complete(target, request)``, ``provider(target)``, ``targets()``,
22
+ ``healthy(model_id)``, ``spent_today(class_name)``, ``close()`` (a context manager); ``GatewayOptions``
23
+ (``storage``, ``clock``, ``monotonic``, ``env``, ``providers``, ``http_backend``, ``notice``);
24
+ ``CostCapExceeded`` (a ``ProviderError`` of kind ``cost_cap``); ``LedgerError`` (kind ``storage``, the paid
25
+ answer in ``completion``); ``cost_usd(price, usage)``, ``day_bounds(now, tz)``.
26
+
27
+ - ``ModelPrices`` (``from_config``, ``price(name)``, ``cost(usage, model)``, ``for_target(target) ->
28
+ TargetPrice``): one price per model id and one per class at its highest member price, for the loop's cost
29
+ limit (``RunOptions.prices``); ``Gateway.prices`` is the gateway's own table.
30
+ - ``CostMeter(storage, *, clock, timezone)``: ``charge``, ``record``, ``spent``, ``day``, ``check``;
31
+ ``Gateway.meter`` is the gateway's own meter.
32
+ - ``AuditEvent`` (one per attempt, kind ``gateway.call``, never prompts, answers or keys), ``AuditSink`` (any
33
+ callable taking an event), ``StorageAuditSink``, ``JsonlAuditSink``, ``LoggingAuditSink``;
34
+ ``GatewayOptions.audit`` and ``audit_extra``.
35
+
36
+ - Streaming (ST2): ``Gateway.stream(target, request)`` and ``Gateway.provider(target).stream``: fallback and
37
+ cooldown only before the first chunk with output, ``StreamInterrupted`` (a ``ProviderError`` with the
38
+ ``partial`` text) after it; cost and audit (``streamed: true``) at the end, also for broken and abandoned
39
+ streams.
40
+
41
+ This tier imports the core tier (and later ``kikolib``), never the agent tier.
42
+ """
43
+
44
+ from .audit import GATEWAY_CALL, AuditEvent, AuditSink, JsonlAuditSink, LoggingAuditSink, StorageAuditSink
45
+ from .config import (CACHE_READ_FACTOR, CACHE_WRITE_FACTOR, ClassConfig, ConfigError, GatewayConfig, ModelConfig,
46
+ Price, resolve_timezone)
47
+ from .costs import CostCapExceeded, CostMeter, LedgerError, cost_usd, day_bounds
48
+ from .presets import PRESETS, PROVIDERS, Preset
49
+ from .prices import ModelPrices, TargetPrice
50
+ from .router import Gateway, GatewayOptions
51
+ from .stream import StreamInterrupted
52
+
53
+ __all__ = ["CACHE_READ_FACTOR", "CACHE_WRITE_FACTOR", "GATEWAY_CALL", "PRESETS", "PROVIDERS", "AuditEvent",
54
+ "AuditSink", "ClassConfig", "ConfigError", "CostCapExceeded", "CostMeter", "Gateway", "GatewayConfig",
55
+ "GatewayOptions", "JsonlAuditSink", "LedgerError", "LoggingAuditSink", "ModelConfig", "ModelPrices",
56
+ "Preset", "Price", "StorageAuditSink", "StreamInterrupted", "TargetPrice", "cost_usd", "day_bounds", "resolve_timezone"]
@@ -0,0 +1,51 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2026 Peter Kokosharov <peter.kokosharov@gmail.com>
3
+ # AI models: claude-opus-5-5
4
+ # Licensed under MIT License
5
+ """One model tried for one gateway call, shared by ``complete`` (``router``) and ``stream`` (``stream``): the
6
+ attempt record, the request sent to the model, the error after every model failed, names in messages."""
7
+
8
+ from __future__ import annotations
9
+
10
+ import dataclasses
11
+ from dataclasses import dataclass
12
+
13
+ from rexlib.providers.base import ChatRequest
14
+ from rexlib.providers.errors import ProviderError
15
+
16
+ from .config import ModelConfig
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Attempt:
21
+ """One model tried for one call: what its audit event and its cost record need."""
22
+
23
+ target: str
24
+ scope: str
25
+ model: ModelConfig
26
+ request: ChatRequest
27
+ started: float
28
+
29
+
30
+ def prepare(model: ModelConfig, request: ChatRequest) -> ChatRequest:
31
+ """The request for ``model``: its upstream name, ``max_tokens`` clamped to ``max_output``."""
32
+ max_tokens = request.max_tokens
33
+ if model.max_output is not None:
34
+ max_tokens = model.max_output if max_tokens is None else min(max_tokens, model.max_output)
35
+ return dataclasses.replace(request, model=model.model, max_tokens=max_tokens)
36
+
37
+
38
+ def exhausted(target: str, failures: list[tuple[str, ProviderError]]) -> ProviderError:
39
+ """The error after every model failed: each model with its error kind; the last error's kind and status."""
40
+ last = failures[-1][1]
41
+ tried = ", ".join(f"{model_id} ({error.kind})" for model_id, error in failures)
42
+ error = ProviderError(f"every model of {show(target)} failed: {tried}; last: {last}", kind=last.kind,
43
+ status=last.status, retry_after=last.retry_after, detail=last.detail)
44
+ error.__cause__ = last
45
+ return error
46
+
47
+
48
+ def show(name: object) -> str:
49
+ """A caller's name for a message: ``repr``, cut to 40 characters."""
50
+ text = str(name)
51
+ return repr(text if len(text) <= 40 else text[:40] + "...")
@@ -0,0 +1,173 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2026 Peter Kokosharov <peter.kokosharov@gmail.com>
3
+ # AI models: claude-opus-5-5
4
+ # Licensed under MIT License
5
+ """Audit events of the gateway and where they go (rexlib design 2.1, "Audit").
6
+
7
+ gateway = Gateway(config, GatewayOptions(storage=store)) # events go to store.append_audit
8
+ gateway = Gateway(config, GatewayOptions(audit=JsonlAuditSink("gateway-audit.jsonl")))
9
+ store.query_audit(kind="gateway.call", limit=20) # newest 20, in append order
10
+
11
+ One ``AuditEvent`` (kind ``gateway.call``) per attempt: one per model tried, so a call that fell back from one model
12
+ to the next leaves two events. Fields: ``ts`` (wall POSIX seconds), ``target`` (what the caller asked for),
13
+ ``class_name`` (the class charged), ``model`` (model id), ``provider``, ``outcome`` (``ok``: the model answered,
14
+ ``error``: it failed, ``refused``: the daily cap was spent and nothing was sent, ``abandoned``: the consumer of a
15
+ stream closed it or was interrupted before its end; ``streamed`` attempts only), ``ms`` (duration on the monotonic
16
+ clock), ``status`` (HTTP status of a failure), ``error`` (the ``ProviderError`` kind; ``storage`` when the answer
17
+ arrived but its cost could not be recorded; ``cost_cap`` for a refusal), the four token counts, ``usd``,
18
+ ``streamed``, ``estimated`` (tokens estimated from characters), ``priced``, ``spent`` and ``cap`` (USD, only on a
19
+ refusal) and ``extra``. A refusal names no model or provider (None) and has no token counts or ``usd`` in
20
+ ``to_dict()``.
21
+
22
+ Privacy: an event never holds a prompt, an answer, a tool argument or a key, so the log can be shared for a cost
23
+ review. The only way in for anything else is ``extra``: fields the APP adds on purpose through
24
+ ``GatewayOptions.audit_extra(request) -> mapping`` (a session id, a user name; or message bodies, if the app
25
+ explicitly chooses to log them). ``extra`` is deep-copied and frozen, never overrides a standard field;
26
+ ``session`` and ``user`` in it are indexed by every ``Storage``.
27
+
28
+ Sinks (an ``AuditSink`` is any callable taking one ``AuditEvent``): ``StorageAuditSink`` (``append_audit``; the
29
+ gateway's default when ``GatewayOptions.storage`` is given), ``JsonlAuditSink`` (one JSON line per event, appended
30
+ to a file), ``LoggingAuditSink`` (one JSON line per event to a ``logging`` logger, ``rexlib.audit`` by default).
31
+ JSON lines escape U+2028, U+2029 and U+0085, so no reader splits an event in two.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import copy
37
+ import json
38
+ import logging
39
+ import os
40
+ import threading
41
+ from collections.abc import Mapping
42
+ from dataclasses import dataclass, field
43
+ from pathlib import Path
44
+ from types import MappingProxyType
45
+ from typing import Any, Protocol
46
+
47
+ from rexlib.storage import Storage
48
+
49
+ GATEWAY_CALL = "gateway.call"
50
+ OK = "ok"
51
+ ERROR = "error"
52
+ REFUSED = "refused"
53
+ ABANDONED = "abandoned"
54
+ _EMPTY: Mapping[str, Any] = MappingProxyType({})
55
+ _SPEND_FIELDS = ("input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens", "usd")
56
+ _LINE_BREAKS = (("
", "\\u2028"), ("
", "\\u2029"), ("\u0085", "\\u0085"))
57
+ _FILE_MODE = 0o600
58
+ _FILE_FLAGS = os.O_WRONLY | os.O_APPEND | os.O_CREAT | getattr(os, "O_BINARY", 0) | getattr(os, "O_CLOEXEC", 0)
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class AuditEvent:
63
+ """One attempt of a gateway call (see the module docstring); ``to_dict()`` is the plain record a sink writes."""
64
+
65
+ ts: float
66
+ target: str
67
+ class_name: str
68
+ model: str | None
69
+ provider: str | None
70
+ outcome: str
71
+ ms: float
72
+ status: int | None = None
73
+ error: str | None = None
74
+ input_tokens: int = 0
75
+ output_tokens: int = 0
76
+ cache_read_tokens: int = 0
77
+ cache_write_tokens: int = 0
78
+ usd: float = 0.0
79
+ streamed: bool = False
80
+ estimated: bool = False
81
+ priced: bool = True
82
+ spent: float | None = None
83
+ cap: float | None = None
84
+ extra: Mapping[str, Any] = field(default=_EMPTY)
85
+ kind: str = GATEWAY_CALL
86
+
87
+ def __post_init__(self) -> None:
88
+ """``extra`` is deep-copied and frozen: the app cannot change an event after it was made."""
89
+ object.__setattr__(self, "extra", MappingProxyType(copy.deepcopy(dict(self.extra))))
90
+
91
+ def to_dict(self) -> dict[str, Any]:
92
+ """The event as one flat dict: ``extra``'s fields first, every standard field over them; ``spent`` and
93
+ ``cap`` only when set, no token counts or ``usd`` on a refusal."""
94
+ record: dict[str, Any] = copy.deepcopy(dict(self.extra))
95
+ for name in self.__dataclass_fields__:
96
+ value = getattr(self, name)
97
+ if name == "extra" or (name in ("spent", "cap") and value is None):
98
+ record.pop(name, None)
99
+ elif self.outcome == REFUSED and name in _SPEND_FIELDS:
100
+ record.pop(name, None)
101
+ else:
102
+ record[name] = value
103
+ return record
104
+
105
+
106
+ class AuditSink(Protocol):
107
+ """Where audit events go: any callable taking one ``AuditEvent``."""
108
+
109
+ def __call__(self, event: AuditEvent, /) -> None: ...
110
+
111
+
112
+ class StorageAuditSink:
113
+ """Each event to ``storage.append_audit`` (indexed by ``kind``, ``ts``, ``session``, ``user``)."""
114
+
115
+ def __init__(self, storage: Storage) -> None:
116
+ self.storage = storage
117
+
118
+ def __repr__(self) -> str:
119
+ return f"StorageAuditSink({type(self.storage).__name__})"
120
+
121
+ def __call__(self, event: AuditEvent, /) -> None:
122
+ self.storage.append_audit(event.to_dict())
123
+
124
+
125
+ class JsonlAuditSink:
126
+ """Each event as one JSON line appended to ``path`` (UTF-8). The path is resolved once, here; the file is
127
+ created with mode 0o600 (owner only, on POSIX) and opened in append mode per event, and each line goes out in
128
+ ONE ``os.write``. One writer process per file; rotation is the app's job (move the file away between events).
129
+ Safe to share between threads of one process; the folder must exist."""
130
+
131
+ def __init__(self, path: str | os.PathLike[str]) -> None:
132
+ self.path = str(Path(path).resolve())
133
+ self._lock = threading.Lock()
134
+
135
+ def __repr__(self) -> str:
136
+ return f"JsonlAuditSink({self.path!r})"
137
+
138
+ def __call__(self, event: AuditEvent, /) -> None:
139
+ data = (json_line(event) + "\n").encode("utf-8")
140
+ with self._lock:
141
+ fd = os.open(self.path, _FILE_FLAGS, _FILE_MODE)
142
+ try:
143
+ os.write(fd, data)
144
+ finally:
145
+ os.close(fd)
146
+
147
+
148
+ class LoggingAuditSink:
149
+ """Each event as one JSON line to a ``logging`` logger (a name or a ``Logger``; default ``rexlib.audit``) at
150
+ ``level``. rexlib configures no handler: the app decides where the log goes."""
151
+
152
+ def __init__(self, logger: logging.Logger | str = "rexlib.audit", level: int = logging.INFO) -> None:
153
+ self.logger = logging.getLogger(logger) if isinstance(logger, str) else logger
154
+ self.level = level
155
+
156
+ def __repr__(self) -> str:
157
+ return f"LoggingAuditSink({self.logger.name!r})"
158
+
159
+ def __call__(self, event: AuditEvent, /) -> None:
160
+ self.logger.log(self.level, "%s", json_line(event))
161
+
162
+
163
+ def json_line(event: AuditEvent) -> str:
164
+ """The event as one line of canonical JSON (sorted keys; U+2028, U+2029 and U+0085 escaped; ``ValueError`` for
165
+ data that is not plain JSON)."""
166
+ line = json.dumps(event.to_dict(), sort_keys=True, ensure_ascii=False, allow_nan=False, default=_refuse)
167
+ for raw, escaped in _LINE_BREAKS:
168
+ line = line.replace(raw, escaped)
169
+ return line
170
+
171
+
172
+ def _refuse(value: object) -> object:
173
+ raise ValueError(f"audit event field of type {type(value).__name__} is not plain JSON data")