"""Small shared helpers.""" from __future__ import annotations import json import os import random import re import string import tempfile import time from dataclasses import asdict, is_dataclass from pathlib import Path from typing import Any from collections.abc import Iterable def now() -> float: return time.time() def iso_time(ts: float | None = None) -> str: return time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(ts if ts is not None else now())) _KEEP = string.ascii_lowercase + string.digits def short_id(n: int = 6) -> str: return "".join(random.choice(_KEEP) for _ in range(n)) def new_session_id() -> str: return f"{time.strftime('%Y%m%d-%H%M%S')}-{short_id(4)}" def api_session_id(prefix: str = "ses_airouter") -> str: # OpenCode Go asks clients for a stable x-opencode-session header. return f"{prefix}_{short_id(12)}" def atomic_write_text(path: Path, text: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) fd, tmp = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent)) try: with os.fdopen(fd, "w", encoding="utf-8", newline="") as fh: fh.write(text) fh.flush() os.fsync(fh.fileno()) os.replace(tmp, path) finally: try: os.unlink(tmp) except FileNotFoundError: pass def atomic_write_json(path: Path, data: Any) -> None: atomic_write_text(path, json.dumps(data, ensure_ascii=False, indent=2)) def read_json(path: Path, default: Any = None) -> Any: try: return json.loads(path.read_text(encoding="utf-8")) except (FileNotFoundError, json.JSONDecodeError, OSError): return default def append_jsonl(path: Path, data: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) with open(path, "a", encoding="utf-8", newline="") as fh: fh.write(json.dumps(data, ensure_ascii=False) + "\n") fh.flush() def read_jsonl(path: Path) -> list[Any]: if not path.exists(): return [] out: list[Any] = [] with open(path, "r", encoding="utf-8", errors="replace") as fh: for line in fh: line = line.strip() if not line: continue try: out.append(json.loads(line)) except json.JSONDecodeError: continue return out def truncate(text: str, limit: int, marker: str = "\n… (обрезано)") -> str: if limit <= 0 or len(text) <= limit: return text return text[: max(0, limit - len(marker))] + marker def estimate_tokens(text: str) -> int: """Cheap estimate that works for both Cyrillic and code.""" if not text: return 0 return max(1, len(text) // 3) def estimate_messages_tokens(messages: Iterable[dict[str, Any]]) -> int: total = 0 for msg in messages: total += 4 for key in ("content", "reasoning_content"): val = msg.get(key) if isinstance(val, str): total += estimate_tokens(val) for tc in msg.get("tool_calls") or []: total += estimate_tokens(json.dumps(tc, ensure_ascii=False)) return total def format_duration(seconds: float | None) -> str: if seconds is None: return "—" seconds = max(0.0, float(seconds)) if seconds < 60: return f"{seconds:.1f}s" m, s = divmod(int(seconds), 60) if m < 60: return f"{m}m {s:02d}s" h, m = divmod(m, 60) return f"{h}h {m:02d}m" def format_tokens(n: int) -> str: if n < 1000: return str(n) if n < 1_000_000: return f"{n / 1000:.1f}k" return f"{n / 1_000_000:.2f}M" def format_cost(cost: float) -> str: if cost <= 0: return "$0" if cost < 0.01: return f"${cost:.4f}" return f"${cost:.3f}" def slugify(text: str, limit: int = 28) -> str: text = text.strip().lower() text = re.sub(r"[^a-z0-9а-яё]+", "-", text) text = text.strip("-") return text[:limit] or "task" def compact_args(args: dict[str, Any], limit: int = 160) -> str: """One-line, human-readable rendering of tool arguments for the UI.""" parts: list[str] = [] for key, value in args.items(): if key in {"content", "new_string", "old_string"}: rendered = f"<{len(str(value))} симв.>" elif key in {"task", "message", "pattern", "command", "path"}: rendered = str(value).replace("\n", " ") elif isinstance(value, (dict, list)): rendered = json.dumps(value, ensure_ascii=False) else: rendered = str(value) rendered = truncate(rendered, 80, "…").replace("\n", " ") parts.append(f"{key}={rendered}") text = ", ".join(parts) return truncate(text, limit, "…") def redact_secrets(text: str) -> str: """Belt-and-braces redaction for anything that looks like a token.""" text = re.sub(r"(oc_sk_[A-Za-z0-9_-]+)", "oc_sk_***", text) text = re.sub(r"(st_[A-Za-z0-9-]{8,})", "st_***", text) text = re.sub(r"(rt_[A-Za-z0-9-]{8,})", "rt_***", text) return text def to_jsonable(value: Any) -> Any: if is_dataclass(value): return asdict(value) if isinstance(value, Path): return str(value) if isinstance(value, set): return sorted(value) return value def parse_int(value: Any, default: int, minimum: int | None = None, maximum: int | None = None) -> int: try: out = int(value) except (TypeError, ValueError): return default if minimum is not None: out = max(minimum, out) if maximum is not None: out = min(maximum, out) return out def tail_lines(text: str, limit: int = 200) -> str: lines = text.splitlines() if len(lines) <= limit: return text return "\n".join(lines[-limit:])