1"""Small shared helpers."""
2
3from __future__ import annotations
4
5import json
6import os
7import random
8import re
9import string
10import tempfile
11import time
12from dataclasses import asdict, is_dataclass
13from pathlib import Path
14from typing import Any
15from collections.abc import Iterable
16
17
18def now() -> float:
19 return time.time()
20
21
22def iso_time(ts: float | None = None) -> str:
23 return time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(ts if ts is not None else now()))
24
25
26_KEEP = string.ascii_lowercase + string.digits
27
28
29def short_id(n: int = 6) -> str:
30 return "".join(random.choice(_KEEP) for _ in range(n))
31
32
33def new_session_id() -> str:
34 return f"{time.strftime('%Y%m%d-%H%M%S')}-{short_id(4)}"
35
36
37def api_session_id(prefix: str = "ses_airouter") -> str:
38 # OpenCode Go asks clients for a stable x-opencode-session header.
39 return f"{prefix}_{short_id(12)}"
40
41
42def atomic_write_text(path: Path, text: str) -> None:
43 path.parent.mkdir(parents=True, exist_ok=True)
44 fd, tmp = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent))
45 try:
46 with os.fdopen(fd, "w", encoding="utf-8", newline="") as fh:
47 fh.write(text)
48 fh.flush()
49 os.fsync(fh.fileno())
50 os.replace(tmp, path)
51 finally:
52 try:
53 os.unlink(tmp)
54 except FileNotFoundError:
55 pass
56
57
58def atomic_write_json(path: Path, data: Any) -> None:
59 atomic_write_text(path, json.dumps(data, ensure_ascii=False, indent=2))
60
61
62def read_json(path: Path, default: Any = None) -> Any:
63 try:
64 return json.loads(path.read_text(encoding="utf-8"))
65 except (FileNotFoundError, json.JSONDecodeError, OSError):
66 return default
67
68
69def append_jsonl(path: Path, data: Any) -> None:
70 path.parent.mkdir(parents=True, exist_ok=True)
71 with open(path, "a", encoding="utf-8", newline="") as fh:
72 fh.write(json.dumps(data, ensure_ascii=False) + "\n")
73 fh.flush()
74
75
76def read_jsonl(path: Path) -> list[Any]:
77 if not path.exists():
78 return []
79 out: list[Any] = []
80 with open(path, "r", encoding="utf-8", errors="replace") as fh:
81 for line in fh:
82 line = line.strip()
83 if not line:
84 continue
85 try:
86 out.append(json.loads(line))
87 except json.JSONDecodeError:
88 continue
89 return out
90
91
92def truncate(text: str, limit: int, marker: str = "\n… (обрезано)") -> str:
93 if limit <= 0 or len(text) <= limit:
94 return text
95 return text[: max(0, limit - len(marker))] + marker
96
97
98def estimate_tokens(text: str) -> int:
99 """Cheap estimate that works for both Cyrillic and code."""
100 if not text:
101 return 0
102 return max(1, len(text) // 3)
103
104
105def estimate_messages_tokens(messages: Iterable[dict[str, Any]]) -> int:
106 total = 0
107 for msg in messages:
108 total += 4
109 for key in ("content", "reasoning_content"):
110 val = msg.get(key)
111 if isinstance(val, str):
112 total += estimate_tokens(val)
113 for tc in msg.get("tool_calls") or []:
114 total += estimate_tokens(json.dumps(tc, ensure_ascii=False))
115 return total
116
117
118def format_duration(seconds: float | None) -> str:
119 if seconds is None:
120 return "—"
121 seconds = max(0.0, float(seconds))
122 if seconds < 60:
123 return f"{seconds:.1f}s"
124 m, s = divmod(int(seconds), 60)
125 if m < 60:
126 return f"{m}m {s:02d}s"
127 h, m = divmod(m, 60)
128 return f"{h}h {m:02d}m"
129
130
131def format_tokens(n: int) -> str:
132 if n < 1000:
133 return str(n)
134 if n < 1_000_000:
135 return f"{n / 1000:.1f}k"
136 return f"{n / 1_000_000:.2f}M"
137
138
139def format_cost(cost: float) -> str:
140 if cost <= 0:
141 return "$0"
142 if cost < 0.01:
143 return f"${cost:.4f}"
144 return f"${cost:.3f}"
145
146
147def slugify(text: str, limit: int = 28) -> str:
148 text = text.strip().lower()
149 text = re.sub(r"[^a-z0-9а-яё]+", "-", text)
150 text = text.strip("-")
151 return text[:limit] or "task"
152
153
154def compact_args(args: dict[str, Any], limit: int = 160) -> str:
155 """One-line, human-readable rendering of tool arguments for the UI."""
156 parts: list[str] = []
157 for key, value in args.items():
158 if key in {"content", "new_string", "old_string"}:
159 rendered = f"<{len(str(value))} симв.>"
160 elif key in {"task", "message", "pattern", "command", "path"}:
161 rendered = str(value).replace("\n", " ")
162 elif isinstance(value, (dict, list)):
163 rendered = json.dumps(value, ensure_ascii=False)
164 else:
165 rendered = str(value)
166 rendered = truncate(rendered, 80, "…").replace("\n", " ")
167 parts.append(f"{key}={rendered}")
168 text = ", ".join(parts)
169 return truncate(text, limit, "…")
170
171
172def redact_secrets(text: str) -> str:
173 """Belt-and-braces redaction for anything that looks like a token."""
174 text = re.sub(r"(oc_sk_[A-Za-z0-9_-]+)", "oc_sk_***", text)
175 text = re.sub(r"(st_[A-Za-z0-9-]{8,})", "st_***", text)
176 text = re.sub(r"(rt_[A-Za-z0-9-]{8,})", "rt_***", text)
177 return text
178
179
180def to_jsonable(value: Any) -> Any:
181 if is_dataclass(value):
182 return asdict(value)
183 if isinstance(value, Path):
184 return str(value)
185 if isinstance(value, set):
186 return sorted(value)
187 return value
188
189
190def parse_int(value: Any, default: int, minimum: int | None = None, maximum: int | None = None) -> int:
191 try:
192 out = int(value)
193 except (TypeError, ValueError):
194 return default
195 if minimum is not None:
196 out = max(minimum, out)
197 if maximum is not None:
198 out = min(maximum, out)
199 return out
200
201
202def tail_lines(text: str, limit: int = 200) -> str:
203 lines = text.splitlines()
204 if len(lines) <= limit:
205 return text
206 return "\n".join(lines[-limit:])