|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import argparse |
| 3 | +import json |
| 4 | +import os |
| 5 | +import sys |
| 6 | +import time |
| 7 | +import urllib.error |
| 8 | +import urllib.request |
| 9 | +from pathlib import Path |
| 10 | + |
| 11 | + |
| 12 | +API_URL = "https://spawn-dock.w3voice.net/knowledge/api/v1/search" |
| 13 | + |
| 14 | + |
| 15 | +def parse_args() -> argparse.Namespace: |
| 16 | + parser = argparse.ArgumentParser( |
| 17 | + description="Query the SpawnDock TMA knowledge API." |
| 18 | + ) |
| 19 | + parser.add_argument("query", help="Knowledge search query") |
| 20 | + parser.add_argument("--locale", default="en", help="Response locale (default: en)") |
| 21 | + parser.add_argument( |
| 22 | + "--api-token", |
| 23 | + help="Optional Bearer token override. Defaults to SPAWNDOCK_API_TOKEN/API_TOKEN or spawndock.config.json", |
| 24 | + ) |
| 25 | + parser.add_argument( |
| 26 | + "--config", |
| 27 | + help="Optional path to spawndock.config.json. Defaults to the nearest config found from cwd upward.", |
| 28 | + ) |
| 29 | + parser.add_argument( |
| 30 | + "--timeout", |
| 31 | + type=float, |
| 32 | + default=20.0, |
| 33 | + help="HTTP timeout in seconds (default: 20)", |
| 34 | + ) |
| 35 | + parser.add_argument( |
| 36 | + "--raw", |
| 37 | + action="store_true", |
| 38 | + help="Print raw JSON response instead of a formatted summary", |
| 39 | + ) |
| 40 | + parser.add_argument( |
| 41 | + "--retries", |
| 42 | + type=int, |
| 43 | + default=2, |
| 44 | + help="Retry count for transient HTTP 5xx failures (default: 2)", |
| 45 | + ) |
| 46 | + return parser.parse_args() |
| 47 | + |
| 48 | + |
| 49 | +def find_config_path(explicit_path: str | None) -> Path | None: |
| 50 | + if explicit_path: |
| 51 | + path = Path(explicit_path).expanduser() |
| 52 | + return path if path.is_file() else None |
| 53 | + |
| 54 | + for base in [Path.cwd(), *Path.cwd().parents]: |
| 55 | + candidate = base / "spawndock.config.json" |
| 56 | + if candidate.is_file(): |
| 57 | + return candidate |
| 58 | + |
| 59 | + return None |
| 60 | + |
| 61 | + |
| 62 | +def read_config_api_token(config_path: Path | None) -> str | None: |
| 63 | + if config_path is None: |
| 64 | + return None |
| 65 | + |
| 66 | + try: |
| 67 | + data = json.loads(config_path.read_text(encoding="utf-8")) |
| 68 | + except (OSError, json.JSONDecodeError): |
| 69 | + return None |
| 70 | + |
| 71 | + token = data.get("apiToken") |
| 72 | + return token.strip() if isinstance(token, str) and token.strip() else None |
| 73 | + |
| 74 | + |
| 75 | +def resolve_api_token(cli_token: str | None, config_path: Path | None) -> str | None: |
| 76 | + if cli_token and cli_token.strip(): |
| 77 | + return cli_token.strip() |
| 78 | + |
| 79 | + for key in ("SPAWNDOCK_API_TOKEN", "API_TOKEN"): |
| 80 | + value = os.environ.get(key, "").strip() |
| 81 | + if value: |
| 82 | + return value |
| 83 | + |
| 84 | + return read_config_api_token(config_path) |
| 85 | + |
| 86 | + |
| 87 | +def request_knowledge( |
| 88 | + query: str, |
| 89 | + locale: str, |
| 90 | + timeout: float, |
| 91 | + retries: int, |
| 92 | + api_token: str | None, |
| 93 | +) -> dict: |
| 94 | + payload = json.dumps({"query": query, "locale": locale}).encode("utf-8") |
| 95 | + for attempt in range(retries + 1): |
| 96 | + headers = { |
| 97 | + "accept": "application/json", |
| 98 | + "content-type": "application/json", |
| 99 | + } |
| 100 | + if api_token: |
| 101 | + headers["authorization"] = f"Bearer {api_token}" |
| 102 | + |
| 103 | + req = urllib.request.Request( |
| 104 | + API_URL, |
| 105 | + data=payload, |
| 106 | + headers=headers, |
| 107 | + method="POST", |
| 108 | + ) |
| 109 | + try: |
| 110 | + with urllib.request.urlopen(req, timeout=timeout) as response: |
| 111 | + charset = response.headers.get_content_charset() or "utf-8" |
| 112 | + return json.loads(response.read().decode(charset)) |
| 113 | + except urllib.error.HTTPError as exc: |
| 114 | + if exc.code < 500 or attempt == retries: |
| 115 | + raise |
| 116 | + time.sleep(min(2**attempt, 5)) |
| 117 | + |
| 118 | + raise RuntimeError("Unreachable retry loop") |
| 119 | + |
| 120 | + |
| 121 | +def format_response(data: dict) -> str: |
| 122 | + lines: list[str] = [] |
| 123 | + answer = data.get("answer") |
| 124 | + sources = data.get("sources") or [] |
| 125 | + meta = data.get("meta") or {} |
| 126 | + |
| 127 | + lines.append("Answer:") |
| 128 | + lines.append(answer if answer else "(empty)") |
| 129 | + |
| 130 | + if sources: |
| 131 | + lines.append("") |
| 132 | + lines.append("Sources:") |
| 133 | + for idx, source in enumerate(sources, start=1): |
| 134 | + if isinstance(source, dict): |
| 135 | + title = source.get("title") or source.get("name") or f"Source {idx}" |
| 136 | + url = source.get("url") or source.get("href") or "" |
| 137 | + snippet = source.get("snippet") or source.get("text") or "" |
| 138 | + line = f"{idx}. {title}" |
| 139 | + if url: |
| 140 | + line += f" - {url}" |
| 141 | + lines.append(line) |
| 142 | + if snippet: |
| 143 | + lines.append(f" {snippet}") |
| 144 | + else: |
| 145 | + lines.append(f"{idx}. {source}") |
| 146 | + |
| 147 | + if meta: |
| 148 | + lines.append("") |
| 149 | + lines.append("Meta:") |
| 150 | + lines.append(json.dumps(meta, ensure_ascii=False, sort_keys=True)) |
| 151 | + |
| 152 | + return "\n".join(lines) |
| 153 | + |
| 154 | + |
| 155 | +def main() -> int: |
| 156 | + args = parse_args() |
| 157 | + config_path = find_config_path(args.config) |
| 158 | + api_token = resolve_api_token(args.api_token, config_path) |
| 159 | + try: |
| 160 | + data = request_knowledge( |
| 161 | + args.query, |
| 162 | + args.locale, |
| 163 | + args.timeout, |
| 164 | + args.retries, |
| 165 | + api_token, |
| 166 | + ) |
| 167 | + except urllib.error.HTTPError as exc: |
| 168 | + body = exc.read().decode("utf-8", errors="replace") |
| 169 | + print(f"HTTP error: {exc.code}\n{body}", file=sys.stderr) |
| 170 | + return 1 |
| 171 | + except urllib.error.URLError as exc: |
| 172 | + print(f"Request failed: {exc}", file=sys.stderr) |
| 173 | + return 1 |
| 174 | + |
| 175 | + if args.raw: |
| 176 | + print(json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True)) |
| 177 | + else: |
| 178 | + print(format_response(data)) |
| 179 | + return 0 |
| 180 | + |
| 181 | + |
| 182 | +if __name__ == "__main__": |
| 183 | + raise SystemExit(main()) |
0 commit comments