release: Themiz на Gitea

This commit is contained in:
public-repo-gate
2026-10-19 11:10:53 +03:00
parent e52e76d4ea
commit 067c6c2414
225 changed files with 240125 additions and 26157 deletions
Regular → Executable
+334 -5
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""cli_probe.py — доступен ли чужой CLI. Пять исходов вместо «работает/нет».
"""cli_probe.py — доступен ли чужой CLI. Семь исходов вместо «работает/нет».
Зачем. Проверка наличия файла не проверяет возможность работать:
бинарник на месте, но вход не выполнен, или кончилась квота, или каталог только
@@ -8,9 +8,15 @@
--provider ИМЯ --json [--probe-cmd КОМАНДА] [--workdir КАТАЛОГ]
[--timeout СЕК] [--cache ФАЙЛ] [--now ЭПОХА]
--leaf-spawn [--provider ИМЯ] [--workdir КАТАЛОГ]
[--cache ФАЙЛ] [--fingerprint SHA] [--json]
--active-session [--json]
--selftest
Исходы: ok · no_binary · no_auth · no_quota · no_write · timeout.
Исходы транспорта: ok · sandbox · no_binary · no_auth · no_quota · no_write · timeout.
Проба leaf-spawn сводит их к ok · sandbox · unavailable. sandbox означает,
что дочерняя сессия не может работать во вложенной песочнице и нужен
маршрут на другой CLI.
Код возврата: 0 только при ok — вызывающий не обязан разбирать JSON, чтобы понять,
идти ли к этому провайдеру.
@@ -26,10 +32,13 @@ from __future__ import annotations
import argparse
import contextlib
import ctypes
import ctypes.util
import fcntl
import hashlib
import json
import os
import platform
import re
import shutil
import subprocess
@@ -41,6 +50,8 @@ import time
from pathlib import Path
DEFAULT_CACHE = Path(os.path.expanduser("~/.cache/themiz/cli_probe.json"))
DEFAULT_LEAF_CACHE = DEFAULT_CACHE.with_name("cli_leaf_probe.json")
CLI_REGISTRY = Path(__file__).with_name("cli_registry.json")
QUOTA_TTL = 5 * 3600 # квота восстанавливается сама — запрет не может быть вечным
OTKAZ_TTL = 15 * 60 # прочие отказы: чиниться им человеком, но не каждую секунду
CACHE_MAX_TTL = 24 * 3600 # подложенный далекий until не держит провайдера вечно
@@ -52,6 +63,149 @@ NO_AUTH = ("not logged", "logged out", "login required", "unauthorized", "не
'"loggedin": false', "please log in", "authentication required")
NO_QUOTA = ("quota", "usage limit", "rate limit", "too many requests", "limit reached",
"insufficient", "исчерпан")
SANDBOX = ("sandbox_apply", "failed to apply sandbox", "cannot apply sandbox",
"nested sandbox", "could not create path aliases: operation not permitted",
"workspace routing discovery failed")
NESTED_NETWORK = "workspace routing discovery failed"
LEAF_MARKER = ".themiz-leaf-ok"
def diagnose_result(returncode: int, stdout: str = "", stderr: str = "") -> dict:
"""Диагноз уже полученного ответа: не запускает CLI, не читает и не пишет кеш."""
text = f"{stdout}\n{stderr}".lower()
if returncode != 0 and any(marker in text for marker in SANDBOX):
detail = ("у дочерней сессии нет сети во вложенной песочнице"
if NESTED_NETWORK in text else "дочерний CLI не смог применить песочницу")
return {"outcome": "sandbox", "available": False, "route": "cli-router", "detail": detail}
return {"outcome": "unavailable" if returncode else "ok", "detail": ""}
def _darwin_lineage() -> list[dict]:
"""Цепочка живых родителей через системный libproc, без `ps` и env."""
class ProcBsdInfo(ctypes.Structure):
_fields_ = [
("flags", ctypes.c_uint32), ("status", ctypes.c_uint32),
("xstatus", ctypes.c_uint32), ("pid", ctypes.c_uint32),
("ppid", ctypes.c_uint32), ("uid", ctypes.c_uint32),
("gid", ctypes.c_uint32), ("ruid", ctypes.c_uint32),
("rgid", ctypes.c_uint32), ("svuid", ctypes.c_uint32),
("svgid", ctypes.c_uint32), ("rfu_1", ctypes.c_uint32),
("comm", ctypes.c_char * 16), ("name", ctypes.c_char * 32),
("nfiles", ctypes.c_uint32), ("pgid", ctypes.c_uint32),
("pjobc", ctypes.c_uint32), ("tdev", ctypes.c_uint32),
("tpgid", ctypes.c_uint32), ("nice", ctypes.c_int32),
("start_tvsec", ctypes.c_uint64), ("start_tvusec", ctypes.c_uint64),
]
try:
lib = ctypes.CDLL(ctypes.util.find_library("proc") or "/usr/lib/libproc.dylib")
lib.proc_pidinfo.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_uint64,
ctypes.c_void_p, ctypes.c_int]
lib.proc_pidinfo.restype = ctypes.c_int
lib.proc_pidpath.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_uint32]
lib.proc_pidpath.restype = ctypes.c_int
except (OSError, AttributeError):
return []
result, seen, pid = [], set(), os.getpid()
while pid > 1 and pid not in seen and len(result) < 64:
seen.add(pid)
info = ProcBsdInfo()
if lib.proc_pidinfo(pid, 3, 0, ctypes.byref(info), ctypes.sizeof(info)) != ctypes.sizeof(info):
break
path = ctypes.create_string_buffer(4096)
path_size = lib.proc_pidpath(pid, path, len(path))
name = bytes(info.name).split(b"\0", 1)[0].decode(errors="replace")
comm = bytes(info.comm).split(b"\0", 1)[0].decode(errors="replace")
result.append({"pid": pid, "name": name or comm,
"path": path.value.decode(errors="replace") if path_size > 0 else ""})
pid = int(info.ppid)
return result
def _linux_lineage() -> list[dict]:
"""Цепочка живых родителей из procfs; аргументы не читаем, чтобы не цеплять секреты."""
result, seen, pid = [], set(), os.getpid()
while pid > 1 and pid not in seen and len(result) < 64:
seen.add(pid)
root = Path("/proc") / str(pid)
try:
stat = (root / "stat").read_text(encoding="utf-8")
tail = stat[stat.rfind(")") + 2:].split()
ppid = int(tail[1])
name = (root / "comm").read_text(encoding="utf-8").strip()
path = os.readlink(root / "exe")
except (OSError, ValueError, IndexError):
break
result.append({"pid": pid, "name": name, "path": path})
pid = ppid
return result
def _process_lineage() -> list[dict]:
# ponytail: нативные backend только для поддерживаемых домом macOS/Linux;
# добавить нативный backend, когда появится третья целевая ОС.
if platform.system() == "Darwin":
return _darwin_lineage()
if platform.system() == "Linux":
return _linux_lineage()
return []
def _candidate_binaries(registry: Path = CLI_REGISTRY) -> dict[str, str]:
try:
data = json.loads(registry.read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
if not isinstance(data, dict):
return {}
return {
name: entry["invoke"][0]
for name, entry in data.items()
if isinstance(name, str) and isinstance(entry, dict)
and entry.get("enabled") is not False
and isinstance(entry.get("invoke"), list) and entry["invoke"]
and isinstance(entry["invoke"][0], str) and entry["invoke"][0]
}
def _registry_entry(provider: str, registry: Path = CLI_REGISTRY) -> dict | None:
try:
data = json.loads(registry.read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
entry = data.get(provider) if isinstance(data, dict) else None
return entry if isinstance(entry, dict) else None
def _active_from_lineage(lineage: list[dict], candidates: dict[str, str]) -> dict:
def same_cli(live: Path, binary: str) -> bool:
target = Path(shutil.which(binary) or binary).resolve()
# Автообновление посреди сессии (08.10.2026): ссылка уже на новой версии, живой процесс -
# прежний бинарь из того же каталога версий (.../claude/versions/2.1.293 против 2.1.294).
return live.name in {Path(binary).name, target.name} or (
target.parent.name == "versions" and live.parent == target.parent)
for process in lineage:
live = Path(process.get("path", ""))
if not live.name:
continue
matches = [name for name, binary in candidates.items() if same_cli(live, binary)]
if len(matches) == 1:
return {"outcome": "ok", "cli": matches[0], "pid": process.get("pid")}
if len(matches) > 1:
return {"outcome": "unknown", "cli": None,
"detail": "один процесс совпал с несколькими CLI"}
return {"outcome": "unknown", "cli": None,
"detail": "в цепочке живых родителей CLI не найден"}
def active_session(registry: Path = CLI_REGISTRY, lineage: list[dict] | None = None) -> dict:
"""Какой CLI реально ведет текущий шаг; без догадки по env или имени роли."""
candidates = _candidate_binaries(registry)
if not candidates:
return {"outcome": "unknown", "cli": None, "detail": "нет кандидатов из реестра"}
return _active_from_lineage(_process_lineage() if lineage is None else lineage, candidates)
def _cache_read(path: Path) -> dict:
@@ -156,6 +310,8 @@ def probe(provider: str, cmd=None, workdir=None, timeout=30) -> dict:
return {"outcome": "no_binary", "detail": str(e)}
text = ((p.stdout or "") + (p.stderr or "")).lower()
if p.returncode != 0 and any(w in text for w in SANDBOX):
return {"outcome": "sandbox", "detail": text.strip()[:200]}
if any(w in text for w in NO_QUOTA):
return {"outcome": "no_quota", "detail": text.strip()[:200]}
if any(w in text for w in NO_AUTH):
@@ -165,6 +321,112 @@ def probe(provider: str, cmd=None, workdir=None, timeout=30) -> dict:
return {"outcome": "ok", "detail": text.strip().splitlines()[0][:120] if text.strip() else ""}
def _leaf_command(provider: str, command: list[str]) -> list[str]:
"""Grant the shell tool without weakening the process sandbox."""
argv = list(command)
if provider == "claude" and "--allowedTools" not in argv:
# --allowedTools принимает список и съедал промт в хвосте как второе имя инструмента:
# «Input must be provided … when using --print», код 1 (проба вне песочницы 01.10.2026).
# Флаг стоит до -p, и промт после булева -p остается промтом.
argv[1:1] = ["--allowedTools", "Bash"]
# ponytail: Kimi's -p mode natively auto-approves regular tool calls;
# --auto is rejected together with --prompt. Add a flag only if that CLI contract changes.
if provider == "kimi" and not ({"-p", "--prompt"} & set(argv)):
argv.append("-p")
return argv
def _leaf_attempt(argv: list[str], base: Path, timeout: int) -> dict:
if not argv:
return {"outcome": "no_binary", "detail": "нет команды leaf-spawn"}
exe = argv[0]
if not (shutil.which(exe) or os.path.isfile(exe)):
return {"outcome": "no_binary", "detail": f"{exe} не найден"}
if not base.is_dir() or not _writable(base):
return {"outcome": "no_write", "detail": f"{base} недоступен для leaf-spawn"}
with tempfile.TemporaryDirectory(prefix="themiz-leaf-probe-", dir=str(base)) as td:
work = Path(td)
prompt = (
"Use your shell tool once. Run exactly: python3 -c \"from pathlib import Path; "
f"Path('{LEAF_MARKER}').write_text('ok', encoding='utf-8')\". "
"Then reply exactly: THEMIZ_LEAF_OK"
)
try:
process = subprocess.run(argv + [prompt], cwd=str(work), env=_clean_env(),
capture_output=True, text=True, timeout=timeout,
stdin=subprocess.DEVNULL)
except subprocess.TimeoutExpired:
return {"outcome": "timeout", "detail": f"leaf-spawn не ответил за {timeout} с"}
except OSError as exc:
return {"outcome": "no_binary", "detail": str(exc)}
text = ((process.stdout or "") + (process.stderr or "")).lower()
marker = work / LEAF_MARKER
if marker.is_file() and marker.read_text(encoding="utf-8", errors="replace") == "ok":
return {"outcome": "ok", "detail": "leaf-spawn выполнил tool-call"}
if process.returncode != 0 and any(marker in text for marker in SANDBOX):
detail = ("у дочерней сессии нет сети во вложенной песочнице"
if NESTED_NETWORK in text else text.strip()[:200])
return {"outcome": "sandbox", "detail": detail}
if any(marker in text for marker in NO_QUOTA):
return {"outcome": "no_quota", "detail": text.strip()[:200]}
if any(marker in text for marker in NO_AUTH):
return {"outcome": "no_auth", "detail": text.strip()[:200]}
if process.returncode != 0:
return {"outcome": "unavailable",
"detail": f"код {process.returncode}: {text.strip()[:200]}"}
return {"outcome": "unavailable",
"detail": "CLI ответил, но дочерняя сессия не выполнила tool-call"}
def leaf_probe(provider: str, cmd, workdir=None, timeout: int = 60) -> dict:
"""Measure whether one child session can complete a tool call."""
argv = list(cmd) if isinstance(cmd, list) else ([cmd] if cmd else [])
argv = _leaf_command(provider, argv)
base = Path(workdir) if workdir else Path(tempfile.gettempdir())
first = _leaf_attempt(argv, base, timeout)
if first["outcome"] == "ok":
return {**first, "provider": provider, "available": True, "route": "native"}
if first["outcome"] == "sandbox":
return {**first, "provider": provider, "available": False,
"route": "cli-router"}
return {"outcome": "unavailable", "provider": provider, "available": False,
"route": "cli-router", "cause": first["outcome"],
"detail": first.get("detail", "CLI недоступен")}
def leaf_check(provider: str, workdir=None, timeout: int = 60,
cache: Path = DEFAULT_LEAF_CACHE, now: float | None = None,
registry: Path = CLI_REGISTRY, fingerprint: str = "",
measure: bool = True) -> dict:
entry = _registry_entry(provider, registry)
command = entry.get("invoke") if entry else None
if not isinstance(command, list) or not command or not all(isinstance(x, str) for x in command):
return {"outcome": "unavailable", "provider": provider, "available": False,
"route": "cli-router", "detail": "в реестре нет команды invoke"}
now = time.time() if now is None else float(now)
# хэш от команды листа, а не от реестра: правка флагов листа сбрасывает старые квитанции
probe_hash = _probe_hash(_leaf_command(provider, command) + [fingerprint])
key = f"leaf:{provider}"
cached = _cache_read(cache).get(key)
if (isinstance(cached, dict) and cached.get("probe_hash") == probe_hash
and cached.get("outcome") in {"ok", "sandbox", "unavailable"}
and isinstance(cached.get("available"), bool)):
return {**cached, "cached": True}
if not measure:
return {"outcome": "unavailable", "provider": provider, "available": False,
"route": "leaf-probe-required", "cause": "not_measured",
"probe_hash": probe_hash, "cached": False,
"detail": "нет leaf-spawn квитанции для SHA входов"}
result = leaf_probe(provider, command, workdir, timeout)
result.update({"checked": int(now), "probe_hash": probe_hash, "cached": False})
with _cache_lock(cache):
data = _cache_read(cache)
data[key] = {k: v for k, v in result.items() if k != "cached"}
_cache_write(cache, data)
return result
def check(provider: str, cmd=None, workdir=None, timeout=30,
cache: Path = DEFAULT_CACHE, now: float | None = None) -> dict:
now = time.time() if now is None else float(now)
@@ -228,6 +490,22 @@ def selftest() -> int:
assert check("t4", ok, str(ro), cache=cache)["outcome"] == "no_write"
assert check("t5", sh("s.sh", "sleep 5\n"), str(work), timeout=1,
cache=cache)["outcome"] == "timeout"
sandbox = sh("sandbox.sh", 'echo "sandbox-exec: sandbox_apply: Operation not permitted" >&2\nexit 1\n')
assert check("t6", sandbox, str(work), cache=cache)["outcome"] == "sandbox"
warned = sh("warned.sh", 'echo "could not create path aliases: operation not permitted" >&2\n')
assert check("t7", warned, str(work), cache=cache)["outcome"] == "ok"
leaf_ok = sh("leaf-ok.sh", f"printf ok > {LEAF_MARKER}\n")
assert leaf_probe("ok", [leaf_ok], str(work))["outcome"] == "ok"
leaf_sandbox = sh(
"leaf-sandbox.sh",
'echo "workspace routing discovery failed" >&2; exit 1\n')
routed = leaf_probe("codex", [leaf_sandbox, "--sandbox", "read-only"], str(work))
assert routed["outcome"] == "sandbox" and not routed["available"] \
and routed["route"] == "cli-router", routed
unavailable = leaf_probe(
"offline", [sh("offline.sh", 'echo "not logged in" >&2\nexit 1\n')], str(work))
assert unavailable["outcome"] == "unavailable" and not unavailable["available"]
# Кеш: отказ помнится, после срока — проба заново, оживший провайдер чистит запись.
povtor = check("t3", ok, str(work), cache=cache)
@@ -253,12 +531,23 @@ def selftest() -> int:
assert ("ANTHROPIC_API_KEY" not in leaked and sreda.NOVYJ not in leaked
and sreda.PREZHNIJ not in leaked), \
"проба наследует секреты окружения"
print("selftest пройден: пять исходов различены, отказ по квоте протухает за 5 ч")
candidates = _candidate_binaries()
assert len(candidates) >= 3, "реестр не описывает три активных CLI"
for name, binary in candidates.items():
live_path = str(Path(shutil.which(binary) or f"/bin/{Path(binary).name}").resolve())
found = _active_from_lineage(
[{"pid": 7, "name": "ignored", "path": live_path}],
candidates)
assert found["cli"] == name, f"живой процесс {name} не различен"
assert _active_from_lineage(
[{"pid": 7, "name": "python", "path": "/usr/bin/python"}], candidates
)["outcome"] == "unknown", "неизвестный процесс угадан как CLI"
print("selftest пройден: транспорт, leaf-spawn и живой CLI различены")
return 0
def main() -> int:
ap = argparse.ArgumentParser(description="Доступность чужого CLI: пять исходов.")
ap = argparse.ArgumentParser(description="Доступность CLI и права дочерней сессии.")
ap.add_argument("--provider", help="имя записи реестра")
ap.add_argument("--probe-cmd", help="JSON-массив команды проверки из реестра")
ap.add_argument("--workdir", help="каталог, в котором будет работать чужой CLI")
@@ -266,12 +555,52 @@ def main() -> int:
ap.add_argument("--cache", default=str(DEFAULT_CACHE))
ap.add_argument("--now", type=float, help="подстановка времени (приемка протухания)")
ap.add_argument("--json", action="store_true")
ap.add_argument("--active-session", action="store_true",
help="определить CLI текущей сессии по цепочке процессов")
ap.add_argument("--diagnose-result", action="store_true",
help="локально разобрать полученный ответ из JSON stdin, без вызова CLI")
ap.add_argument("--leaf-spawn", action="store_true",
help="проверить tool-call дочерней сессии текущего CLI")
ap.add_argument("--fingerprint", default="",
help="SHA входов, для которых действует leaf-spawn")
ap.add_argument("--selftest", action="store_true")
a = ap.parse_args()
if a.selftest:
return selftest()
if a.diagnose_result:
try:
received = json.load(sys.stdin)
if (not isinstance(received, dict) or type(received.get("returncode")) is not int
or not all(isinstance(received.get(key, ""), str) for key in ("stdout", "stderr"))):
raise ValueError("нужны returncode=int, stdout=str и stderr=str")
except (ValueError, TypeError) as error:
ap.error(f"--diagnose-result: {error}")
result = diagnose_result(received["returncode"], received.get("stdout", ""), received.get("stderr", ""))
print(json.dumps(result, ensure_ascii=False) if a.json else result["detail"] or result["outcome"])
return 0
if a.active_session:
r = active_session()
print(json.dumps(r, ensure_ascii=False) if a.json
else (r["cli"] or "неизвестно"))
return 0 if r["outcome"] == "ok" else 1
if a.leaf_spawn:
provider = a.provider
if not provider:
active = active_session()
provider = active.get("cli") if active.get("outcome") == "ok" else None
if not provider:
r = {"outcome": "unavailable", "available": False, "route": "active-session",
"detail": "CLI текущей сессии не определен"}
else:
cache = Path(a.cache) if a.cache != str(DEFAULT_CACHE) else DEFAULT_LEAF_CACHE
r = leaf_check(provider, a.workdir, a.timeout, cache, a.now,
fingerprint=a.fingerprint, measure=True)
print(json.dumps(r, ensure_ascii=False) if a.json else
f"{provider or 'неизвестно'}: {r['outcome']} — {r.get('detail', '')}; "
f"маршрут: {r.get('route', '-')}")
return 0 if r.get("available") else 1
if not a.provider:
ap.error("нужен --provider либо --selftest")
ap.error("нужен --provider, --active-session либо --selftest")
try:
command = json.loads(a.probe_cmd) if a.probe_cmd and a.probe_cmd.lstrip().startswith("[") else a.probe_cmd
except ValueError: