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
rexlib/cli/repl.py ADDED
@@ -0,0 +1,97 @@
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
+ """Unstable (0.x): ``workflow``, the line-based prompt loop of ``rexlib.cli``."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import dataclasses
10
+ import sys
11
+ from collections.abc import Iterable
12
+
13
+ from ..container import Container
14
+ from ..gateway import Gateway, GatewayConfig, GatewayOptions
15
+ from ..tools.base import Tool
16
+ from ..tools.registry import ToolRegistry
17
+ from .commands import HINT, dispatch
18
+ from .console import Console
19
+ from .options import CliOptions
20
+ from .permissions import Permissions
21
+ from .session import Session, turn
22
+
23
+ ARMED = "(Ctrl-C again to quit)"
24
+
25
+
26
+ def workflow(config: GatewayConfig, container: Container, *, tools: ToolRegistry | Iterable[Tool] = (),
27
+ options: CliOptions | None = None) -> int:
28
+ """Run the prompt until ``/quit``, EOF or a second Ctrl-C; returns the exit code (0).
29
+
30
+ ``config`` builds the session's ``Gateway`` (closed at the end); ``container.interactive`` decides colours, the
31
+ echo of lines read and whether permission questions can be asked at all. See the package docstring."""
32
+ opts = options or CliOptions()
33
+ console = Console(opts.output if opts.output is not None else sys.stdout, opts.input_fn,
34
+ colour=container.interactive, echo=not container.interactive)
35
+ table = _tool_table(tools)
36
+ with Gateway(config, _gateway_options(opts, console)) as gateway:
37
+ target = opts.target or next(iter(config.classes), None) or gateway.targets()[0]
38
+ if target not in gateway.targets():
39
+ raise ValueError(f"unknown target {target!r}; known: {', '.join(gateway.targets())}")
40
+ permissions = Permissions(opts.policy, table, console, outward=opts.outward,
41
+ interactive=container.interactive)
42
+ session = Session(gateway, table, console, permissions, opts, target)
43
+ session.messages = session.fresh_messages()
44
+ session.spent_at_start = sum(session.spent_today().values())
45
+ console.note(HINT)
46
+ return _loop(session)
47
+
48
+
49
+ def _loop(session: Session) -> int:
50
+ console, armed = session.console, False
51
+ while True:
52
+ try:
53
+ line = console.read(session.options.prompt).strip()
54
+ except EOFError:
55
+ console.write("\n")
56
+ return 0
57
+ except KeyboardInterrupt:
58
+ console.write("\n")
59
+ if armed:
60
+ return 0
61
+ armed = True
62
+ console.note(ARMED)
63
+ continue
64
+ armed = False
65
+ if not line:
66
+ continue
67
+ try:
68
+ if line.startswith("/"):
69
+ if dispatch(session, line):
70
+ return 0
71
+ elif not turn(session, line):
72
+ armed = True # the answer was cancelled: one more Ctrl-C at the prompt quits
73
+ except KeyboardInterrupt: # in a slash command
74
+ console.end_line()
75
+ armed = True
76
+ except Exception as exc: # a bug in a tool, a policy or a command must not end the session
77
+ console.error(f"Error: {type(exc).__name__}")
78
+
79
+
80
+ def _gateway_options(opts: CliOptions, console: Console) -> GatewayOptions:
81
+ """The app's gateway options with the storage put in, and gateway notices printed as notes."""
82
+ base = opts.gateway_options or GatewayOptions()
83
+ storage = opts.storage if opts.storage is not None else base.storage
84
+ notice = base.notice if base.notice is not None else (lambda text: console.note(f"note: {text}"))
85
+ return dataclasses.replace(base, storage=storage, notice=notice)
86
+
87
+
88
+ def _tool_table(tools: ToolRegistry | Iterable[Tool]) -> dict[str, Tool]:
89
+ if isinstance(tools, ToolRegistry):
90
+ found = (tools.get(name) for name in tools.list_tools())
91
+ return {tool.name: tool for tool in found if tool is not None}
92
+ table: dict[str, Tool] = {}
93
+ for tool in tools:
94
+ if tool.name in table:
95
+ raise ValueError(f"two tools named {tool.name!r}")
96
+ table[tool.name] = tool
97
+ return table
rexlib/cli/session.py ADDED
@@ -0,0 +1,99 @@
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
+ """Unstable (0.x): one ``rexlib.cli`` session: its state and one turn (a question, a streamed answer, tools)."""
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Callable
10
+ from dataclasses import dataclass, field
11
+ from typing import Any
12
+
13
+ from ..gateway import Gateway
14
+ from ..loop import LoopHooks, RunOptions, RunResult, RunStatus, parse_arguments, run
15
+ from ..messages import ToolCall
16
+ from ..tools.base import Tool, ToolResult
17
+ from .console import CYAN, Console
18
+ from .options import CliOptions
19
+ from .permissions import Permissions
20
+
21
+ CANCELLED = "cancelled (Ctrl-C again at the prompt to quit)"
22
+
23
+
24
+ @dataclass
25
+ class Session:
26
+ """What one ``workflow`` run keeps: the gateway, the tools, the target, the conversation and the spend at start."""
27
+
28
+ gateway: Gateway
29
+ tools: dict[str, Tool]
30
+ console: Console
31
+ permissions: Permissions
32
+ options: CliOptions
33
+ target: str
34
+ messages: list[dict[str, Any]] = field(default_factory=list)
35
+ spent_at_start: float = 0.0
36
+
37
+ def fresh_messages(self) -> list[dict[str, Any]]:
38
+ """The conversation of a new session: only the system prompt, when there is one."""
39
+ return [{"role": "system", "content": self.options.system}] if self.options.system else []
40
+
41
+ def spent_today(self) -> dict[str, float]:
42
+ """Today's spend per class (the gateway's ledger)."""
43
+ return {name: self.gateway.spent_today(name) for name in self.gateway.config.classes}
44
+
45
+
46
+ def turn(session: Session, text: str) -> bool:
47
+ """Send ``text`` and stream the answer; False when Ctrl-C cancelled it. A cancelled or failed turn is
48
+ dropped from the conversation; a finished one (also one stopped by a limit) is kept. Note: tools that ran
49
+ before a cancel or a failure keep their effects (a file written stays written), but the conversation no longer
50
+ records them, so the model does not know about them in the next turn."""
51
+ asked = [*session.messages, {"role": "user", "content": text}]
52
+ console = session.console
53
+ try:
54
+ result = run(session.gateway.provider(session.target), asked, list(session.tools.values()),
55
+ _hooks(session), options=_run_options(session))
56
+ except KeyboardInterrupt:
57
+ console.end_line()
58
+ console.note(CANCELLED)
59
+ return False
60
+ if not session.options.stream: # every new assistant text, also the words before a tool call
61
+ for message in result.messages[len(asked):]:
62
+ if message.get("role") == "assistant" and isinstance(message.get("content"), str):
63
+ console.write(message["content"])
64
+ console.end_line()
65
+ console.end_line()
66
+ _report(session, result)
67
+ return True
68
+
69
+
70
+ def _run_options(session: Session) -> RunOptions:
71
+ return RunOptions(limits=session.options.limits, tool_policy=session.permissions.tool_policy(),
72
+ stream=session.options.stream)
73
+
74
+
75
+ def _hooks(session: Session) -> LoopHooks:
76
+ console = session.console
77
+ on_token: Callable[[str], None] | None = console.write if session.options.stream else None
78
+ return LoopHooks(on_token=on_token, around_tool=lambda call, proceed: _around_tool(session, call, proceed))
79
+
80
+
81
+ def _around_tool(session: Session, call: ToolCall, proceed: Callable[..., ToolResult]) -> ToolResult:
82
+ """One summary line per tool call that runs (never its result: it may hold anything)."""
83
+ args, _ = parse_arguments(call.function.get("arguments"))
84
+ session.console.line(f"· {session.permissions.summary(call, args)}", CYAN)
85
+ result = proceed()
86
+ if not result.success:
87
+ session.console.note(f" failed: {str(result.error or '')[:200]}")
88
+ return result
89
+
90
+
91
+ def _report(session: Session, result: RunResult) -> None:
92
+ """Keep a finished turn, report a failed or limited one."""
93
+ console = session.console
94
+ if result.status == RunStatus.ERROR:
95
+ console.error(f"Error: {result.error if result.error is not None else result.reason}")
96
+ return # dropped from the conversation: a retry starts from the same place
97
+ session.messages = list(result.messages)
98
+ if result.status != RunStatus.COMPLETE:
99
+ console.note(f"[{result.status.value}] {result.reason}".rstrip())
@@ -0,0 +1,33 @@
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
+ """Where does this runtime live? One frozen ``Container`` answers it, like an old CGI User-Agent (Lynx or
6
+ Netscape): the app picks its renderer from it, the logic stays one.
7
+
8
+ from rexlib.container import detect_container
9
+
10
+ here = detect_container() # or detect_container(channel="gui", config=app_dir / "container.toml")
11
+ here.host_app, here.mode, here.channel # "intellij", "native", "cli"
12
+ here.source_of("host_app") # "detected: TERMINAL_EMULATOR=JetBrains-JediTerm"
13
+
14
+ - Fields: ``os`` (``OsInfo``: system, release, distro, machine), ``host_app`` (``HOST_APPS``), ``mode`` (native,
15
+ docker, sandbox, embedded) with ``hints`` (wsl, ci, codespaces, flatpak, podman), ``channel`` (tui, gui, web, cli,
16
+ embedded), ``interactive`` and ``evidence`` (``(field, value, source)`` for every value).
17
+ - Precedence per field: arguments in code > a TOML config file the app names > ``REX_CONTAINER``
18
+ (``key=value;key=value``) > detection. Config and environment are strict; a broken one is refused as a whole and
19
+ recorded as ``Evidence("refused", reason, source)``.
20
+ - ``embedded`` (mode or channel) is declared by the host app, never guessed.
21
+ - Detection reads only environment variables, a few small files and parent process names (Linux ``/proc``, Windows
22
+ ``ctypes``); no network, no subprocess, never raises, an unknown value is ``"unknown"``. Inject a ``Probe`` to test.
23
+
24
+ These are HINTS ONLY. Never use them for a security decision: whoever starts the process controls every source.
25
+ """
26
+
27
+ from .model import (CHANNELS, DECLARABLE, HINTS, HOST_APPS, MODES, UNKNOWN, Container, ContainerError, Evidence,
28
+ OsInfo)
29
+ from .probe import Probe
30
+ from .resolve import ENV_VAR, detect_container, load_config, parse_env
31
+
32
+ __all__ = ["CHANNELS", "DECLARABLE", "ENV_VAR", "HINTS", "HOST_APPS", "MODES", "UNKNOWN", "Container",
33
+ "ContainerError", "Evidence", "OsInfo", "Probe", "detect_container", "load_config", "parse_env"]
@@ -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
+ """Detection rules of ``rexlib.container``: each returns a value and the ``"detected: ..."`` source that gave it.
6
+
7
+ Only a ``Probe`` is read (environment, a few files, parent process names, OS name, ``isatty``). A source never
8
+ repeats a raw environment value: it says "is set", or names a value only after it matched a fixed known one
9
+ (``TERM_PROGRAM=vscode``). These are HINTS: never use them for a security decision.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from types import MappingProxyType
15
+
16
+ from .model import DETECTED, UNKNOWN, Evidence, OsInfo
17
+ from .probe import Probe
18
+
19
+ JETBRAINS = "JetBrains-JediTerm"
20
+ TERM_PROGRAMS: MappingProxyType[str, str] = MappingProxyType({
21
+ "vscode": "vscode", "Apple_Terminal": "apple-terminal", "iTerm.app": "iterm", "tmux": "tmux"})
22
+ # lower-case executable name without ".exe" -> host_app (JetBrains IDEs all use the JediTerm terminal)
23
+ PARENT_APPS: MappingProxyType[str, str] = MappingProxyType({
24
+ **dict.fromkeys(("idea", "idea64", "pycharm", "pycharm64", "webstorm64", "goland64", "clion64", "rider64",
25
+ "phpstorm64", "rubymine64", "datagrip64"), "intellij"),
26
+ **dict.fromkeys(("code", "code - insiders", "codium", "code helper"), "vscode"),
27
+ # conhost.exe and OpenConsole.exe are never ancestors: the classic console host is a child of the console
28
+ # program and Windows Terminal's ConPTY host a sibling (the shell's parent is WindowsTerminal.exe); conhost is
29
+ # inferred in host_app() instead.
30
+ "windowsterminal": "windows-terminal", "sshd": "ssh", "tmux": "tmux", "tmux: server": "tmux", "screen": "screen",
31
+ "iterm2": "iterm"})
32
+ CGROUP_WORDS = ("docker", "containerd", "kubepods")
33
+ OS_RELEASE = ("/etc/os-release", "/usr/lib/os-release")
34
+
35
+
36
+ def _set(probe: Probe, name: str) -> bool:
37
+ return bool(probe.env.get(name))
38
+
39
+
40
+ def host_app(probe: Probe, interactive: bool) -> tuple[str, str]:
41
+ """``(host_app, source)``: multiplexers first (closest to the process), then the terminal or IDE, then ssh,
42
+ then the parent processes; a Windows console without ``WT_SESSION`` is ``conhost``."""
43
+ env = probe.env
44
+ if _set(probe, "TMUX"):
45
+ return "tmux", DETECTED + "TMUX is set"
46
+ if _set(probe, "STY"):
47
+ return "screen", DETECTED + "STY is set"
48
+ if env.get("TERMINAL_EMULATOR") == JETBRAINS:
49
+ return "intellij", DETECTED + f"TERMINAL_EMULATOR={JETBRAINS}"
50
+ program = env.get("TERM_PROGRAM", "")
51
+ if program in TERM_PROGRAMS:
52
+ return TERM_PROGRAMS[program], DETECTED + f"TERM_PROGRAM={program}"
53
+ if _set(probe, "WT_SESSION"):
54
+ return "windows-terminal", DETECTED + "WT_SESSION is set"
55
+ for name in ("SSH_CONNECTION", "SSH_TTY"):
56
+ if _set(probe, name):
57
+ return "ssh", DETECTED + f"{name} is set"
58
+ for parent in probe.parents():
59
+ key = str(parent).lower().removesuffix(".exe")
60
+ if key in PARENT_APPS:
61
+ return PARENT_APPS[key], DETECTED + f"parent process {key}"
62
+ if probe.platform == "win32" and interactive and not program:
63
+ return "conhost", DETECTED + "Windows console without WT_SESSION or TERM_PROGRAM"
64
+ return UNKNOWN, DETECTED + "no host hint"
65
+
66
+
67
+ def _cgroup_word(probe: Probe) -> str:
68
+ text = probe.read_file("/proc/1/cgroup") or ""
69
+ return next((word for word in CGROUP_WORDS if word in text), "")
70
+
71
+
72
+ def mode(probe: Probe) -> tuple[str, str, list[tuple[str, str]]]:
73
+ """``(mode, source, [(hint, source)])`` for native, docker (any OCI container) and sandbox; extra hints for
74
+ wsl, ci, codespaces, flatpak and podman. ``embedded`` is never detected (only declared)."""
75
+ env, hints = probe.env, _hints(probe)
76
+ posix = probe.platform != "win32"
77
+ if probe.platform == "win32" and env.get("USERNAME", "").lower() == "wdagutilityaccount":
78
+ return "sandbox", DETECTED + "USERNAME=WDAGUtilityAccount (Windows Sandbox)", hints
79
+ if posix and probe.read_file("/.flatpak-info") is not None:
80
+ return "sandbox", DETECTED + "/.flatpak-info", hints + [("flatpak", DETECTED + "/.flatpak-info")]
81
+ if posix and probe.read_file("/run/.containerenv") is not None:
82
+ return "docker", DETECTED + "/run/.containerenv", hints + [("podman", DETECTED + "/run/.containerenv")]
83
+ if env.get("container") == "podman":
84
+ return "docker", DETECTED + "container=podman", hints + [("podman", DETECTED + "container=podman")]
85
+ if posix and probe.read_file("/.dockerenv") is not None:
86
+ return "docker", DETECTED + "/.dockerenv", hints
87
+ word = _cgroup_word(probe) if posix else ""
88
+ if word:
89
+ return "docker", DETECTED + f"/proc/1/cgroup names {word}", hints
90
+ if env.get("container") == "docker":
91
+ return "docker", DETECTED + "container=docker", hints
92
+ return "native", DETECTED + "no container or sandbox sign", hints
93
+
94
+
95
+ def _hints(probe: Probe) -> list[tuple[str, str]]:
96
+ env, found = probe.env, []
97
+ if _set(probe, "WSL_DISTRO_NAME"):
98
+ found.append(("wsl", DETECTED + "WSL_DISTRO_NAME is set"))
99
+ if env.get("CI", "").lower() not in ("", "0", "false", "no"):
100
+ found.append(("ci", DETECTED + "CI is set"))
101
+ elif env.get("GITHUB_ACTIONS") == "true":
102
+ found.append(("ci", DETECTED + "GITHUB_ACTIONS=true"))
103
+ if env.get("CODESPACES") == "true":
104
+ found.append(("codespaces", DETECTED + "CODESPACES=true"))
105
+ return found
106
+
107
+
108
+ def interactive(probe: Probe) -> tuple[bool, str]:
109
+ """``(True, ...)`` when every stream of ``probe.streams`` (stdin, stdout) is a terminal."""
110
+ if not probe.streams:
111
+ return False, DETECTED + "no standard streams"
112
+ for number, stream in enumerate(probe.streams):
113
+ name = ("stdin", "stdout")[number] if number < 2 else f"stream {number}"
114
+ try:
115
+ tty = bool(stream is not None and stream.isatty()) # type: ignore[attr-defined]
116
+ except (AttributeError, OSError, ValueError):
117
+ tty = False
118
+ if not tty:
119
+ return False, DETECTED + f"{name} is not a terminal"
120
+ return True, DETECTED + "stdin and stdout are terminals"
121
+
122
+
123
+ def os_info(probe: Probe) -> tuple[OsInfo, list[Evidence]]:
124
+ """``OsInfo`` and its evidence; ``distro`` from ``/etc/os-release`` (or ``/usr/lib/os-release``)."""
125
+ system, release, machine = (_short(str(v)) or UNKNOWN for v in probe.uname())
126
+ distro, source = UNKNOWN, DETECTED + "no os-release file"
127
+ for path in (OS_RELEASE if probe.platform != "win32" else ()):
128
+ text = probe.read_file(path)
129
+ if text is not None:
130
+ distro, source = _distro(text), DETECTED + path
131
+ break
132
+ info = OsInfo(system=system, release=release, distro=distro, machine=machine)
133
+ return info, [Evidence("os.system", system, DETECTED + "uname"), Evidence("os.release", release,
134
+ DETECTED + "uname"), Evidence("os.distro", distro, source),
135
+ Evidence("os.machine", machine, DETECTED + "uname")]
136
+
137
+
138
+ def _distro(text: str) -> str:
139
+ values: dict[str, str] = {}
140
+ for line in text.splitlines():
141
+ key, sep, value = line.strip().partition("=")
142
+ if sep and key.isidentifier():
143
+ values[key] = value.strip().strip("\"'")
144
+ name = values.get("PRETTY_NAME") or " ".join(v for v in (values.get("NAME"), values.get("VERSION_ID")) if v)
145
+ return _short(name) or UNKNOWN
146
+
147
+
148
+ def _short(text: str, limit: int = 80) -> str:
149
+ """Printable text cut to ``limit`` characters (file and environment values are not trusted)."""
150
+ clean = "".join(ch for ch in text if ch.isprintable()).strip()
151
+ return clean[:limit]
@@ -0,0 +1,111 @@
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 value types of ``rexlib.container``: ``Container``, ``OsInfo``, ``Evidence`` and the allowed values.
6
+
7
+ Every field is a HINT about where the runtime lives, for choosing a renderer or a default. Never use any of it
8
+ for a security decision: every source (code, file, environment, process names) can be set by whoever starts the
9
+ process.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import dataclass
15
+ from typing import Any, NamedTuple
16
+
17
+ HOST_APPS: tuple[str, ...] = ("intellij", "vscode", "windows-terminal", "conhost", "apple-terminal", "iterm", "ssh",
18
+ "tmux", "screen", "unknown")
19
+ MODES: tuple[str, ...] = ("native", "docker", "sandbox", "embedded") # "embedded" is only ever declared
20
+ CHANNELS: tuple[str, ...] = ("tui", "gui", "web", "cli", "embedded") # "embedded" is only ever declared
21
+ HINTS: tuple[str, ...] = ("ci", "codespaces", "flatpak", "podman", "wsl")
22
+ DECLARABLE: tuple[str, ...] = ("channel", "host_app", "interactive", "mode") # keys of code, config and env
23
+ UNKNOWN = "unknown"
24
+
25
+ SOURCE_CODE = "declared in code"
26
+ SOURCE_CONFIG = "config file"
27
+ SOURCE_ENV = "env REX_CONTAINER"
28
+ DETECTED = "detected: " # prefix of every detected source
29
+
30
+
31
+ class ContainerError(ValueError):
32
+ """A declared value or a config / ``REX_CONTAINER`` entry that is not allowed (the message names it)."""
33
+
34
+
35
+ class Evidence(NamedTuple):
36
+ """Why a field has its value: ``(field, value, source)``; ``source`` is ``"declared in code"``,
37
+ ``"config file"``, ``"env REX_CONTAINER"`` or ``"detected: <what>"``. Field ``"refused"`` records a config or
38
+ environment value that was ignored (its value is the reason)."""
39
+ field: str
40
+ value: str
41
+ source: str
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class OsInfo:
46
+ """The operating system: ``system`` (Windows, Linux, Darwin ...), ``release``, ``distro`` (from
47
+ ``/etc/os-release`` where present, else ``"unknown"``) and ``machine`` (AMD64, x86_64, arm64 ...)."""
48
+ system: str = UNKNOWN
49
+ release: str = UNKNOWN
50
+ distro: str = UNKNOWN
51
+ machine: str = UNKNOWN
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class Container:
56
+ """Where this runtime lives (like a browser's User-Agent): HINTS for picking a renderer, never for security.
57
+
58
+ ``host_app`` is the program around the process (one of ``HOST_APPS``), ``mode`` how it is packaged (``native``,
59
+ ``docker`` = any OCI container incl. Podman, ``sandbox``, ``embedded``), ``hints`` extra facts (``HINTS``:
60
+ wsl, ci, codespaces, flatpak, podman), ``channel`` how the app talks to its user (``CHANNELS``), ``interactive``
61
+ whether stdin and stdout are a terminal, ``evidence`` the source of every value."""
62
+ os: OsInfo
63
+ host_app: str
64
+ mode: str
65
+ hints: tuple[str, ...]
66
+ channel: str
67
+ interactive: bool
68
+ evidence: tuple[Evidence, ...]
69
+
70
+ def __post_init__(self) -> None:
71
+ check_value("host_app", self.host_app)
72
+ check_value("mode", self.mode)
73
+ check_value("channel", self.channel)
74
+ if not isinstance(self.interactive, bool):
75
+ raise ContainerError(f"interactive must be a bool, not {type(self.interactive).__name__}")
76
+ unknown = [h for h in self.hints if h not in HINTS]
77
+ if unknown:
78
+ raise ContainerError(f"unknown hint {unknown[0]!r}; allowed: {', '.join(HINTS)}")
79
+
80
+ def source_of(self, field: str) -> str:
81
+ """The source of ``field`` (``"os.system"``, ``"host_app"``, ...), ``""`` when none was recorded."""
82
+ return next((e.source for e in self.evidence if e.field == field), "")
83
+
84
+ def to_dict(self) -> dict[str, Any]:
85
+ """A JSON-ready dict (``evidence`` as a list of ``{field, value, source}``)."""
86
+ return {"os": {"system": self.os.system, "release": self.os.release, "distro": self.os.distro,
87
+ "machine": self.os.machine},
88
+ "host_app": self.host_app, "mode": self.mode, "hints": list(self.hints), "channel": self.channel,
89
+ "interactive": self.interactive, "evidence": [e._asdict() for e in self.evidence]}
90
+
91
+
92
+ def check_value(field: str, value: object, position: str = "") -> None:
93
+ """Raise ``ContainerError`` unless ``value`` is allowed for the declarable ``field``. Messages name a known key,
94
+ never a value and never an unknown key (either may be a secret pasted into the wrong place; messages end up in
95
+ ``evidence``): an unknown key is reported by ``position`` (``"REX_CONTAINER entry 2"``)."""
96
+ allowed = {"host_app": HOST_APPS, "mode": MODES, "channel": CHANNELS}.get(field)
97
+ if field == "interactive":
98
+ if not isinstance(value, bool):
99
+ raise ContainerError("interactive must be true or false")
100
+ return
101
+ if allowed is None:
102
+ where = f" at {position}" if position else ""
103
+ raise ContainerError(f"unknown key{where} (not shown); allowed: {', '.join(DECLARABLE)}")
104
+ if value not in allowed:
105
+ raise ContainerError(f"{field}: value not allowed; allowed: {', '.join(allowed)}")
106
+
107
+
108
+ def shown(value: object) -> str:
109
+ """``repr(value)`` cut to 40 characters, for error messages."""
110
+ text = repr(value)
111
+ return text if len(text) <= 40 else text[:37] + "..."