"""The world's tool layer: `@tool` methods of a `World` subclass, their JSON schemas (from the type hints and the docstring's first paragraph), argument checks, runtime knobs and lane pauses (the admin API, saved in `knobs.json`), and secret redaction. `server.py` serves it over HTTP. A parameter named `agent` (or annotated `Agent`) receives the caller and is never shown in the schema. """ from __future__ import annotations import inspect import json import logging import os import re import threading import types import typing from collections.abc import Callable from dataclasses import dataclass from pathlib import Path from typing import Any log = logging.getLogger(__name__) POOLS = ("fast", "slow") @dataclass(frozen=True) class Agent: """Who calls: the agent's name (from its credential).""" name: str class ToolError(Exception): """Raise from a tool: the agent reads `message` as the tool's error result. `retry_after_s`: the call cannot succeed before then (a budget, a busy backend).""" def __init__(self, message: str, code: str = "tool_error", retry_after_s: float | None = None) -> None: super().__init__(message) self.code = code self.message = message self.retry_after_s = retry_after_s def tool(fn: Callable | None = None, *, pool: str = "fast", read_only: bool = False) -> Any: """Mark a method as a tool: `@tool`, or `@tool(pool="slow", read_only=True)`. `pool`: the server's thread pool for the call ("slow" for tools that block for seconds). `read_only`: the tool changes nothing (manifest `annotations.readOnlyHint`).""" if pool not in POOLS: raise ValueError(f"pool {pool!r} must be one of {POOLS}") def mark(f: Callable) -> Callable: f.world_tool = {"pool": pool, "read_only": read_only} # type: ignore[attr-defined] return f return mark if fn is None else mark(fn) # ------------------------------------------------------------------ schemas and argument checks def _is_agent(name: str, hint: Any) -> bool: return name == "agent" or hint is Agent def type_schema(hint: Any) -> dict[str, Any]: """The JSON schema of a type hint: str, int, float, bool, list[...], dict, Literal[...], X | None (accepts null too).""" origin, args = typing.get_origin(hint), typing.get_args(hint) if origin in (typing.Union, types.UnionType): rest = [a for a in args if a is not type(None)] if len(rest) != 1 or len(rest) == len(args): raise TypeError(f"unions other than `X | None` are not supported: {hint!r}") schema = type_schema(rest[0]) schema["type"] = [schema["type"], "null"] if "enum" in schema: schema["enum"] = [*schema["enum"], None] return schema simple = {str: "string", bool: "boolean", int: "integer", float: "number", dict: "object"} if hint in simple or origin is dict: return {"type": simple[dict if origin is dict else hint]} if origin is list: return {"type": "array", "items": type_schema(args[0]) if args else {}} if origin is typing.Literal: kinds = {type(a) for a in args} return {"type": "string" if kinds == {str} else "integer", "enum": list(args)} raise TypeError(f"unsupported type {hint!r}") def tool_schema(fn: Callable) -> dict[str, Any]: """{name, description, parameters} of a tool function or method.""" hints = typing.get_type_hints(fn) props, required = {}, [] for p in inspect.signature(fn).parameters.values(): if p.name == "self" or _is_agent(p.name, hints.get(p.name)): continue props[p.name] = schema = type_schema(hints[p.name]) if p.default is p.empty: required.append(p.name) elif p.default is not None: schema["default"] = p.default params: dict[str, Any] = {"type": "object", "properties": props, "additionalProperties": False} if required: params["required"] = required doc = inspect.getdoc(fn) or "" return {"name": fn.__name__, "description": " ".join(doc.split("\n\n")[0].split()), "parameters": params} _JSON_TYPES = {"string": (str,), "integer": (int,), "number": (int, float), "boolean": (bool,), "array": (list,), "object": (dict,), "null": (type(None),)} def _check(schema: dict[str, Any], value: Any, where: str) -> str | None: t = schema.get("type") types_ = [t] if isinstance(t, str) else t or [] if types_ and not any(isinstance(value, _JSON_TYPES[x]) and not ( x in ("integer", "number") and isinstance(value, bool)) for x in types_): return f"{where} must be {' or '.join(types_)}, got {json.dumps(value)[:60]}" if "enum" in schema and value not in schema["enum"]: return f"{where} must be one of {schema['enum']}, got {json.dumps(value)[:60]}" if isinstance(value, list) and schema.get("items"): for i, v in enumerate(value): if err := _check(schema["items"], v, f"{where}[{i}]"): return err return None def check_args(params: dict[str, Any], args: Any) -> str | None: """An error message for arguments that do not fit the tool's schema, else None.""" if not isinstance(args, dict): return f"arguments must be a JSON object, got {type(args).__name__}" props = params["properties"] if unknown := [k for k in args if k not in props]: return f"unknown argument(s) {', '.join(unknown)}; expected: {', '.join(props) or 'none'}" if missing := [k for k in params.get("required", ()) if k not in args]: return f"missing required argument(s): {', '.join(missing)}" return next((err for k, v in args.items() if (err := _check(props[k], v, k))), None) # ------------------------------------------------------------------ secrets _SECRET_NAME = re.compile(r"TOKEN|SECRET|PASSWORD|INVITE|API_KEY|_KEY$", re.IGNORECASE) def redact(value: Any) -> Any: """`value` (JSON-able) with the value of every secret-looking environment variable (8+ characters) replaced by "[redacted]".""" secrets = sorted({v for k, v in os.environ.items() if _SECRET_NAME.search(k) and len(v) >= 8}, key=len, reverse=True) text = json.dumps(value, default=str) if not any(s in text for s in secrets): return value for s in secrets: text = text.replace(json.dumps(s)[1:-1], "[redacted]") return json.loads(text) # ------------------------------------------------------------------ admin: knobs and lane pauses LANE_RE = re.compile(r"^[a-z][a-z0-9_.-]{0,63}$") KNOB_TYPES = (int, float, bool, str) @dataclass class Knob: name: str type: type default: Any min: float | None = None max: float | None = None doc: str = "" on_change: Callable[[Any], None] | None = None def check(self, value: Any) -> Any: """`value` as this knob's type (raises ValueError).""" t = self.type if t is bool or t is str: ok = isinstance(value, t) else: # int or float: JSON numbers, not booleans; 2.0 is an int, 2.5 is not ok = isinstance(value, int | float) and not isinstance(value, bool) and ( t is float or float(value).is_integer()) if not ok: raise ValueError(f"{self.name}: expected {t.__name__}, got {json.dumps(value)}") value = t(value) if self.min is not None and value < self.min: raise ValueError(f"{self.name}: {value} is below the minimum {self.min:g}") if self.max is not None and value > self.max: raise ValueError(f"{self.name}: {value} is above the maximum {self.max:g}") return value class Admin: """Knobs (name -> value) and paused lanes (lane -> reason), saved in `/knobs.json` and read back at the next start. Thread-safe.""" def __init__(self, state_dir: str | os.PathLike | None = None) -> None: self.path = Path(state_dir) / "knobs.json" if state_dir is not None else None self.knobs: dict[str, Knob] = {} self.values: dict[str, Any] = {} self.stored: dict[str, Any] = {} # values set through the admin API self.paused: dict[str, str] = {} self.lock = threading.RLock() try: data = json.loads(self.path.read_text()) if self.path else {} knobs, paused = data.get("knobs") or {}, data.get("paused") or {} if not isinstance(knobs, dict) or not isinstance(paused, dict) or not all( isinstance(k, str) and isinstance(v, str) for k, v in paused.items()): raise ValueError('expected {"knobs": {name: value}, "paused": {lane: reason}}') self.stored, self.paused = dict(knobs), dict(paused) except FileNotFoundError: pass except (OSError, ValueError, AttributeError) as e: # never fail the start over this file log.warning("%s: unreadable (%s); starting from the defaults", self.path, e) def register(self, knob: Knob) -> Any: with self.lock: value = knob.check(knob.default) if knob.name in self.stored: try: value = knob.check(self.stored[knob.name]) except ValueError as e: log.warning("knobs.json: stored value ignored: %s", e) self.knobs[knob.name] = knob self.values[knob.name] = value return value def describe(self) -> dict[str, dict[str, Any]]: with self.lock: return {n: {"value": self.values[n], "default": k.default, "type": k.type.__name__, "min": k.min, "max": k.max, "doc": k.doc} for n, k in self.knobs.items()} def set(self, updates: dict[str, Any]) -> list[dict[str, Any]]: """Validate every update, apply them (on_change callbacks included) and save, all or nothing. Returns [{name, old, new}]; raises ValueError (nothing changed) on a bad value or a failing on_change (those already applied get on_change(old) back).""" if not isinstance(updates, dict) or not updates: raise ValueError("expected {knob: value, ...}") with self.lock: if unknown := sorted(set(updates) - set(self.knobs)): raise ValueError(f"unknown knob(s) {', '.join(unknown)}; knobs: " f"{', '.join(self.knobs) or 'none'}") checked = {n: self.knobs[n].check(v) for n, v in updates.items()} changes: list[dict[str, Any]] = [] for n, v in checked.items(): try: if self.knobs[n].on_change is not None: self.knobs[n].on_change(v) except Exception as e: # noqa: BLE001 (any refusal rolls the patch back) for c in reversed(changes): try: if self.knobs[c["name"]].on_change is not None: self.knobs[c["name"]].on_change(c["old"]) except Exception: log.exception("knob %s: restoring %r failed", c["name"], c["old"]) raise ValueError(f"{n}: the world refused {json.dumps(v)}: {e}") from None changes.append({"name": n, "old": self.values[n], "new": v}) for c in changes: self.values[c["name"]] = self.stored[c["name"]] = c["new"] self._save() return changes def pause(self, lanes: list[str], reason: str = "") -> None: self._lanes(lanes) with self.lock: self.paused.update(dict.fromkeys(lanes, reason)) self._save() def resume(self, lanes: list[str]) -> None: self._lanes(lanes) with self.lock: for lane in lanes: self.paused.pop(lane, None) self._save() @staticmethod def _lanes(lanes: Any) -> None: if not isinstance(lanes, list) or not lanes or not all( isinstance(x, str) and LANE_RE.match(x) for x in lanes): raise ValueError(f"lanes: expected a list of names matching {LANE_RE.pattern}") def _save(self) -> None: if self.path is None: return tmp = self.path.with_suffix(".tmp") tmp.write_text(json.dumps({"knobs": self.stored, "paused": self.paused}, indent=1)) tmp.replace(self.path) # ------------------------------------------------------------------ the base class class World: """Base class. Class attributes: `name`, `description` (shown to the agents). The server runs calls concurrently: the world guards its state.""" name: typing.ClassVar[str] = "world" description: typing.ClassVar[str] = "" @classmethod def tool_functions(cls) -> dict[str, Callable]: """The `@tool` functions of the class, by name (in definition order).""" found = {} for klass in reversed(cls.__mro__): for attr, value in vars(klass).items(): if hasattr(value, "world_tool"): found[attr] = value return found @classmethod def manifest(cls) -> dict[str, Any]: """{"name", "description", "tools": [{name, description, parameters, annotations?}]}, built once per class (it depends on the code only).""" if "_manifest" not in cls.__dict__: tools = [] for fn in cls.tool_functions().values(): t = tool_schema(fn) if fn.world_tool["read_only"]: t["annotations"] = {"readOnlyHint": True} tools.append(t) cls._manifest = {"name": cls.name, "description": cls.description, "tools": tools} return json.loads(json.dumps(cls._manifest)) @classmethod def pool(cls, tool: str) -> str: fn = cls.tool_functions().get(tool) return fn.world_tool["pool"] if fn is not None else "fast" def call(self, tool: str, args: dict[str, Any], agent: Agent) -> Any: """Run `tool` for `agent` (KeyError for an unknown tool; ToolError for a refusal).""" fn = self.tool_functions()[tool] hints = typing.get_type_hints(fn) extra = {p.name: agent for p in inspect.signature(fn).parameters.values() if p.name != "self" and _is_agent(p.name, hints.get(p.name))} return fn(self, **args, **extra) def metrics(self) -> dict[str, float]: """World-specific numbers for `GET /metrics`.""" return {} def state_dir(self) -> str | os.PathLike | None: """Where `knobs.json` lives (None: in memory only).""" return None @property def admin(self) -> Admin: if "_admin" not in self.__dict__: self.__dict__["_admin"] = Admin(self.state_dir()) return self.__dict__["_admin"] def knob(self, name: str, type: type, default: Any, *, min: float | None = None, max: float | None = None, doc: str = "", on_change: Callable[[Any], None] | None = None) -> Any: """Register a runtime knob (int, float, bool or str) and return its current value: the value set through `PATCH /admin/knobs` if any (it survives restarts), else `default`. A change calls `on_change(value)` (raise to refuse it).""" if type not in KNOB_TYPES: raise ValueError(f"knob {name}: type must be one of int, float, bool, str") return self.admin.register(Knob(name, type, default, min, max, doc, on_change)) def paused(self, lane: str) -> bool: """Did an operator pause `lane` (`POST /admin/pause`)?""" return lane in self.admin.paused