#!/usr/bin/env python3 """cli_probe.py — доступен ли чужой CLI. Семь исходов вместо «работает/нет». Зачем. Проверка наличия файла не проверяет возможность работать: бинарник на месте, но вход не выполнен, или кончилась квота, или каталог только на чтение, или инструмент висит. Все четыре случая выглядят как «не сработало» и лечатся по-разному, поэтому исход называется своим именем. --provider ИМЯ --json [--probe-cmd КОМАНДА] [--workdir КАТАЛОГ] [--timeout СЕК] [--cache ФАЙЛ] [--now ЭПОХА] --leaf-spawn [--provider ИМЯ] [--workdir КАТАЛОГ] [--cache ФАЙЛ] [--fingerprint SHA] [--json] --active-session [--json] --selftest Исходы транспорта: ok · sandbox · no_binary · no_auth · no_quota · no_write · timeout. Проба leaf-spawn сводит их к ok · sandbox · unavailable. sandbox означает, что дочерняя сессия не может работать во вложенной песочнице и нужен маршрут на другой CLI. Код возврата: 0 только при ok — вызывающий не обязан разбирать JSON, чтобы понять, идти ли к этому провайдеру. Кеш. Отказ повторяется при каждом вызове, и без памяти проба долбится в закрытую дверь на каждом листе роя. Отказ по квоте БЕЗ названной даты сброса протухает через пять часов: квота восстанавливается сама, и вечная запись «нет квоты» отрезает провайдера навсегда. `--now` существует ради приемки: срок протухания проверяется подстановкой времени, а не ожиданием пяти часов. """ 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 import sys import sreda # noqa: E402,F401 переходный период имен переменных import tempfile 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 не держит провайдера вечно KEEP_ENV = ("HOME", "USER", "LOGNAME", "LANG", "LC_ALL", "TERM", "LC_CTYPE", "TMPDIR", "LC_TIME") SAFE_PATH = "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" SECRET_RE = re.compile(r"THEMIZ|TOKEN|SECRET|API_?KEY|PASSWORD|CREDENTIAL|ANTHROPIC|OPENAI", re.I) 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 [] # Десктопные приложения-харнессы: провайдер -> пути бандлов. Сессия Kimi Work идет # из приложения, а не из терминального CLI, и живой процесс в цепочке — это бандл. _DESKTOP_BUNDLES: dict[str, tuple[str, ...]] = {"kimi": ("/Applications/Kimi.app/",)} 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 not matches: # Десктопное приложение ведет сессию само: в цепочке живых родителей нет # бинаря CLI из PATH, есть процесс приложения (Kimi Work, 04-05.11.2026: # активная сессия не определялась, ПД-роли вставали без исполнителя). # Тождество — по полному пути бандла, который сообщила ОС, не по имени. matches = [name for name, bundles in _DESKTOP_BUNDLES.items() if name in candidates and any(str(live).startswith(bundle) for bundle in bundles)] 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: try: data = json.loads(path.read_text(encoding="utf-8")) except (OSError, ValueError): return {} # Кеш — ускорение, а не условие работы: посторонний файл верного JSON, но чужой # формы (список вместо словаря) не должен ронять пробу исключением `.get` и # останавливать весь ПД-конвейер. Не словарь — считаем «кеша нет». return data if isinstance(data, dict) else {} def _cache_write(path: Path, data: dict) -> None: try: path.parent.mkdir(parents=True, exist_ok=True) # Атомарная замена: параллельный читатель видит целый файл, не полузапись. tmp = path.with_name(f"{path.name}.tmp.{os.getpid()}") tmp.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8") os.replace(tmp, path) except OSError: pass # кеш — ускорение, а не условие работы @contextlib.contextmanager def _cache_lock(path: Path): """Межпроцессный замок на чтение-правку-запись кеша. Волна ролей идет параллельно ПО ЗАМЫСЛУ: без замка двенадцать одновременных проб делают read-modify-write наперегонки и затирают работу друг друга (хвост круга 5 — три записи из двенадцати). flock на соседнем .lock-файле сериализует только короткую правку кеша, сама проба чужого CLI идет вне замка.""" try: path.parent.mkdir(parents=True, exist_ok=True) f = open(path.with_name(f"{path.name}.lock"), "w") except OSError: yield # замок не построить — кеш не условие работы return try: fcntl.flock(f.fileno(), fcntl.LOCK_EX) yield finally: try: fcntl.flock(f.fileno(), fcntl.LOCK_UN) finally: f.close() def _clean_env() -> dict: env = {k: v for k, v in os.environ.items() if k in KEEP_ENV and not SECRET_RE.search(k)} env["PATH"] = SAFE_PATH + ":" + os.environ.get("PATH", "") env["PATH"] = ":".join(dict.fromkeys(env["PATH"].split(":"))) return env def _probe_hash(cmd) -> str: if isinstance(cmd, list): payload = cmd elif cmd is None: payload = [] else: payload = [str(cmd)] raw = json.dumps(payload, ensure_ascii=False, separators=(",", ":")) return hashlib.sha256(raw.encode("utf-8")).hexdigest() def _writable(d: Path) -> bool: """Может ли чужой CLI вообще работать в этом каталоге.""" try: with tempfile.NamedTemporaryFile(dir=str(d), prefix=".proba-", delete=True): return True except (OSError, PermissionError): return False def probe(provider: str, cmd=None, workdir=None, timeout=30) -> dict: argv = cmd if isinstance(argv, str): argv = [argv] if not argv: return {"outcome": "no_binary", "detail": "нет команды пробы из реестра"} exe = argv[0] if not (shutil.which(exe) or os.path.isfile(exe)): return {"outcome": "no_binary", "detail": f"{exe} не найден"} base = Path(workdir) if workdir else Path(tempfile.gettempdir()) if not base.is_dir(): return {"outcome": "no_write", "detail": f"каталога {base} нет"} if not _writable(base): return {"outcome": "no_write", "detail": f"{base} недоступен для записи — " "чужому CLI негде работать"} with tempfile.TemporaryDirectory(prefix="themiz-cli-probe-", dir=str(base)) as td: work = Path(td) / "work" work.mkdir() try: p = subprocess.run(argv, cwd=str(work), env=_clean_env(), capture_output=True, text=True, timeout=timeout, stdin=subprocess.DEVNULL) except subprocess.TimeoutExpired: return {"outcome": "timeout", "detail": f"не ответил за {timeout} с"} except OSError as e: 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): return {"outcome": "no_auth", "detail": text.strip()[:200]} if p.returncode != 0: return {"outcome": "no_auth", "detail": f"код {p.returncode}: {text.strip()[:200]}"} 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) probe_hash = _probe_hash(cmd) zapisi = _cache_read(cache) zapis = zapisi.get(provider) until = float(zapis.get("until", 0)) if isinstance(zapis, dict) else 0 if (isinstance(zapis, dict) and zapis.get("outcome") != "ok" and until > now and until <= now + CACHE_MAX_TTL and (zapis.get("probe_hash") in (None, probe_hash) or zapis.get("outcome") == "no_quota")): return {**zapis, "provider": provider, "cached": True} if isinstance(zapis, dict) and (zapis.get("outcome") == "ok" or until > now + CACHE_MAX_TTL): zapisi.pop(provider, None) r = probe(provider, cmd, workdir, timeout) r["provider"] = provider r["cached"] = False r["checked"] = int(now) r["probe_hash"] = probe_hash # Правка кеша — под замком и по СВЕЖЕМУ снимку: параллельные пробы иных # провайдеров не затираются, каждая дописывает только свою запись. with _cache_lock(cache): zapisi = _cache_read(cache) if r["outcome"] != "ok": ttl = QUOTA_TTL if r["outcome"] == "no_quota" else OTKAZ_TTL r["until"] = int(min(now + ttl, now + CACHE_MAX_TTL)) zapisi[provider] = {k: v for k, v in r.items() if k != "cached"} _cache_write(cache, zapisi) elif provider in zapisi: zapisi.pop(provider) # ожил — запрет снимается сразу _cache_write(cache, zapisi) return r def selftest() -> int: import stat as _stat with tempfile.TemporaryDirectory() as td: td = Path(td) cache = td / "c.json" work = td / "w" work.mkdir() def sh(name, body): p = td / name p.write_text("#!/bin/bash\n" + body, encoding="utf-8") p.chmod(p.stat().st_mode | _stat.S_IXUSR) return str(p) ok = sh("ok.sh", 'echo "Logged in"; exit 0\n') assert check("t", ok, str(work), cache=cache)["outcome"] == "ok" assert check("t", str(td / "netu.sh"), str(work), cache=cache)["outcome"] == "no_binary" assert check("t2", sh("a.sh", 'echo "not logged in"; exit 1\n'), str(work), cache=cache)["outcome"] == "no_auth" q = check("t3", sh("q.sh", 'echo "usage limit reached"; exit 1\n'), str(work), cache=cache) assert q["outcome"] == "no_quota", q assert q["until"] - q["checked"] == QUOTA_TTL, "срок протухания квоты не пять часов" ro = td / "ro" ro.mkdir() ro.chmod(0o500) 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) assert povtor["cached"], "отказ не закеширован — рой будет долбиться в закрытую дверь" posle = check("t3", ok, str(work), cache=cache, now=q["until"] + 1) assert not posle["cached"] and posle["outcome"] == "ok", "после срока квота не проверена заново" assert "t3" not in _cache_read(cache), "ожившего провайдера не выпустили из кеша" poison = cache _cache_write(poison, {"ghost": {"outcome": "ok", "until": 9999999999}}) assert check("ghost", str(td / "netu.sh"), str(work), cache=poison)["outcome"] == "no_binary", \ "поддельный ok из кеша принят без пробы" # Посторонний файл верного JSON, но чужой формы (список) — не условие работы: # проба идет, а не падает `.get`-исключением. chuzhoy = td / "chuzhoy.json" chuzhoy.write_text(json.dumps(["посторонний", "но валидный json"]), encoding="utf-8") assert check("t", ok, str(work), cache=chuzhoy)["outcome"] == "ok", \ "чужая форма кеша уронила пробу" envdump = td / "env.txt" spy = sh("spy.sh", f"env > {envdump}\n") assert check("spy", spy, str(work), cache=cache, now=q["until"] + 2)["outcome"] == "ok" leaked = envdump.read_text(encoding="utf-8", errors="ignore") assert ("ANTHROPIC_API_KEY" not in leaked and sreda.NOVYJ not in leaked and sreda.PREZHNIJ not in leaked), \ "проба наследует секреты окружения" 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.add_argument("--provider", help="имя записи реестра") ap.add_argument("--probe-cmd", help="JSON-массив команды проверки из реестра") ap.add_argument("--workdir", help="каталог, в котором будет работать чужой CLI") ap.add_argument("--timeout", type=int, default=30) 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, --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: ap.error("--probe-cmd: поврежден JSON-массив") r = check(a.provider, command, a.workdir, a.timeout, Path(a.cache), a.now) if a.json: print(json.dumps(r, ensure_ascii=False)) else: print(f"{r['provider']}: {r['outcome']}" + (f" — {r['detail']}" if r.get("detail") else "") + (" (из кеша)" if r.get("cached") else "")) return 0 if r["outcome"] == "ok" else 1 if __name__ == "__main__": sys.exit(main())