main
py 97 lines 3.26 KB
Raw
1 from __future__ import annotations
2
3 import json
4 import os
5 from pathlib import Path
6 from typing import Any
7
8 from plugins._orchestrator.helpers.adapters.base import TerminalAgentAdapter
9
10
11 _SECRET_KEYS = {"access_token", "api_key", "id_token", "refresh_token", "token"}
12
13
14 class GrokBuildAdapter(TerminalAgentAdapter):
15 id = "grok"
16 title = "Grok Build"
17 binary = "grok"
18 install_hint = "curl -fsSL https://x.ai/cli/install.sh | bash"
19 description = "xAI Grok Build CLI in headless single-prompt mode."
20
21 def _home(self) -> Path:
22 configured = os.environ.get("GROK_HOME", "").strip()
23 return Path(configured).expanduser() if configured else Path.home() / ".grok"
24
25 def auth_status(self, config: dict[str, Any] | None = None) -> dict[str, Any]:
26 env_var = next(
27 (name for name in ("XAI_API_KEY", "API_KEY_XAI") if os.environ.get(name)),
28 "",
29 )
30 if env_var:
31 return {"connected": True, "mode": "env", "auth_path": env_var}
32
33 home = self._home()
34 for path in (home / "config.toml", home / "auth.json"):
35 try:
36 if _file_has_secret(path):
37 return {"connected": True, "mode": "external", "auth_path": str(path)}
38 except OSError as exc:
39 return {"connected": False, "mode": "", "auth_path": "", "error": str(exc)}
40
41 auth_dir = home / "auth"
42 try:
43 if auth_dir.is_dir():
44 for path in auth_dir.iterdir():
45 if path.is_file() and _file_has_secret(path):
46 return {
47 "connected": True,
48 "mode": "external",
49 "auth_path": str(auth_dir),
50 }
51 except OSError as exc:
52 return {"connected": False, "mode": "", "auth_path": "", "error": str(exc)}
53
54 return {"connected": False, "mode": "", "auth_path": str(home)}
55
56
57 def _file_has_secret(path: Path) -> bool:
58 if not path.is_file() or path.stat().st_size <= 0:
59 return False
60 text = path.read_text(encoding="utf-8", errors="ignore")
61 if path.suffix == ".toml":
62 return _toml_has_secret(text)
63 try:
64 return _contains_secret(json.loads(text))
65 except ValueError:
66 return _text_has_secret(text)
67
68
69 def _toml_has_secret(text: str) -> bool:
70 for line in text.splitlines():
71 raw = line.strip()
72 if not raw or raw.startswith("#") or "=" not in raw:
73 continue
74 key, value = raw.split("=", 1)
75 key = key.strip()
76 value = value.strip().strip("'\"")
77 if key == "api_key" and value:
78 return True
79 if key == "env_key" and value and os.environ.get(value):
80 return True
81 return False
82
83
84 def _text_has_secret(text: str) -> bool:
85 return any(f'"{key}"' in text or f"{key} =" in text for key in _SECRET_KEYS)
86
87
88 def _contains_secret(value: Any) -> bool:
89 if isinstance(value, dict):
90 for key, item in value.items():
91 if str(key) in _SECRET_KEYS and isinstance(item, str) and item.strip():
92 return True
93 if _contains_secret(item):
94 return True
95 if isinstance(value, list):
96 return any(_contains_secret(item) for item in value)
97 return False