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.
- rexlib/__init__.py +75 -0
- rexlib/cli/__init__.py +44 -0
- rexlib/cli/commands.py +99 -0
- rexlib/cli/console.py +83 -0
- rexlib/cli/options.py +47 -0
- rexlib/cli/permissions.py +174 -0
- rexlib/cli/render.py +78 -0
- rexlib/cli/repl.py +97 -0
- rexlib/cli/session.py +99 -0
- rexlib/container/__init__.py +33 -0
- rexlib/container/detect.py +151 -0
- rexlib/container/model.py +111 -0
- rexlib/container/probe.py +191 -0
- rexlib/container/resolve.py +151 -0
- rexlib/gateway/__init__.py +56 -0
- rexlib/gateway/attempts.py +51 -0
- rexlib/gateway/audit.py +173 -0
- rexlib/gateway/config.py +383 -0
- rexlib/gateway/costs.py +157 -0
- rexlib/gateway/keys.py +46 -0
- rexlib/gateway/presets.py +59 -0
- rexlib/gateway/prices.py +134 -0
- rexlib/gateway/router.py +391 -0
- rexlib/gateway/stream.py +224 -0
- rexlib/loop/__init__.py +63 -0
- rexlib/loop/calls.py +220 -0
- rexlib/loop/core.py +249 -0
- rexlib/loop/options.py +149 -0
- rexlib/loop/stream.py +88 -0
- rexlib/messages.py +221 -0
- rexlib/providers/__init__.py +11 -0
- rexlib/providers/anthropic.py +108 -0
- rexlib/providers/base.py +53 -0
- rexlib/providers/errors.py +191 -0
- rexlib/providers/http.py +124 -0
- rexlib/providers/openai.py +148 -0
- rexlib/providers/transport.py +163 -0
- rexlib/py.typed +0 -0
- rexlib/storage/__init__.py +30 -0
- rexlib/storage/base.py +144 -0
- rexlib/storage/contract.py +262 -0
- rexlib/storage/registry.py +49 -0
- rexlib/storage/sqlite.py +219 -0
- rexlib/testing.py +160 -0
- rexlib/tools/__init__.py +12 -0
- rexlib/tools/base.py +116 -0
- rexlib/tools/executor.py +105 -0
- rexlib/tools/function_tool.py +168 -0
- rexlib/tools/registry.py +66 -0
- rexlib/wire/__init__.py +6 -0
- rexlib/wire/anthropic_messages.py +300 -0
- rexlib/wire/openai_chat.py +134 -0
- rexlib/wire/sse.py +85 -0
- rexlib_py-0.9.0a1.dist-info/METADATA +251 -0
- rexlib_py-0.9.0a1.dist-info/RECORD +58 -0
- rexlib_py-0.9.0a1.dist-info/WHEEL +5 -0
- rexlib_py-0.9.0a1.dist-info/licenses/LICENSE +21 -0
- rexlib_py-0.9.0a1.dist-info/top_level.txt +1 -0
rexlib/__init__.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
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
|
+
"""rexlib: stdlib-only building blocks for AI apps.
|
|
6
|
+
|
|
7
|
+
``import rexlib`` loads nothing else: public names are re-exported lazily through ``__getattr__`` from the
|
|
8
|
+
sub-module listed for them in ``_EXPORTS``; the ``TYPE_CHECKING`` block gives type checkers the same names.
|
|
9
|
+
``__all__`` is the stability promise of 1.0 (core and gateway tiers); the 0.x parts (agent tier, app kit,
|
|
10
|
+
bridges) are reachable only by module name and are never listed here.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import importlib
|
|
16
|
+
from types import MappingProxyType
|
|
17
|
+
|
|
18
|
+
TYPE_CHECKING = False # True for type checkers; not imported from typing, so `import rexlib` loads no other module
|
|
19
|
+
if TYPE_CHECKING: # static types for the lazy names below; never runs (tests/test_rexlib_typed_exports.py)
|
|
20
|
+
# "X as X" marks an explicit re-export for strict type checkers (no implicit re-export).
|
|
21
|
+
from rexlib.container import Container as Container, ContainerError as ContainerError
|
|
22
|
+
from rexlib.container import detect_container as detect_container
|
|
23
|
+
from rexlib.gateway import PRESETS as PRESETS, CostCapExceeded as CostCapExceeded, Gateway as Gateway
|
|
24
|
+
from rexlib.gateway import GatewayConfig as GatewayConfig, GatewayOptions as GatewayOptions, Price as Price
|
|
25
|
+
from rexlib.gateway import AuditEvent as AuditEvent, AuditSink as AuditSink, CostMeter as CostMeter
|
|
26
|
+
from rexlib.gateway import JsonlAuditSink as JsonlAuditSink, LoggingAuditSink as LoggingAuditSink
|
|
27
|
+
from rexlib.gateway import ModelPrices as ModelPrices, StorageAuditSink as StorageAuditSink
|
|
28
|
+
from rexlib.gateway import StreamInterrupted as StreamInterrupted
|
|
29
|
+
from rexlib.gateway import ConfigError as ConfigError, LedgerError as LedgerError, Preset as Preset
|
|
30
|
+
from rexlib.loop import Decision as Decision, Limits as Limits, LoopHooks as LoopHooks
|
|
31
|
+
from rexlib.loop import RunOptions as RunOptions, RunResult as RunResult, RunStatus as RunStatus, Stop as Stop
|
|
32
|
+
from rexlib.loop import ToolDecision as ToolDecision, ToolPolicy as ToolPolicy, run as run
|
|
33
|
+
from rexlib.messages import ChatCompletion as ChatCompletion, ChatCompletionChunk as ChatCompletionChunk
|
|
34
|
+
from rexlib.messages import ChatMessage as ChatMessage, ToolCall as ToolCall, Usage as Usage
|
|
35
|
+
from rexlib.providers import ChatRequest as ChatRequest, Provider as Provider, ProviderError as ProviderError
|
|
36
|
+
from rexlib.providers.anthropic import AnthropicMessages as AnthropicMessages
|
|
37
|
+
from rexlib.providers.openai import OpenAIChat as OpenAIChat
|
|
38
|
+
from rexlib.storage import SqliteStorage as SqliteStorage, Storage as Storage, open_storage as open_storage
|
|
39
|
+
from rexlib.storage import StorageError as StorageError
|
|
40
|
+
from rexlib.tools import Tool as Tool, ToolRegistry as ToolRegistry, ToolResult as ToolResult
|
|
41
|
+
from rexlib.tools import ToolSchema as ToolSchema, function_tool as function_tool
|
|
42
|
+
|
|
43
|
+
__version__ = "0.9.0a1"
|
|
44
|
+
|
|
45
|
+
# public name -> sub-module that defines it
|
|
46
|
+
_EXPORTS: MappingProxyType[str, str] = MappingProxyType({
|
|
47
|
+
**dict.fromkeys(("ChatCompletion", "ChatCompletionChunk", "ChatMessage", "ToolCall", "Usage"), "rexlib.messages"),
|
|
48
|
+
**dict.fromkeys(("Tool", "ToolRegistry", "ToolResult", "ToolSchema", "function_tool"), "rexlib.tools"),
|
|
49
|
+
**dict.fromkeys(("ChatRequest", "Provider", "ProviderError"), "rexlib.providers"),
|
|
50
|
+
"OpenAIChat": "rexlib.providers.openai",
|
|
51
|
+
"AnthropicMessages": "rexlib.providers.anthropic",
|
|
52
|
+
**dict.fromkeys(("Decision", "Limits", "LoopHooks", "RunOptions", "RunResult", "RunStatus", "Stop", "ToolDecision",
|
|
53
|
+
"ToolPolicy", "run"), "rexlib.loop"),
|
|
54
|
+
**dict.fromkeys(("SqliteStorage", "Storage", "StorageError", "open_storage"), "rexlib.storage"),
|
|
55
|
+
**dict.fromkeys(("Container", "ContainerError", "detect_container"), "rexlib.container"),
|
|
56
|
+
**dict.fromkeys(("AuditEvent", "AuditSink", "ConfigError", "CostCapExceeded", "CostMeter", "Gateway",
|
|
57
|
+
"GatewayConfig", "GatewayOptions", "JsonlAuditSink", "LedgerError", "LoggingAuditSink",
|
|
58
|
+
"ModelPrices", "PRESETS", "Preset", "Price", "StorageAuditSink", "StreamInterrupted"),
|
|
59
|
+
"rexlib.gateway"),
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
__all__ = sorted(_EXPORTS)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def __getattr__(name: str) -> object:
|
|
66
|
+
module = _EXPORTS.get(name)
|
|
67
|
+
if module is None:
|
|
68
|
+
raise AttributeError(f"module 'rexlib' has no attribute {name!r}")
|
|
69
|
+
value = getattr(importlib.import_module(module), name)
|
|
70
|
+
globals()[name] = value # resolve once
|
|
71
|
+
return value
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def __dir__() -> list[str]:
|
|
75
|
+
return sorted(set(globals()) | set(_EXPORTS))
|
rexlib/cli/__init__.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
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): ``rexlib.cli``, a line-based prompt for any app over a gateway (no curses, stdlib only).
|
|
6
|
+
|
|
7
|
+
from rexlib import GatewayConfig, cli, detect_container
|
|
8
|
+
config = GatewayConfig.from_toml("gateway.toml")
|
|
9
|
+
cli.workflow(config, detect_container(channel="cli"), tools=[...]) # prompt "rex › ", loop, tools
|
|
10
|
+
|
|
11
|
+
- ``workflow(config, container, *, tools=(), options=None) -> int``: builds a ``Gateway`` from ``config``, reads
|
|
12
|
+
lines until ``/quit``, EOF or a second Ctrl-C, and returns 0. A line is a slash command or a question; the
|
|
13
|
+
answer streams through ``gateway.provider(target)`` and ``rexlib.run(..., stream=True)`` (``on_token``), tool
|
|
14
|
+
calls print one summary line each, a failed turn prints one ``Error:`` line (a ``ProviderError`` text, which
|
|
15
|
+
never holds a key) and leaves the conversation as it was.
|
|
16
|
+
- ``CliOptions``: policy, outward tools, storage, gateway options, start target, system prompt, prompt text,
|
|
17
|
+
``input_fn``, ``output``, limits, streaming.
|
|
18
|
+
- Slash commands: ``/help``, ``/tools``, ``/cost`` (today per class from ``Gateway.spent_today``, and this
|
|
19
|
+
session), ``/model [NAME]`` = ``/class [NAME]``, ``/reset``, ``/quit`` = ``/exit`` = ``/q``.
|
|
20
|
+
- Permissions (``rexlib.cli.permissions``): the app's ``ToolPolicy.decide`` or a table ``tool -> auto | ask |
|
|
21
|
+
forbid``, every tool asks without one; outward tools always ask; "always" lasts for the session and covers
|
|
22
|
+
exactly the same arguments (never just the same summary); the question shows the whole command or text,
|
|
23
|
+
clipped; when the container is not interactive nothing is asked and an ask is denied.
|
|
24
|
+
- Ctrl-C: during an answer or at a permission question it cancels the answer; at the prompt the first press
|
|
25
|
+
arms, the second quits (also right after a cancelled answer); any line disarms. EOF quits. Any other exception
|
|
26
|
+
in a turn or a command is one ``Error: <Type>`` line and the session goes on.
|
|
27
|
+
- Outside text (tokens, tool summaries and details, server errors, notices) is printed without control
|
|
28
|
+
characters (``rexlib.cli.console.clean``): no escape sequence from a model or a server reaches the terminal.
|
|
29
|
+
- ``container.interactive``: colours on; off: no colours, each line read is echoed (a piped transcript reads
|
|
30
|
+
like a session) and permission questions are denied unasked.
|
|
31
|
+
|
|
32
|
+
App tier: imports the core and gateway tiers; nothing else in rexlib imports it. Tests drive it with ``input_fn``,
|
|
33
|
+
``output`` and ``GatewayOptions(providers={"id": FakeProvider([...])})``.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
from .commands import COMMANDS, HELP, HINT, dispatch
|
|
37
|
+
from .console import Console
|
|
38
|
+
from .options import DEFAULT_PROMPT, CliOptions
|
|
39
|
+
from .permissions import MODES, Permissions
|
|
40
|
+
from .repl import workflow
|
|
41
|
+
from .session import Session, turn
|
|
42
|
+
|
|
43
|
+
__all__ = ["COMMANDS", "DEFAULT_PROMPT", "HELP", "HINT", "MODES", "CliOptions", "Console", "Permissions", "Session",
|
|
44
|
+
"dispatch", "turn", "workflow"]
|
rexlib/cli/commands.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): the slash commands of ``rexlib.cli``: one table, each command a function of (session, argument).
|
|
6
|
+
|
|
7
|
+
A command returns True to end the session (``/quit``). Unknown commands print one line and change nothing.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from collections.abc import Callable, Mapping
|
|
13
|
+
from types import MappingProxyType
|
|
14
|
+
|
|
15
|
+
from .console import CYAN
|
|
16
|
+
from .session import Session
|
|
17
|
+
|
|
18
|
+
Command = Callable[[Session, str], bool]
|
|
19
|
+
HINT = "Commands: /help /tools /cost /model /reset /quit | Ctrl+C interrupts, Ctrl+D exits"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _help(session: Session, arg: str) -> bool:
|
|
23
|
+
for names, text in HELP:
|
|
24
|
+
session.console.line(f" {names:<22} {text}")
|
|
25
|
+
return False
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _tools(session: Session, arg: str) -> bool:
|
|
29
|
+
if not session.tools:
|
|
30
|
+
session.console.line("no tools: plain chat")
|
|
31
|
+
return False
|
|
32
|
+
width = max(len(name) for name in session.tools)
|
|
33
|
+
for name, tool in session.tools.items():
|
|
34
|
+
first = (tool.description or "").strip().splitlines()[0] if (tool.description or "").strip() else ""
|
|
35
|
+
session.console.line(f" {name:<{width}} [{session.permissions.mode(name)}] {first[:90]}")
|
|
36
|
+
return False
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _cost(session: Session, arg: str) -> bool:
|
|
40
|
+
spent = session.spent_today()
|
|
41
|
+
total = sum(spent.values())
|
|
42
|
+
for name, usd in spent.items():
|
|
43
|
+
session.console.line(f" {name:<16} ${usd:.4f} today")
|
|
44
|
+
session.console.line(f" {'total':<16} ${total:.4f} today, ${max(total - session.spent_at_start, 0.0):.4f} "
|
|
45
|
+
"this session")
|
|
46
|
+
return False
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _model(session: Session, arg: str) -> bool:
|
|
50
|
+
targets = session.gateway.targets()
|
|
51
|
+
wanted = arg.strip()
|
|
52
|
+
if not wanted:
|
|
53
|
+
classes = set(session.gateway.config.classes)
|
|
54
|
+
for name in targets:
|
|
55
|
+
mark = "*" if name == session.target else " "
|
|
56
|
+
kind = "class" if name in classes else "model"
|
|
57
|
+
session.console.line(f" {mark} {name:<20} {kind}")
|
|
58
|
+
return False
|
|
59
|
+
if wanted not in targets:
|
|
60
|
+
session.console.error(f"unknown target {wanted!r}; known: {', '.join(targets)}")
|
|
61
|
+
return False
|
|
62
|
+
session.target = wanted
|
|
63
|
+
session.console.line(f"target: {wanted}", CYAN)
|
|
64
|
+
return False
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _reset(session: Session, arg: str) -> bool:
|
|
68
|
+
session.messages = session.fresh_messages()
|
|
69
|
+
session.console.line("new conversation")
|
|
70
|
+
return False
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _quit(session: Session, arg: str) -> bool:
|
|
74
|
+
return True
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
HELP: tuple[tuple[str, str], ...] = (
|
|
78
|
+
("/help", "this list"),
|
|
79
|
+
("/tools", "the tools and whether each runs, asks or is forbidden"),
|
|
80
|
+
("/cost", "today's spend per class and this session's"),
|
|
81
|
+
("/model [NAME], /class", "show the targets, or switch to NAME"),
|
|
82
|
+
("/reset", "start a new conversation"),
|
|
83
|
+
("/quit, /exit, /q", "leave (also Ctrl+D, or Ctrl+C twice)"),
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
COMMANDS: Mapping[str, Command] = MappingProxyType({
|
|
87
|
+
"help": _help, "tools": _tools, "cost": _cost, "model": _model, "class": _model, "reset": _reset,
|
|
88
|
+
"quit": _quit, "exit": _quit, "q": _quit,
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def dispatch(session: Session, line: str, commands: Mapping[str, Command] = COMMANDS) -> bool:
|
|
93
|
+
"""Run one ``/command [argument]`` line; True ends the session."""
|
|
94
|
+
name, _, arg = line[1:].strip().partition(" ")
|
|
95
|
+
command = commands.get(name.lower())
|
|
96
|
+
if command is None:
|
|
97
|
+
session.console.error(f"unknown command /{name}; /help lists them")
|
|
98
|
+
return False
|
|
99
|
+
return command(session, arg)
|
rexlib/cli/console.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
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): the line console of ``rexlib.cli``: output with optional colours, input through a function.
|
|
6
|
+
|
|
7
|
+
Every text that reaches the terminal through ``write``, ``line``, ``note``, ``error`` or the echo passes ``clean``
|
|
8
|
+
first: model tokens, tool summaries and details, server error texts and notices come from outside, and a control
|
|
9
|
+
sequence in them could erase lines, move the cursor, retitle the window or write the clipboard (OSC 52). Only the
|
|
10
|
+
console's own colour codes are written raw.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
from collections.abc import Callable
|
|
17
|
+
from typing import TextIO
|
|
18
|
+
|
|
19
|
+
RESET = "\033[0m"
|
|
20
|
+
GRAY = "\033[90m"
|
|
21
|
+
RED = "\033[31m"
|
|
22
|
+
CYAN = "\033[36m"
|
|
23
|
+
YELLOW = "\033[33m"
|
|
24
|
+
|
|
25
|
+
# C0 controls except TAB and LF, DEL, ESC (in C0), C1 controls (U+0080-U+009F, e.g. the 8-bit CSI U+009B), and the
|
|
26
|
+
# bidi embedding, override and isolate controls (U+202A-U+202E, U+2066-U+2069) that reorder what is shown
|
|
27
|
+
_CONTROLS = re.compile("[\x00-\x08\x0b-\x1f\x7f-\x9f--]")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def clean(text: str) -> str:
|
|
31
|
+
"""``text`` without control characters and bidi controls (TAB and LF kept); each one becomes nothing, so an
|
|
32
|
+
escape sequence loses its ESC and is left as plain, harmless characters. Permission texts are first made
|
|
33
|
+
visible (``rexlib.cli.render.visible``), so there a bidi control shows as ``<U+202E>`` instead."""
|
|
34
|
+
return _CONTROLS.sub("", text)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Console:
|
|
38
|
+
"""Writes to ``output`` (flushed per write) and reads with ``input_fn``. ``colour`` adds ANSI colours (only
|
|
39
|
+
for an interactive terminal); ``echo`` writes each line read after the prompt (a piped transcript then reads
|
|
40
|
+
like a session). Knows whether the cursor is at the start of a line, so notes never land inside an answer."""
|
|
41
|
+
|
|
42
|
+
def __init__(self, output: TextIO, input_fn: Callable[[str], str], *, colour: bool, echo: bool) -> None:
|
|
43
|
+
self.output, self.input_fn, self.colour, self.echo = output, input_fn, colour, echo
|
|
44
|
+
self.at_line_start = True
|
|
45
|
+
|
|
46
|
+
def _raw(self, text: str) -> None:
|
|
47
|
+
if not text:
|
|
48
|
+
return
|
|
49
|
+
self.output.write(text)
|
|
50
|
+
self.output.flush()
|
|
51
|
+
self.at_line_start = text.endswith("\n")
|
|
52
|
+
|
|
53
|
+
def write(self, text: str) -> None:
|
|
54
|
+
"""Outside text (a streamed token, an answer) as it is, control characters removed."""
|
|
55
|
+
self._raw(clean(text))
|
|
56
|
+
|
|
57
|
+
def end_line(self) -> None:
|
|
58
|
+
"""Start a new line unless the cursor is already at the start of one."""
|
|
59
|
+
if not self.at_line_start:
|
|
60
|
+
self._raw("\n")
|
|
61
|
+
|
|
62
|
+
def paint(self, text: str, colour: str) -> str:
|
|
63
|
+
return f"{colour}{text}{RESET}" if self.colour and colour and text else text
|
|
64
|
+
|
|
65
|
+
def line(self, text: str = "", colour: str = "") -> None:
|
|
66
|
+
"""One line of its own (a new line first when an answer is still open); ``text`` is cleaned."""
|
|
67
|
+
self.end_line()
|
|
68
|
+
self._raw(self.paint(clean(text), colour) + "\n")
|
|
69
|
+
|
|
70
|
+
def note(self, text: str) -> None:
|
|
71
|
+
self.line(text, GRAY)
|
|
72
|
+
|
|
73
|
+
def error(self, text: str) -> None:
|
|
74
|
+
self.line(text, RED)
|
|
75
|
+
|
|
76
|
+
def read(self, prompt: str) -> str:
|
|
77
|
+
"""One line from ``input_fn`` (``EOFError`` and ``KeyboardInterrupt`` pass through)."""
|
|
78
|
+
self.end_line()
|
|
79
|
+
text = self.input_fn(prompt)
|
|
80
|
+
if self.echo:
|
|
81
|
+
self.write(text + "\n")
|
|
82
|
+
self.at_line_start = True
|
|
83
|
+
return text
|
rexlib/cli/options.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
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): the options of ``rexlib.cli.workflow``."""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Callable, Mapping
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from typing import TextIO
|
|
12
|
+
|
|
13
|
+
from ..gateway import GatewayOptions
|
|
14
|
+
from ..loop import Limits, ToolPolicy
|
|
15
|
+
from ..storage import Storage
|
|
16
|
+
|
|
17
|
+
DEFAULT_PROMPT = "rex › "
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class CliOptions:
|
|
22
|
+
"""Everything ``workflow`` takes besides the gateway configuration, the container and the tools.
|
|
23
|
+
|
|
24
|
+
- ``policy``: a ``ToolPolicy`` (its ``decide`` is used; its ``ask`` is replaced by the prompt unless set), or a
|
|
25
|
+
table ``tool name -> "auto" | "ask" | "forbid"`` (``"allow"`` / ``"deny"`` too; ``"*"`` = every other tool).
|
|
26
|
+
None: every tool asks.
|
|
27
|
+
- ``outward``: names of tools that act outside the machine (network, mail, ...). They always ask, even when the
|
|
28
|
+
policy allows them, and offer no "always". A tool with the attribute ``outward = True`` counts too.
|
|
29
|
+
- ``storage`` / ``gateway_options``: passed to the ``Gateway`` (``storage`` replaces the one in
|
|
30
|
+
``gateway_options``); ``gateway_options.providers`` is where tests put a ``FakeProvider``.
|
|
31
|
+
- ``target``: the class or model id to start with (None = the first class of the configuration).
|
|
32
|
+
- ``system``: an optional system prompt; ``limits``: the loop's limits per answer; ``stream``: stream answers.
|
|
33
|
+
- ``prompt``, ``input_fn`` (shows the prompt, returns one line; raises ``EOFError`` / ``KeyboardInterrupt``)
|
|
34
|
+
and ``output`` (None = ``sys.stdout`` at call time).
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
policy: ToolPolicy | Mapping[str, str] | None = None
|
|
38
|
+
outward: frozenset[str] = frozenset()
|
|
39
|
+
storage: Storage | None = None
|
|
40
|
+
gateway_options: GatewayOptions | None = None
|
|
41
|
+
target: str | None = None
|
|
42
|
+
system: str | None = None
|
|
43
|
+
prompt: str = DEFAULT_PROMPT
|
|
44
|
+
input_fn: Callable[[str], str] = input
|
|
45
|
+
output: TextIO | None = None
|
|
46
|
+
limits: Limits = field(default_factory=Limits)
|
|
47
|
+
stream: bool = True
|
|
@@ -0,0 +1,174 @@
|
|
|
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): tool permissions of ``rexlib.cli``: the app's policy, outward tools, the question.
|
|
6
|
+
|
|
7
|
+
``Permissions(policy, tools, console, ...)`` builds the ``ToolPolicy`` the loop gets (``tool_policy()``):
|
|
8
|
+
|
|
9
|
+
- the decision comes from the app: a ``ToolPolicy.decide`` or a table ``tool -> auto | ask | forbid``; without
|
|
10
|
+
either every tool asks (a prompt is no place for silent writes);
|
|
11
|
+
- an outward tool (``CliOptions.outward`` or ``tool.outward = True``) always asks, also when allowed;
|
|
12
|
+
- an "always" answer allows the same tool with exactly the same arguments (``always_key``: the tool name and the
|
|
13
|
+
arguments as sorted JSON, never the display summary, which may hide a second line) for the rest of the session
|
|
14
|
+
(in this object, never on disk);
|
|
15
|
+
- the question: ``Permission needed: <summary>`` (marked when the full text follows below), the full detail of
|
|
16
|
+
the call (``Tool.describe(args)[1]``) made visible by ``rexlib.cli.render`` (invisible characters as
|
|
17
|
+
``<U+XXXX>``, long blank runs as ``<300 spaces>``, long lines wrapped, never cut), at most ``DETAIL_LINES``
|
|
18
|
+
lines. When lines are left out, a warning says how many lines and characters are hidden, ``[v] view all``
|
|
19
|
+
prints everything and asks again, and "always" is not offered. ``Allow? [y] once [a] always [N] deny:``;
|
|
20
|
+
Enter, any other answer, an "a" where "always" is not offered (outward tools, hidden text) and EOF deny;
|
|
21
|
+
Ctrl-C cancels the whole turn. When nobody can answer (``interactive`` false) an ask is denied unasked;
|
|
22
|
+
- every denial prints one line with the reason, so the user sees what the model was refused.
|
|
23
|
+
|
|
24
|
+
All of it is printed through the console, which also removes control characters (``console.clean``).
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import dataclasses
|
|
30
|
+
import json
|
|
31
|
+
from collections.abc import Mapping
|
|
32
|
+
from types import MappingProxyType
|
|
33
|
+
from typing import Any
|
|
34
|
+
|
|
35
|
+
from ..loop import Decision, ToolPolicy
|
|
36
|
+
from ..messages import ToolCall
|
|
37
|
+
from ..tools.base import Tool, default_describe
|
|
38
|
+
from .console import YELLOW, Console
|
|
39
|
+
from .render import DETAIL_LINES, DETAIL_WIDTH, Detail, render_detail, visible_line
|
|
40
|
+
|
|
41
|
+
__all__ = ["DETAIL_LINES", "DETAIL_WIDTH", "MODES", "NOBODY", "Permissions", "always_key", "mode_table", "question"]
|
|
42
|
+
|
|
43
|
+
MODES: Mapping[str, Decision] = MappingProxyType({
|
|
44
|
+
"auto": Decision.ALLOW, "allow": Decision.ALLOW, "ask": Decision.ASK, "forbid": Decision.DENY,
|
|
45
|
+
"deny": Decision.DENY,
|
|
46
|
+
})
|
|
47
|
+
NOBODY = "needs approval and nobody can answer here"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def mode_table(table: Mapping[str, str]) -> dict[str, Decision]:
|
|
51
|
+
"""``tool -> auto | ask | forbid`` checked; a ``ValueError`` names the bad entry."""
|
|
52
|
+
out: dict[str, Decision] = {}
|
|
53
|
+
for name, mode in table.items():
|
|
54
|
+
decision = MODES.get(str(mode).strip().lower())
|
|
55
|
+
if decision is None:
|
|
56
|
+
raise ValueError(f"policy[{name!r}] = {mode!r}; expected one of {', '.join(MODES)}")
|
|
57
|
+
out[str(name)] = decision
|
|
58
|
+
return out
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def always_key(name: str, args: Mapping[str, Any]) -> tuple[str, str]:
|
|
62
|
+
"""What an "always" answer remembers: the tool and its full arguments (sorted JSON)."""
|
|
63
|
+
return name, json.dumps(args, sort_keys=True, ensure_ascii=False, default=str)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def question(*, always: bool, view: bool) -> str:
|
|
67
|
+
"""The answer line: ``[a] always`` only when allowed, ``[v] view all`` only when text is hidden."""
|
|
68
|
+
return ("Allow? [y] once" + (" [a] always" if always else "") + (" [v] view all" if view else "")
|
|
69
|
+
+ " [N] deny: ")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class Permissions:
|
|
73
|
+
"""The session's permission state; see the module docstring."""
|
|
74
|
+
|
|
75
|
+
def __init__(self, policy: ToolPolicy | Mapping[str, str] | None, tools: Mapping[str, Tool],
|
|
76
|
+
console: Console, *, outward: frozenset[str] = frozenset(), interactive: bool = True) -> None:
|
|
77
|
+
self.base = policy if isinstance(policy, ToolPolicy) else ToolPolicy()
|
|
78
|
+
self.table = mode_table(policy) if isinstance(policy, Mapping) else None
|
|
79
|
+
self.tools, self.console, self.interactive = tools, console, interactive
|
|
80
|
+
self.outward = frozenset(outward) | {n for n, t in tools.items() if getattr(t, "outward", False) is True}
|
|
81
|
+
self.always: set[tuple[str, str]] = set() # always_key() of each "always" answer
|
|
82
|
+
|
|
83
|
+
def tool_policy(self) -> ToolPolicy:
|
|
84
|
+
"""The policy for ``RunOptions.tool_policy`` (enabled tools, caps and timeouts kept from the app's)."""
|
|
85
|
+
return dataclasses.replace(self.base, decide=self.decide, ask=self.base.ask or self.ask)
|
|
86
|
+
|
|
87
|
+
def mode(self, name: str) -> str:
|
|
88
|
+
"""What ``/tools`` shows for a tool: auto, ask, forbid, "policy" (the app decides per call), plus outward."""
|
|
89
|
+
if self.table is not None:
|
|
90
|
+
decision = self.table.get(name, self.table.get("*", Decision.ASK))
|
|
91
|
+
shown = {Decision.ALLOW: "auto", Decision.ASK: "ask", Decision.DENY: "forbid"}[decision]
|
|
92
|
+
else:
|
|
93
|
+
shown = "policy" if self.base.decide is not None else "ask"
|
|
94
|
+
return f"{shown}, outward: always asks" if name in self.outward else shown
|
|
95
|
+
|
|
96
|
+
def describe(self, call: ToolCall, args: dict[str, Any]) -> tuple[str, str]:
|
|
97
|
+
"""(summary, detail) of a call from the tool's ``describe``, as the tool gave them."""
|
|
98
|
+
name = str(call.function.get("name") or "")
|
|
99
|
+
tool = self.tools.get(name)
|
|
100
|
+
try:
|
|
101
|
+
summary, detail = tool.describe(args) if tool is not None else default_describe(name, args)
|
|
102
|
+
return str(summary), str(detail or "")
|
|
103
|
+
except Exception: # a broken describe must not break the question
|
|
104
|
+
return name, json.dumps(args, ensure_ascii=False, default=str)
|
|
105
|
+
|
|
106
|
+
def summary(self, call: ToolCall, args: dict[str, Any]) -> str:
|
|
107
|
+
"""The summary made visible (``<U+XXXX>`` markers, blank runs collapsed)."""
|
|
108
|
+
return visible_line(self.describe(call, args)[0])
|
|
109
|
+
|
|
110
|
+
def decide(self, call: ToolCall, args: dict[str, Any]) -> tuple[Decision, str]:
|
|
111
|
+
name = str(call.function.get("name") or "")
|
|
112
|
+
decision, reason = self._app_decision(call, args, name)
|
|
113
|
+
if decision == Decision.ALLOW and name in self.outward:
|
|
114
|
+
decision, reason = Decision.ASK, "outward action"
|
|
115
|
+
if decision == Decision.ASK and name not in self.outward and always_key(name, args) in self.always:
|
|
116
|
+
return Decision.ALLOW, "allowed always (this session)"
|
|
117
|
+
if decision == Decision.ASK and not self.interactive:
|
|
118
|
+
decision, reason = Decision.DENY, NOBODY
|
|
119
|
+
if decision == Decision.DENY:
|
|
120
|
+
self.console.note(f"· {self.summary(call, args)}: denied ({reason or 'policy'})")
|
|
121
|
+
return decision, reason
|
|
122
|
+
|
|
123
|
+
def _app_decision(self, call: ToolCall, args: dict[str, Any], name: str) -> tuple[Decision, str]:
|
|
124
|
+
if self.table is not None:
|
|
125
|
+
return self.table.get(name, self.table.get("*", Decision.ASK)), "policy"
|
|
126
|
+
if self.base.decide is None:
|
|
127
|
+
return Decision.ASK, ""
|
|
128
|
+
raw = self.base.decide(call, args)
|
|
129
|
+
value, reason = (raw[0], str(raw[1])) if isinstance(raw, tuple) else (raw, "")
|
|
130
|
+
return Decision(value), reason
|
|
131
|
+
|
|
132
|
+
def ask(self, call: ToolCall, args: dict[str, Any]) -> bool:
|
|
133
|
+
"""The question; True = allowed. An "always" answer is remembered for the session; Ctrl-C propagates
|
|
134
|
+
(``KeyboardInterrupt``: the turn is cancelled)."""
|
|
135
|
+
name = str(call.function.get("name") or "")
|
|
136
|
+
raw_summary, raw_detail = self.describe(call, args)
|
|
137
|
+
summary, detail = visible_line(raw_summary), render_detail(raw_detail, raw_summary)
|
|
138
|
+
always_ok = name not in self.outward and not detail.hidden_lines
|
|
139
|
+
self._show(summary, detail)
|
|
140
|
+
answer = self._answer(question(always=always_ok, view=bool(detail.hidden_lines)), detail)
|
|
141
|
+
if answer in ("a", "always") and always_ok:
|
|
142
|
+
self.always.add(always_key(name, args))
|
|
143
|
+
return True
|
|
144
|
+
if answer in ("y", "yes"):
|
|
145
|
+
return True
|
|
146
|
+
self.console.note(f"· {summary}: denied")
|
|
147
|
+
return False
|
|
148
|
+
|
|
149
|
+
def _show(self, summary: str, detail: Detail) -> None:
|
|
150
|
+
mark = " (full text below)" if detail.all_lines else ""
|
|
151
|
+
if detail.hidden_lines:
|
|
152
|
+
mark = " (clipped: see the warning below)"
|
|
153
|
+
self.console.line(f"Permission needed: {summary}{mark}", YELLOW)
|
|
154
|
+
for line in detail.lines:
|
|
155
|
+
self.console.line(f" {line}")
|
|
156
|
+
if detail.hidden_lines:
|
|
157
|
+
self.console.line(f"WARNING: {detail.hidden_lines} lines / {detail.hidden_chars} characters hidden; "
|
|
158
|
+
"[v] shows everything before you decide", YELLOW)
|
|
159
|
+
|
|
160
|
+
def _answer(self, prompt: str, detail: Detail) -> str:
|
|
161
|
+
"""Read the answer; ``v`` prints every line and asks again; EOF = deny, Ctrl-C propagates."""
|
|
162
|
+
while True:
|
|
163
|
+
try:
|
|
164
|
+
answer = self.console.read(prompt).strip().lower()
|
|
165
|
+
except (EOFError, KeyboardInterrupt) as exc:
|
|
166
|
+
self.console.at_line_start = False # input() left the cursor after the question
|
|
167
|
+
self.console.end_line()
|
|
168
|
+
if isinstance(exc, KeyboardInterrupt):
|
|
169
|
+
raise
|
|
170
|
+
return ""
|
|
171
|
+
if answer not in ("v", "view") or not detail.hidden_lines:
|
|
172
|
+
return answer
|
|
173
|
+
for line in detail.all_lines:
|
|
174
|
+
self.console.line(f" {line}")
|
rexlib/cli/render.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
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): what a person must see before allowing a tool call, nothing hidden and nothing invisible.
|
|
6
|
+
|
|
7
|
+
- ``mark_invisible(text)``: every format character (Unicode category Cf: zero-width spaces and joiners, bidi
|
|
8
|
+
controls, the BOM ...), U+2028 / U+2029 and the tag characters U+E0000-U+E007F become a visible ``<U+XXXX>``.
|
|
9
|
+
- ``visible(text)``: ``mark_invisible`` plus runs of more than ``MAX_BLANKS`` spaces or tabs shown as one marker
|
|
10
|
+
(``<300 spaces>``), so a command cannot push its tail out of sight with blanks.
|
|
11
|
+
- ``visible_line(text)``: ``visible`` plus every line break as a marker (for the one-line summary).
|
|
12
|
+
- ``render_detail(detail, summary)``: the detail lines of a call, long lines wrapped (never cut), at most
|
|
13
|
+
``DETAIL_LINES`` lines shown; ``Detail.hidden_lines`` / ``hidden_chars`` say what is left out (the question then
|
|
14
|
+
warns, offers ``[v] view all`` and no "always").
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import re
|
|
20
|
+
import unicodedata
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
|
|
23
|
+
DETAIL_LINES = 20
|
|
24
|
+
DETAIL_WIDTH = 200
|
|
25
|
+
MAX_BLANKS = 8
|
|
26
|
+
_BREAKS = "\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029"
|
|
27
|
+
_BLANK_RUN = re.compile("[ \t]{%d,}" % (MAX_BLANKS + 1))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _invisible(char: str) -> bool:
|
|
31
|
+
code = ord(char)
|
|
32
|
+
return unicodedata.category(char) == "Cf" or code in (0x2028, 0x2029) or 0xE0000 <= code <= 0xE007F
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def mark_invisible(text: str) -> str:
|
|
36
|
+
"""Invisible and direction-changing characters as ``<U+XXXX>`` markers."""
|
|
37
|
+
return "".join(f"<U+{ord(c):04X}>" if _invisible(c) else c for c in text)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _blanks(match: re.Match[str]) -> str:
|
|
41
|
+
run = match.group(0)
|
|
42
|
+
kind = "spaces" if set(run) == {" "} else "tabs" if set(run) == {"\t"} else "blanks"
|
|
43
|
+
return f"<{len(run)} {kind}>"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def visible(text: str) -> str:
|
|
47
|
+
"""``mark_invisible`` plus long runs of blanks as one marker."""
|
|
48
|
+
return _BLANK_RUN.sub(_blanks, mark_invisible(text))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def visible_line(text: str) -> str:
|
|
52
|
+
"""``visible`` for a one-line text: every line break (LF, CR, VT, FF, FS/GS/RS, NEL, U+2028/U+2029) too is
|
|
53
|
+
shown as ``<U+XXXX>``, so the text can never look like extra lines."""
|
|
54
|
+
return "".join(f"<U+{ord(c):04X}>" if c in _BREAKS else c for c in visible(text))
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True)
|
|
58
|
+
class Detail:
|
|
59
|
+
"""The detail of a call as shown: ``lines`` (at most ``DETAIL_LINES``), ``all_lines`` (everything, wrapped),
|
|
60
|
+
and how many lines and characters are not shown."""
|
|
61
|
+
|
|
62
|
+
lines: tuple[str, ...] = ()
|
|
63
|
+
all_lines: tuple[str, ...] = ()
|
|
64
|
+
hidden_lines: int = 0
|
|
65
|
+
hidden_chars: int = 0
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def render_detail(detail: str, summary: str, *, max_lines: int = DETAIL_LINES, width: int = DETAIL_WIDTH) -> Detail:
|
|
69
|
+
"""``detail`` made visible, wrapped at ``width`` and limited to ``max_lines`` (empty when it only repeats the
|
|
70
|
+
summary)."""
|
|
71
|
+
text = visible(detail).strip("\r\n")
|
|
72
|
+
if not text.strip() or text.strip() == visible(summary).strip():
|
|
73
|
+
return Detail()
|
|
74
|
+
wrapped: list[str] = []
|
|
75
|
+
for line in text.splitlines():
|
|
76
|
+
wrapped += [line[i:i + width] for i in range(0, len(line), width)] or [""]
|
|
77
|
+
hidden = wrapped[max_lines:]
|
|
78
|
+
return Detail(tuple(wrapped[:max_lines]), tuple(wrapped), len(hidden), sum(len(x) for x in hidden))
|