recovered from aaronjaworski710
CI / offline-tests (push) Has been cancelled
CI / web-unit-tests (push) Has been cancelled
CI / package-console10 (push) Has been cancelled

This commit is contained in:
reform
2026-10-23 20:02:14 +03:00
commit 8044e88be4
409 changed files with 104886 additions and 0 deletions
+212
View File
@@ -0,0 +1,212 @@
#!/usr/bin/env bash
# Isolated A/B for browser_fingerprint_mode=off vs light (tier A).
#
# Does NOT touch production batch supervisor. Uses its own flock and only
# starts register_cli when /tmp/grok_register_cli.lock is free (no --no-cli-lock)
# so we never dual-Chromium with batch_dc1k_ns.
#
# Usage (on pxed under /data/grok-register):
# bash scripts/ab_fingerprint_light.sh
# AB_N=2 SMOKE_TIMEOUT=900 bash scripts/ab_fingerprint_light.sh
# AB_ARMS="off light" bash scripts/ab_fingerprint_light.sh
#
# Env freeze (disk-first):
# CPA_EXPORT_ENABLED=true CPA_PROBE_CHAT=false CPA_REMOTE_INJECT=false
# Default fingerprint remains off for production launchers; this script only
# passes --browser-fingerprint-mode per arm.
set -uo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT" || exit 1
if [[ -d /data/grok-register && -f /data/grok-register/register_cli.py ]]; then
if [[ "$ROOT" != /data/grok-register && "$ROOT" != /personal/grok-register ]]; then
# Prefer runtime when script was copied from monorepo checkout.
if [[ -f /data/grok-register/scripts/ab_fingerprint_light.sh ]]; then
:
fi
fi
fi
AB_LOCK=/tmp/grok_ab_fingerprint.lock
exec 8>"$AB_LOCK"
if ! flock -n 8; then
echo "another ab_fingerprint holds $AB_LOCK; exit 1"
exit 1
fi
echo $$ > "${AB_LOCK}.pid"
CLI_LOCK=/tmp/grok_register_cli.lock
SMOKE_TIMEOUT=${SMOKE_TIMEOUT:-900}
AB_N=${AB_N:-1} # attempts per arm
AB_ARMS=${AB_ARMS:-"off light"}
AB_WAIT_CLI_SEC=${AB_WAIT_CLI_SEC:-120} # wait for production CLI lock to free
TS=$(date +%Y%m%d_%H%M%S)
mkdir -p logs
SUMMARY="logs/ab_fingerprint_${TS}.summary.jsonl"
LOG="logs/ab_fingerprint_${TS}.log"
export AB_SUMMARY_PATH="$SUMMARY"
export AB_LOG_PATH="$LOG"
# Line-safe .env load
if [[ -f .env ]]; then
while IFS= read -r line || [ -n "$line" ]; do
case "$line" in ""|\#*) continue ;; esac
key=${line%%=*}
val=${line#*=}
case "$key" in
EMAIL_PROVIDER|EMAIL_PROVIDERS|EMAIL_PROVIDER_STRATEGY|MAIL_TIMEOUT|PLAYWRIGHT_BROWSERS_PATH|PROXY|CPA_PROXY|GROK_NODE|DISPLAY)
export "$key=$val"
;;
esac
done < .env
fi
if [[ -f .venv/bin/activate ]]; then
# shellcheck source=/dev/null
source .venv/bin/activate
fi
export EMAIL_PROVIDER=${SMOKE_EMAIL_PROVIDER:-cloudflare}
unset EMAIL_PROVIDERS || true
export MAIL_TIMEOUT=${MAIL_TIMEOUT:-20}
export CPA_EXPORT_ENABLED=true
export CPA_PROBE_CHAT=false
export CPA_REMOTE_INJECT=false
export CPA_PREFER_PROTOCOL=${CPA_PREFER_PROTOCOL:-false}
export PROXY=${PROXY:-http://127.0.0.1:7897}
export CPA_PROXY=${CPA_PROXY:-$PROXY}
export PLAYWRIGHT_BROWSERS_PATH=${PLAYWRIGHT_BROWSERS_PATH:-/personal/browsers/ms-playwright}
export SKIP_CLASH_PREFLIGHT=${SKIP_CLASH_PREFLIGHT:-1}
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY all_proxy || true
export NO_PROXY=127.0.0.1,localhost
export no_proxy=127.0.0.1,localhost
PY=${ROOT}/.venv/bin/python
if [[ ! -x "$PY" ]]; then
PY=python3
fi
baseline_complete() {
"$PY" - <<'PY'
import json
from pathlib import Path
need = ["access_token", "refresh_token", "email", "base_url", "token_endpoint", "headers"]
xs = list(Path("cpa_auths").glob("xai-*.json")) if Path("cpa_auths").exists() else []
complete = 0
for f in xs:
try:
j = json.loads(f.read_text())
except Exception:
continue
if all((j.get(k) or "") for k in need):
complete += 1
print(complete)
PY
}
wait_cli_lock_free() {
local waited=0
while ! flock -n 9 2>/dev/null; do
if (( waited >= AB_WAIT_CLI_SEC )); then
echo "[ab] CLI lock still held after ${AB_WAIT_CLI_SEC}s; refuse dual Chromium; exit 2"
return 2
fi
echo "[ab] waiting for $CLI_LOCK free (${waited}/${AB_WAIT_CLI_SEC}s)..."
sleep 5
waited=$((waited + 5))
done
# We only probed; release immediately so register_cli can take it.
flock -u 9 2>/dev/null || true
return 0
}
# Open CLI lock fd for probing (non-blocking try)
exec 9>"$CLI_LOCK"
{
echo "=== ab_fingerprint start $(date -u +%Y-%m-%dT%H:%M:%SZ) ==="
echo "root=$ROOT arms=$AB_ARMS n=$AB_N timeout=$SMOKE_TIMEOUT"
echo "EMAIL_PROVIDER=$EMAIL_PROVIDER PROXY=$PROXY SKIP_CLASH_PREFLIGHT=$SKIP_CLASH_PREFLIGHT"
echo "summary=$SUMMARY"
overall_base=$(baseline_complete)
echo "overall_baseline_complete=$overall_base"
for arm in $AB_ARMS; do
arm=$(echo "$arm" | tr -d '[:space:]')
[[ -z "$arm" ]] && continue
if [[ "$arm" != "off" && "$arm" != "light" ]]; then
echo "[ab] skip unknown arm=$arm"
continue
fi
for i in $(seq 1 "$AB_N"); do
echo "--- arm=$arm attempt=$i/$(echo $AB_N) $(date -u +%Y-%m-%dT%H:%M:%SZ) ---"
if ! wait_cli_lock_free; then
echo "{\"arm\":\"$arm\",\"attempt\":$i,\"status\":\"cli_lock_busy\",\"product_ok\":0}" >> "$SUMMARY"
echo "[ab] abort remaining arms due to CLI lock" | tee -a "$LOG"
exit 2
fi
base=$(baseline_complete)
echo "baseline_complete=$base arm=$arm"
set +e
if command -v xvfb-run >/dev/null 2>&1 && [[ -z "${DISPLAY:-}" || "${FORCE_XVFB:-0}" == "1" ]]; then
timeout "$SMOKE_TIMEOUT" xvfb-run -a -s "-screen 0 1280x900x24 -ac +extension GLX +render -noreset -nolisten tcp" \
"$PY" -u register_cli.py --extra 1 --threads 1 --no-headless --fast \
--browser-fingerprint-mode "$arm"
code=$?
else
timeout "$SMOKE_TIMEOUT" \
"$PY" -u register_cli.py --extra 1 --threads 1 --no-headless --fast \
--browser-fingerprint-mode "$arm"
code=$?
fi
set -e
now=$(baseline_complete)
delta=$((now - base))
product_ok=0
if (( delta > 0 )); then product_ok=1; fi
echo "arm=$arm attempt=$i exit=$code delta=$delta product_ok=$product_ok"
echo "{\"arm\":\"$arm\",\"attempt\":$i,\"exit\":$code,\"delta\":$delta,\"product_ok\":$product_ok,\"ts\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}" >> "$SUMMARY"
# brief cool between arms to avoid thrashing mail/proxy
sleep 3
done
done
echo "=== ab_fingerprint summary ==="
if [[ -f "$SUMMARY" ]]; then
cat "$SUMMARY"
"$PY" - <<'PY'
import json, os
from collections import defaultdict
path = os.environ.get("AB_SUMMARY_PATH") or ""
rows = []
if path and os.path.isfile(path):
for line in open(path):
line = line.strip()
if not line:
continue
try:
rows.append(json.loads(line))
except Exception:
pass
by = defaultdict(lambda: {"n": 0, "ok": 0, "busy": 0})
for r in rows:
a = r.get("arm") or "?"
by[a]["n"] += 1
by[a]["ok"] += int(r.get("product_ok") or 0)
if r.get("status") == "cli_lock_busy":
by[a]["busy"] += 1
print("AGG", {k: dict(v) for k, v in by.items()})
print("NOTE production default remains browser_fingerprint_mode=off until AGG favors light")
PY
fi
echo "=== ab_fingerprint end $(date -u +%Y-%m-%dT%H:%M:%SZ) ==="
} 2>&1 | tee -a "$LOG"
# exit 0 if at least one product_ok across arms; 1 otherwise; 2 lock busy already exited
if [[ -f "$SUMMARY" ]] && grep -q '"product_ok":1' "$SUMMARY"; then
exit 0
fi
exit 1
+430
View File
@@ -0,0 +1,430 @@
#!/usr/bin/env python3
"""Inventory / backfill chat_ok stamps on historical CPA xai-*.json files.
Ops tool for auth dirs minted before chat probe stamps existed (~mostly
unstamped pools). Default is inventory-only (no network).
With ``--probe``: re-probe chat (and models if needed) using the file's
access_token, then stamp chat_ok / entitlement_denied / chat_retryable /
import_gate via ``stamp_auth_chat_fields``. Entitlement denials also append
the ledger. Does NOT remint OAuth and does NOT remote-inject (use remint for
that after stamps exist).
Mid-tier probe (tebi CPA):
- ``cpa_probe_via`` / ``--probe-via``: direct | cpa | hybrid (default hybrid)
- unpinned ``cpa`` falls back to hybrid (direct gate + optional CPA smoke)
- observational ``probe_via_cpa_ok`` never replaces ``chat_ok`` for inject
Examples (from project root):
.venv/bin/python -u scripts/backfill_chat_stamps.py --inventory-only
.venv/bin/python -u scripts/backfill_chat_stamps.py --probe --only-missing --limit 20
.venv/bin/python -u scripts/backfill_chat_stamps.py --probe --email a@b.com --no-remote
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
_ROOT = Path(__file__).resolve().parents[1]
if str(_ROOT) not in sys.path:
sys.path.insert(0, str(_ROOT))
from cpa_xai.probe import ( # noqa: E402
apply_chat_probe_to_result,
build_probe_transport,
probe_chat_with_retries,
probe_models,
resolve_gate_probe_policy,
)
from cpa_xai.schema import DEFAULT_BASE_URL, credential_file_name # noqa: E402
from cpa_xai.writer import ( # noqa: E402
inventory_chat_stamps,
is_entitlement_denied_auth,
record_entitlement_denied,
stamp_auth_chat_fields,
)
def _load_config(path: Path) -> dict:
if not path.is_file():
return {}
try:
raw = json.loads(path.read_text(encoding="utf-8"))
except Exception as e: # noqa: BLE001
print(f"warn: config read failed: {e}", flush=True)
return {}
if not isinstance(raw, dict):
return {}
return {
k: v
for k, v in raw.items()
if not (isinstance(k, str) and (k.startswith("//") or k.startswith("#")))
}
def _iter_auth_files(
auth_dir: Path,
*,
only_email: str,
only_missing: bool,
include_denied: bool,
limit: int,
) -> list[Path]:
want = (only_email or "").strip().lower()
out: list[Path] = []
for p in sorted(auth_dir.glob("xai-*.json")):
if "_selftest" in p.name:
continue
try:
d = json.loads(p.read_text(encoding="utf-8"))
except Exception:
continue
if not isinstance(d, dict):
continue
em = str(d.get("email") or "").strip().lower()
if want and em != want:
continue
if only_missing and "chat_ok" in d:
continue
if not include_denied and is_entitlement_denied_auth(d):
continue
out.append(p)
if limit and len(out) >= limit:
break
return out
def _resolve_probe_pin(
*,
email: str,
path: Path,
pin_mode: str,
explicit_pin: str = "",
) -> str:
if (explicit_pin or "").strip():
return explicit_pin.strip()
mode = (pin_mode or "auth_filename").strip().lower()
if mode == "email":
return (email or "").strip()
if mode == "auth_filename":
if email:
return credential_file_name(email=email)
return path.name
return ""
def _probe_and_stamp(
path: Path,
*,
base_url: str,
proxy: str | None,
log,
probe_via: str = "hybrid",
cpa_probe_base_url: str = "",
cpa_probe_api_key: str = "",
pin_mode: str = "auth_filename",
pin_header: str = "X-CPA-Credential",
allow_unpinned_cpa_gate: bool = False,
probe_credential_pin: str = "",
) -> dict:
try:
d = json.loads(path.read_text(encoding="utf-8"))
except Exception as e: # noqa: BLE001
return {"ok": False, "path": str(path), "error": f"read: {e}"}
if not isinstance(d, dict):
return {"ok": False, "path": str(path), "error": "not a dict"}
email = str(d.get("email") or "").strip()
token = str(d.get("access_token") or "").strip()
if not token:
return {"ok": False, "email": email, "path": str(path), "error": "missing access_token"}
pin = _resolve_probe_pin(
email=email,
path=path,
pin_mode=pin_mode,
explicit_pin=probe_credential_pin,
)
policy = resolve_gate_probe_policy(
via=probe_via,
cpa_base_url=cpa_probe_base_url,
cpa_api_key=cpa_probe_api_key,
credential_pin=pin if str(probe_via or "").strip().lower() != "direct" else "",
allow_unpinned_cpa_gate=bool(allow_unpinned_cpa_gate),
)
gate_via = str(policy.get("gate_via") or "direct")
gate_transport = build_probe_transport(
via=gate_via,
upstream_base_url=base_url,
cpa_base_url=cpa_probe_base_url,
cpa_api_key=cpa_probe_api_key,
access_token=token,
credential_pin=pin if gate_via == "cpa" else "",
pin_header=pin_header or "X-CPA-Credential",
)
log(
f"probe policy via={probe_via!r} gate={gate_via} "
f"cpa_smoke={policy.get('cpa_smoke')} reason={policy.get('reason')}"
)
pr = probe_models(token, base_url=base_url, proxy=proxy, transport=gate_transport)
result: dict = {
"email": email,
"path": str(path),
"probe_models": pr,
"probe_gate_via": gate_via,
"probe_policy_reason": policy.get("reason") or "",
"probe_via_cpa_ok": None,
}
log(
f"models ok={pr.get('ok')} status={pr.get('status')} "
f"has_grok_45={pr.get('has_grok_45')} mode={pr.get('transport_mode')!r} "
f"err={str(pr.get('error') or '')[:120]}"
)
if not pr.get("has_grok_45"):
apply_chat_probe_to_result(
result,
None,
models_missing=True,
models_status=int(pr.get("status") or 0),
)
else:
ch = probe_chat_with_retries(
token,
base_url=base_url,
proxy=proxy,
max_attempts=3,
log=log,
transport=gate_transport,
)
apply_chat_probe_to_result(result, ch)
if result.get("entitlement_denied"):
log("FAIL-FAST: chat entitlement_denied — ledger + stamp only (no remint)")
# Observational CPA smoke only after gate chat_ok (never inject latch).
if (
policy.get("cpa_smoke")
and result.get("chat_ok") is True
and not result.get("entitlement_denied")
and (cpa_probe_base_url or "").strip()
and (cpa_probe_api_key or "").strip()
):
cpa_t = build_probe_transport(
via="cpa",
upstream_base_url=base_url,
cpa_base_url=cpa_probe_base_url,
cpa_api_key=cpa_probe_api_key,
access_token=token,
credential_pin=pin,
pin_header=pin_header or "X-CPA-Credential",
)
try:
smoke = probe_chat_with_retries(
token,
base_url=base_url,
proxy=proxy,
max_attempts=1,
log=log,
transport=cpa_t,
)
result["probe_cpa_smoke"] = smoke
result["probe_via_cpa_ok"] = bool(smoke.get("ok"))
log(
f"cpa smoke ok={smoke.get('ok')} status={smoke.get('status')} "
f"mode={smoke.get('transport_mode')!r}"
)
except Exception as e: # noqa: BLE001
result["probe_via_cpa_ok"] = False
result["probe_cpa_smoke_error"] = str(e)
log(f"cpa smoke failed: {e}")
try:
updates = {
"probe_gate_via": result.get("probe_gate_via"),
"probe_policy_reason": result.get("probe_policy_reason"),
}
if result.get("probe_via_cpa_ok") is True or result.get("probe_via_cpa_ok") is False:
updates["probe_via_cpa_ok"] = bool(result.get("probe_via_cpa_ok"))
stamped = stamp_auth_chat_fields(path, result, updates=updates)
result["import_gate"] = stamped.get("import_gate")
if stamped.get("chat_ok") is None and "chat_ok" not in stamped:
# incomplete stamp should not happen after full probe; surface for ops
log(f"stamp incomplete keys={sorted(stamped.keys())}")
except Exception as e: # noqa: BLE001
result["stamp_error"] = str(e)
log(f"stamp failed: {e}")
if result.get("entitlement_denied"):
try:
record_entitlement_denied(
path.parent,
email,
extra={
"path": str(path),
"source": "backfill_chat_stamps",
"chat_error_code": result.get("chat_error_code"),
},
)
except Exception as e: # noqa: BLE001
log(f"ledger write failed: {e}")
return result
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--config", default=str(_ROOT / "config.json"))
ap.add_argument("--auth-dir", default="", help="Default: config cpa_auth_dir or ./cpa_auths")
ap.add_argument("--inventory-only", action="store_true", help="Only print inventory stats")
ap.add_argument("--probe", action="store_true", help="Re-probe chat and stamp files")
ap.add_argument("--only-missing", action="store_true", help="Only files without chat_ok key")
ap.add_argument("--include-denied", action="store_true", help="Also process stamped denied")
ap.add_argument("--email", default="")
ap.add_argument("--limit", type=int, default=0)
ap.add_argument("--sleep", type=float, default=1.5)
ap.add_argument(
"--base-url",
default="",
help=f"Override probe base (default config/DEFAULT {DEFAULT_BASE_URL})",
)
ap.add_argument(
"--probe-via",
default="",
help="Override cpa_probe_via: direct|cpa|hybrid (default hybrid)",
)
ap.add_argument(
"--state",
default=str(_ROOT / "logs" / "backfill_chat_stamps_state.json"),
)
args = ap.parse_args()
cfg = _load_config(Path(args.config))
auth_dir = Path(args.auth_dir or cfg.get("cpa_auth_dir") or (_ROOT / "cpa_auths"))
if not auth_dir.is_absolute():
auth_dir = (_ROOT / auth_dir).resolve()
if not auth_dir.is_dir():
print(f"auth_dir missing: {auth_dir}", flush=True)
return 2
inv = inventory_chat_stamps(auth_dir)
print(f"auth_dir={auth_dir}", flush=True)
print(json.dumps({"inventory": inv}, ensure_ascii=False, indent=2), flush=True)
if args.inventory_only or not args.probe:
if not args.probe and not args.inventory_only:
print(
"hint: pass --probe to re-probe+stamp, or --inventory-only to silence this hint",
flush=True,
)
return 0
base_url = (args.base_url or cfg.get("cpa_base_url") or DEFAULT_BASE_URL).rstrip("/")
proxy = (cfg.get("proxy") or cfg.get("https_proxy") or "").strip() or None
probe_via = (
str(args.probe_via or cfg.get("cpa_probe_via") or "hybrid").strip().lower() or "hybrid"
)
if probe_via not in {"direct", "cpa", "hybrid"}:
probe_via = "hybrid"
cpa_probe_base_url = str(
cfg.get("cpa_probe_base_url") or os.environ.get("CPA_PROBE_BASE_URL") or ""
).strip()
cpa_probe_api_key = str(
cfg.get("cpa_probe_api_key") or os.environ.get("CPA_PROBE_API_KEY") or ""
).strip()
pin_mode = str(
cfg.get("cpa_probe_credential_pin_mode") or "auth_filename"
).strip().lower() or "auth_filename"
pin_header = str(
cfg.get("cpa_probe_pin_header") or "X-CPA-Credential"
).strip() or "X-CPA-Credential"
allow_unpinned = bool(cfg.get("cpa_probe_allow_unpinned_cpa_gate") is True)
files = _iter_auth_files(
auth_dir,
only_email=args.email,
only_missing=bool(args.only_missing),
include_denied=bool(args.include_denied),
limit=args.limit,
)
print(
f"probe candidates={len(files)} only_missing={args.only_missing} "
f"base_url={base_url} probe_via={probe_via} sleep={args.sleep}",
flush=True,
)
if not files:
print("nothing to probe", flush=True)
return 0
ok_n = denied_n = fail_n = 0
t0 = time.time()
state_path = Path(args.state)
state_path.parent.mkdir(parents=True, exist_ok=True)
for i, p in enumerate(files, 1):
email_hint = p.name
def log(msg: str, _i=i, _p=email_hint) -> None:
print(f"[{time.strftime('%H:%M:%S')}] [{_i}/{len(files)}] [{_p}] {msg}", flush=True)
log("start")
r = _probe_and_stamp(
p,
base_url=base_url,
proxy=proxy,
log=log,
probe_via=probe_via,
cpa_probe_base_url=cpa_probe_base_url,
cpa_probe_api_key=cpa_probe_api_key,
pin_mode=pin_mode,
pin_header=pin_header,
allow_unpinned_cpa_gate=allow_unpinned,
)
if r.get("entitlement_denied"):
denied_n += 1
log(f"DENIED gate={r.get('import_gate')}")
elif r.get("chat_ok") is True:
ok_n += 1
log("chat_ok")
else:
fail_n += 1
log(f"fail reason={r.get('fail_reason') or r.get('error')}")
if i == 1 or i % 10 == 0 or i == len(files):
state = {
"updated_at": datetime.now(timezone.utc).isoformat(),
"done": i,
"total": len(files),
"chat_ok": ok_n,
"chat_denied": denied_n,
"chat_fail": fail_n,
"elapsed_s": round(time.time() - t0, 1),
"last_path": str(p),
"last_chat_ok": r.get("chat_ok"),
"last_import_gate": r.get("import_gate"),
"probe_via": probe_via,
}
state_path.write_text(
json.dumps(state, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
)
if args.sleep and i < len(files):
time.sleep(args.sleep)
inv_after = inventory_chat_stamps(auth_dir)
print(
f"\n=== done chat_ok={ok_n} chat_denied={denied_n} chat_fail={fail_n} "
f"elapsed={round(time.time()-t0,1)}s ===",
flush=True,
)
print(json.dumps({"inventory_after": inv_after}, ensure_ascii=False, indent=2), flush=True)
return 0 if denied_n + fail_n == 0 or ok_n > 0 else 1
if __name__ == "__main__":
raise SystemExit(main())
+288
View File
@@ -0,0 +1,288 @@
#!/usr/bin/env python3
"""Batch mint CPA xai-*.json from register accounts_cli.txt.
Default path goes through ``cpa_export.export_cpa_xai_for_account`` so SSO
normalize, optional tebi remote inject, hotload copy, and local backup match
the live register pipeline.
Use ``--local-only`` to call mint_and_export directly (no remote inject).
Example (from grok-register project root):
uv run python -u scripts/backfill_cpa_xai_from_accounts.py --limit 1
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import time
from pathlib import Path
_ROOT = Path(__file__).resolve().parents[1]
if str(_ROOT) not in sys.path:
sys.path.insert(0, str(_ROOT))
from cpa_xai import email_in_existing, existing_cpa_emails, parse_accounts_file # noqa: E402
def _load_config(path: str | Path) -> dict:
cfg_path = Path(path)
if not cfg_path.is_file():
return {}
try:
cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
except Exception as e: # noqa: BLE001
print(f"warn: read config failed: {e}", flush=True)
return {}
if not isinstance(cfg, dict):
return {}
return {
k: v
for k, v in cfg.items()
if not (isinstance(k, str) and (k.startswith("//") or k.startswith("#")))
}
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument(
"--accounts",
default=str(_ROOT / "accounts_cli.txt"),
)
ap.add_argument(
"--out-dir",
default="",
help="Override cpa_auth_dir (default: config or ./cpa_auths)",
)
ap.add_argument(
"--cpa-dir",
default="",
help="Optional CPA hot-load auth-dir override",
)
ap.add_argument("--limit", type=int, default=0, help="0 = all missing")
ap.add_argument("--offset", type=int, default=0)
ap.add_argument("--email", default="", help="Only this email")
ap.add_argument(
"--emails",
default="",
help="Alias of --email (single address). Kept for CLI muscle memory.",
)
ap.add_argument("--skip-existing", action="store_true", default=True)
ap.add_argument("--no-skip-existing", action="store_false", dest="skip_existing")
ap.add_argument(
"--headless",
action="store_true",
default=False,
help="Headless Chromium (usually blocked by Cloudflare on accounts.x.ai)",
)
ap.add_argument(
"--headed",
action="store_true",
default=True,
help="Show browser (default; required for stable device consent)",
)
ap.add_argument("--probe", action="store_true", default=True)
ap.add_argument("--no-probe", action="store_false", dest="probe")
ap.add_argument(
"--probe-chat",
action="store_true",
default=True,
help="Probe /v1/responses after mint (default on; product free-Build gate)",
)
ap.add_argument("--no-probe-chat", action="store_false", dest="probe_chat")
ap.add_argument(
"--proxy",
default="",
help="Outbound proxy. Empty → read register config.json cpa_proxy/proxy, else env",
)
ap.add_argument(
"--config",
default=str(_ROOT / "config.json"),
help="register config.json for cpa_* defaults and remote inject",
)
ap.add_argument("--timeout", type=float, default=300.0)
ap.add_argument("--sleep", type=float, default=3.0, help="Sleep between accounts")
ap.add_argument(
"--fail-log",
default=str(_ROOT / "cpa_auths" / "backfill_failed.jsonl"),
help="Append failures JSONL",
)
ap.add_argument(
"--force-standalone",
action="store_true",
default=True,
help="Always open fresh Chromium (default)",
)
ap.add_argument(
"--local-only",
action="store_true",
default=False,
help="Bypass cpa_export (no remote inject / backup hooks); mint only",
)
ap.add_argument(
"--no-remote",
action="store_true",
default=False,
help="Keep cpa_export path but force cpa_remote_inject=false for this run",
)
args = ap.parse_args()
if args.headless:
args.headed = False
else:
args.headless = False
# Accept --emails as alias of --email (first token if comma/space list)
if not (args.email or "").strip() and (args.emails or "").strip():
raw = args.emails.replace(",", " ").split()
args.email = raw[0] if raw else ""
cfg = _load_config(args.config)
if not args.proxy:
args.proxy = (cfg.get("cpa_proxy") or cfg.get("proxy") or "").strip()
if not args.proxy:
args.proxy = (
os.environ.get("https_proxy")
or os.environ.get("HTTPS_PROXY")
or os.environ.get("http_proxy")
or ""
).strip()
out_dir = (args.out_dir or cfg.get("cpa_auth_dir") or str(_ROOT / "cpa_auths")).strip()
out_path = Path(out_dir).expanduser()
if not out_path.is_absolute():
out_path = (_ROOT / out_path).resolve()
cpa_dir = (args.cpa_dir or cfg.get("cpa_hotload_dir") or "").strip()
# Overlay CLI flags onto config for export path
run_cfg = dict(cfg)
run_cfg["cpa_auth_dir"] = str(out_path)
if cpa_dir:
run_cfg["cpa_hotload_dir"] = cpa_dir
run_cfg["cpa_copy_to_hotload"] = True
if args.proxy:
run_cfg["cpa_proxy"] = args.proxy
run_cfg["cpa_headless"] = bool(args.headless)
run_cfg["cpa_probe_after_write"] = bool(args.probe)
run_cfg["cpa_probe_chat"] = bool(args.probe_chat)
run_cfg["cpa_mint_timeout_sec"] = float(args.timeout)
run_cfg["cpa_force_standalone"] = bool(args.force_standalone)
if args.no_remote:
run_cfg["cpa_remote_inject"] = False
print(
f"proxy={args.proxy or '(none)'} out={out_path} "
f"local_only={args.local_only} remote_inject={run_cfg.get('cpa_remote_inject')}",
flush=True,
)
accounts = parse_accounts_file(args.accounts)
if args.email:
accounts = [a for a in accounts if a.email.lower() == args.email.lower()]
accounts = accounts[args.offset :]
have: set[str] = set()
if args.skip_existing:
have |= existing_cpa_emails(out_path)
if cpa_dir:
have |= existing_cpa_emails(cpa_dir)
todo = []
for a in accounts:
if args.skip_existing and email_in_existing(a.email, have):
continue
todo.append(a)
if args.limit and len(todo) >= args.limit:
break
print(
f"accounts total={len(parse_accounts_file(args.accounts))} "
f"todo={len(todo)} out={out_path}",
flush=True,
)
out_path.mkdir(parents=True, exist_ok=True)
if cpa_dir:
Path(cpa_dir).expanduser().mkdir(parents=True, exist_ok=True)
ok_n = fail_n = 0
results = []
for i, acc in enumerate(todo, 1):
print(f"\n=== [{i}/{len(todo)}] {acc.email} ===", flush=True)
def log(msg: str, _email=acc.email) -> None:
print(f"[{time.strftime('%H:%M:%S')}] [{_email}] {msg}", flush=True)
if args.local_only:
from cpa_xai import mint_and_export
r = mint_and_export(
email=acc.email,
password=acc.password,
auth_dir=out_path,
page=None,
proxy=args.proxy or None,
headless=args.headless,
probe=args.probe,
probe_chat=args.probe_chat,
browser_timeout_sec=args.timeout,
force_standalone=args.force_standalone,
sso=acc.sso or None,
prefer_protocol=bool(run_cfg.get("cpa_prefer_protocol", True)),
protocol_only=bool(run_cfg.get("cpa_protocol_only", False)),
allow_device_flow_fallback=bool(
run_cfg.get("cpa_allow_device_flow_fallback", True)
),
protocol_flow=str(run_cfg.get("cpa_protocol_flow") or "pkce"),
log=log,
)
if r.get("ok") and r.get("path") and cpa_dir:
import shutil
src = Path(r["path"])
dst = Path(cpa_dir).expanduser() / src.name
shutil.copy2(src, dst)
os.chmod(dst, 0o600)
print(f"copied -> {dst}", flush=True)
else:
import cpa_export
r = cpa_export.export_cpa_xai_for_account(
acc.email,
acc.password,
page=None,
sso=acc.sso or None,
config=run_cfg,
log_callback=log,
)
results.append(r)
if r.get("ok") and r.get("path"):
ok_n += 1
from cpa_xai.accounts import email_match_keys
have |= email_match_keys(acc.email)
else:
fail_n += 1
if args.fail_log:
Path(args.fail_log).parent.mkdir(parents=True, exist_ok=True)
with open(args.fail_log, "a", encoding="utf-8") as f:
f.write(json.dumps(r, ensure_ascii=False, default=str) + "\n")
if args.sleep and i < len(todo):
time.sleep(args.sleep)
print(f"\n=== done ok={ok_n} fail={fail_n} ===", flush=True)
summary = out_path / f"backfill_summary_{int(time.time())}.json"
summary.write_text(
json.dumps(results, indent=2, ensure_ascii=False, default=str),
encoding="utf-8",
)
print(f"summary {summary}")
return 0 if ok_n > 0 or not todo else 1
if __name__ == "__main__":
raise SystemExit(main())
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Snapshot registered accounts + CPA auth files into project backups/.
Usage (project root):
uv run python -u scripts/backup_registered_accounts.py
uv run python -u scripts/backup_registered_accounts.py --no-stamp
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
_ROOT = Path(__file__).resolve().parents[1]
if str(_ROOT) not in sys.path:
sys.path.insert(0, str(_ROOT))
import account_backup # noqa: E402
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument(
"--no-stamp",
action="store_true",
help="Only refresh backups/latest (no register_YYYYMMDD_HHMMSS dir)",
)
ap.add_argument("--reason", default="manual")
args = ap.parse_args()
res = account_backup.snapshot_registered_accounts(
_ROOT,
reason=args.reason,
make_timestamped=not args.no_stamp,
log_callback=print,
)
print(
f"OK accounts={res.get('account_count')} cpa={res.get('cpa_count')} "
f"latest={res.get('latest')} stamped={res.get('stamped') or '-'}"
)
return 0 if res.get("ok") else 1
if __name__ == "__main__":
raise SystemExit(main())
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/env bash
# Bootstrap project-owned mihomo core under .nodes/bin/
# Usage: ./scripts/bootstrap_nodes_core.sh
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
BIN_DIR="$ROOT/.nodes/bin"
mkdir -p "$BIN_DIR" "$ROOT/.nodes/config" "$ROOT/.nodes/runtime" "$ROOT/.nodes/profiles"
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"
case "$ARCH" in
arm64|aarch64) ARCH=arm64 ;;
x86_64|amd64) ARCH=amd64 ;;
esac
ASSET="mihomo-${OS}-${ARCH}"
# Prefer go-default build
TAG="${MIHOMO_TAG:-v1.19.28}"
URL="https://github.com/MetaCubeX/mihomo/releases/download/${TAG}/${ASSET}-${TAG}.gz"
# fallback name without tag middle
URL2="https://github.com/MetaCubeX/mihomo/releases/download/${TAG}/${ASSET}-v${TAG#v}.gz"
echo "[bootstrap] fetch $URL"
TMP="$(mktemp)"
if curl -fsSL -L "$URL" -o "$TMP"; then
:
elif curl -fsSL -L "$URL2" -o "$TMP"; then
:
else
# last resort: copy from local Clash Verge install
VERGE="/Applications/Clash Verge.app/Contents/MacOS/verge-mihomo"
if [[ -x "$VERGE" ]]; then
echo "[bootstrap] github failed; copying local verge-mihomo"
cp -f "$VERGE" "$BIN_DIR/mihomo"
chmod +x "$BIN_DIR/mihomo"
"$BIN_DIR/mihomo" -v | head -2
exit 0
fi
echo "[bootstrap] failed to download mihomo" >&2
exit 1
fi
gunzip -c "$TMP" > "$BIN_DIR/mihomo"
rm -f "$TMP"
chmod +x "$BIN_DIR/mihomo"
echo "[bootstrap] installed:"
"$BIN_DIR/mihomo" -v | head -3
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
# scripts/build_web_console.sh — build console10 (Vite+Preact) into apps/web/dist
# Prefer npm ci when package-lock.json is present (CI-friendly).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT/apps/web"
if [[ -f package-lock.json ]]; then
npm ci
elif [[ ! -d node_modules ]]; then
npm install
fi
npm run build
test -f dist/index.html
echo "[web] built → $ROOT/apps/web/dist"
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env python3
"""Authoritative Clash/proxy egress IP check (ops).
Prefer this over bare ``curl -x http://127.0.0.1:7897 https://api.ipify.org``
on Bohrium/pxed: system curl can report host CN IP (e.g. 39.98.70.173) even when
mihomo leaf is overseas and delay API is green. Uses curl_cffi when available
(same stack as ChatGPT provider / node L1 probes), else urllib.
Usage:
.venv/bin/python scripts/check_clash_egress.py
.venv/bin/python scripts/check_clash_egress.py --proxy http://127.0.0.1:7897
.venv/bin/python scripts/check_clash_egress.py --json
.venv/bin/python scripts/check_clash_egress.py --expect-not 39.98.70.173
Exit: 0 if ok (+ expect filters pass), 2 if probe failed / expect mismatch.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
_ROOT = Path(__file__).resolve().parents[1]
if str(_ROOT) not in sys.path:
sys.path.insert(0, str(_ROOT))
from register_core.nodes.health import probe_egress_ip # noqa: E402
def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(description="Probe public egress IP via HTTP proxy")
p.add_argument(
"--proxy",
default="http://127.0.0.1:7897",
help="HTTP proxy URL (default Clash mixed-port)",
)
p.add_argument("--timeout", type=float, default=15.0)
p.add_argument("--json", action="store_true", help="print full result JSON")
p.add_argument(
"--expect-not",
action="append",
default=[],
metavar="IP",
help="fail if egress equals this IP (repeatable); use for known host CN",
)
p.add_argument(
"--expect",
default="",
metavar="IP",
help="optional exact IP match requirement",
)
args = p.parse_args(argv)
result = probe_egress_ip(args.proxy, timeout=args.timeout)
if args.json:
print(json.dumps(result, ensure_ascii=False, indent=2))
else:
if result.get("ok"):
print(
f"EGRESS_IP={result['ip']} backend={result.get('backend')} "
f"ms={result.get('ms')} proxy={args.proxy} url={result.get('url')}"
)
else:
print(
f"EGRESS_IP=FAIL error={result.get('error')} "
f"backend={result.get('backend')} proxy={args.proxy}",
file=sys.stderr,
)
if not result.get("ok"):
return 2
ip = str(result.get("ip") or "")
if args.expect and ip != args.expect.strip():
print(f"EXPECT_MISMATCH want={args.expect!r} got={ip!r}", file=sys.stderr)
return 2
banned = {x.strip() for x in (args.expect_not or []) if str(x).strip()}
if ip in banned:
print(
f"EXPECT_NOT hit banned host/CN IP={ip!r} "
f"(proxy may be bypassed or leaf REJECT; do not trust bare curl either)",
file=sys.stderr,
)
return 2
return 0
if __name__ == "__main__":
raise SystemExit(main())
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""Manage control-plane operator accounts (password auth).
Examples:
uv run python scripts/control_api_user.py set admin
uv run python scripts/control_api_user.py set admin --password '...'
uv run python scripts/control_api_user.py list
"""
from __future__ import annotations
import argparse
import getpass
import os
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from apps.control_api.users import list_usernames, upsert_user, users_path # noqa: E402
def main() -> int:
p = argparse.ArgumentParser(description="Control API operator accounts")
p.add_argument(
"--root",
default=os.environ.get("REGISTER_PROJECT_ROOT") or str(ROOT),
help="project root (default REGISTER_PROJECT_ROOT or repo)",
)
sub = p.add_subparsers(dest="cmd", required=True)
set_p = sub.add_parser("set", help="create or update a user password")
set_p.add_argument("username")
set_p.add_argument("--password", default=None, help="if omitted, prompt")
sub.add_parser("list", help="list usernames")
args = p.parse_args()
root = Path(args.root).resolve()
if args.cmd == "list":
users = list_usernames(root)
print(f"path={users_path(root)}")
for u in users:
print(u)
if not users:
print("(no users)")
return 0
if args.cmd == "set":
password = args.password
if not password:
password = getpass.getpass("password: ")
again = getpass.getpass("confirm: ")
if password != again:
print("passwords do not match", file=sys.stderr)
return 2
try:
upsert_user(root, args.username, password)
except ValueError as e:
print(str(e), file=sys.stderr)
return 2
print(f"ok user={args.username} path={users_path(root)}")
return 0
return 1
if __name__ == "__main__":
raise SystemExit(main())
+187
View File
@@ -0,0 +1,187 @@
#!/usr/bin/env bash
# scripts/deploy_web_console10.sh — single source for manual + GitHub Actions deploy
# Does NOT stop batch/coinbot. Static SPA only.
#
# control_api mounts StaticFiles at apps/web (NOT apps/web/dist):
# web_dir = .../apps/web + index.html + assets/
# so we publish dist/* into that web root, and also keep apps/web/dist in sync.
#
# Env:
# PXED_HOST ssh target (default: pxed)
# PXED_WEB remote web root (default: /data/grok-register/apps/web)
# must stay under /data/grok-register (sanitized)
# PXED_SSH_PORT default 22
# PXED_SSH_KEY optional private key path (IdentitiesOnly)
# PXED_SSH_PRIVATE_KEY optional PEM contents (written to a temp key file)
# PXED_KNOWN_HOSTS optional known_hosts body (required for non-interactive CI)
# PXED_KNOWN_HOSTS_FILE optional path to known_hosts (alternative to body)
# SKIP_BUILD=1 use existing apps/web/dist (or CONSOLE10_TGZ)
# CONSOLE10_TGZ prebuilt tarball of dist contents; skips local build
# DRY_RUN=1 pack only; no scp/ssh
# PRUNE_STALE_ASSETS=1 default 1 — remove remote assets not in the new package
set -euo pipefail
export COPYFILE_DISABLE=1
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
HOST="${PXED_HOST:-pxed}"
REMOTE="${PXED_WEB:-/data/grok-register/apps/web}"
PORT="${PXED_SSH_PORT:-22}"
TGZ="${CONSOLE10_TGZ:-/tmp/console10-webroot.tgz}"
PRUNE_STALE_ASSETS="${PRUNE_STALE_ASSETS:-1}"
CLEANUPS=()
cleanup() {
local p
for p in "${CLEANUPS[@]:-}"; do
rm -rf "$p" 2>/dev/null || true
done
}
trap cleanup EXIT
# --- sanitize remote path (C2) ---
while [[ "$REMOTE" == */ && "$REMOTE" != / ]]; do
REMOTE="${REMOTE%/}"
done
case "$REMOTE" in
/data/grok-register|/data/grok-register/*) ;;
*)
echo "[deploy] PXED_WEB must be under /data/grok-register, got: $REMOTE" >&2
exit 2
;;
esac
if [[ "$REMOTE" == *..* ]]; then
echo "[deploy] PXED_WEB must not contain .." >&2
exit 2
fi
if [[ ! "$REMOTE" =~ ^/data/grok-register(/[A-Za-z0-9._+-]+)*$ ]]; then
echo "[deploy] PXED_WEB has unsafe characters: $REMOTE" >&2
exit 2
fi
# --- SSH identity / known_hosts ---
KEY_FILE="${PXED_SSH_KEY:-}"
if [[ -n "${PXED_SSH_PRIVATE_KEY:-}" ]]; then
KEY_FILE="$(mktemp "${TMPDIR:-/tmp}/pxed_deploy_key.XXXXXX")"
CLEANUPS+=("$KEY_FILE")
umask 077
# M2: always end PEM with a newline (OpenSSH rejects some keys without it).
# Strip one trailing newline first so we never double-pad multi-line secrets oddly.
_pem="${PXED_SSH_PRIVATE_KEY%$'\n'}"
printf '%s\n' "$_pem" > "$KEY_FILE"
unset _pem
chmod 600 "$KEY_FILE"
fi
KNOWN_FILE=""
if [[ -n "${PXED_KNOWN_HOSTS_FILE:-}" && -f "${PXED_KNOWN_HOSTS_FILE}" ]]; then
KNOWN_FILE="$PXED_KNOWN_HOSTS_FILE"
elif [[ -n "${PXED_KNOWN_HOSTS:-}" ]]; then
KNOWN_FILE="$(mktemp "${TMPDIR:-/tmp}/pxed_known_hosts.XXXXXX")"
CLEANUPS+=("$KNOWN_FILE")
_kh="${PXED_KNOWN_HOSTS%$'\n'}"
printf '%s\n' "$_kh" > "$KNOWN_FILE"
unset _kh
chmod 600 "$KNOWN_FILE"
fi
# CI / production: pin host keys when known_hosts provided.
# Local interactive fallback: accept-new (operator machine already trusts pxed).
if [[ -n "$KNOWN_FILE" ]]; then
ssh_opts=(-o BatchMode=yes -o StrictHostKeyChecking=yes
-o UserKnownHostsFile="$KNOWN_FILE" -o GlobalKnownHostsFile=/dev/null)
scp_opts=(-o BatchMode=yes -o StrictHostKeyChecking=yes
-o UserKnownHostsFile="$KNOWN_FILE" -o GlobalKnownHostsFile=/dev/null)
else
ssh_opts=(-o BatchMode=yes -o StrictHostKeyChecking=accept-new)
scp_opts=(-o BatchMode=yes -o StrictHostKeyChecking=accept-new)
fi
if [[ -n "$KEY_FILE" ]]; then
ssh_opts+=(-i "$KEY_FILE" -o IdentitiesOnly=yes)
scp_opts+=(-i "$KEY_FILE" -o IdentitiesOnly=yes)
fi
if [[ "$PORT" != "22" ]]; then
ssh_opts+=(-p "$PORT")
scp_opts+=(-P "$PORT")
fi
# --- build / pack ---
if [[ -n "${CONSOLE10_TGZ:-}" && -f "${CONSOLE10_TGZ}" ]]; then
TGZ="$CONSOLE10_TGZ"
echo "[deploy] using prebuilt tarball: $TGZ"
elif [[ "${SKIP_BUILD:-0}" == "1" ]]; then
if [[ ! -f "$ROOT/apps/web/dist/index.html" ]]; then
echo "[deploy] SKIP_BUILD=1 but apps/web/dist/index.html missing" >&2
exit 2
fi
tar -C "$ROOT/apps/web/dist" -czf "$TGZ" .
echo "[deploy] packed existing dist → $TGZ"
else
"$ROOT/scripts/build_web_console.sh"
tar -C "$ROOT/apps/web/dist" -czf "$TGZ" .
fi
if [[ ! -s "$TGZ" ]]; then
echo "[deploy] tarball missing or empty: $TGZ" >&2
exit 2
fi
if [[ "${DRY_RUN:-0}" == "1" ]]; then
ls -la "$TGZ"
echo "[deploy] DRY_RUN=1 — not copying to $HOST:$REMOTE"
exit 0
fi
if [[ -z "${PXED_HOST:-}" && "$HOST" == "pxed" ]]; then
: # default host alias ok for local
fi
scp "${scp_opts[@]}" "$TGZ" "$HOST:/tmp/console10-webroot.tgz"
# Remote publish: extract stage → prune stale assets (I2) → overlay → dist mirror.
# REMOTE is passed via env (not interpolated into remote shell string).
ssh -T "${ssh_opts[@]}" "$HOST" \
env "REMOTE=$REMOTE" "PRUNE_STALE_ASSETS=$PRUNE_STALE_ASSETS" \
bash -s <<'REMOTE_SCRIPT'
set -euo pipefail
case "$REMOTE" in
/data/grok-register|/data/grok-register/*) ;;
*) echo "refusing remote path: $REMOTE" >&2; exit 1 ;;
esac
if [[ ! "$REMOTE" =~ ^/data/grok-register(/[A-Za-z0-9._+-]+)*$ ]]; then
echo "refusing unsafe remote path: $REMOTE" >&2
exit 1
fi
TGZ=/tmp/console10-webroot.tgz
test -s "$TGZ"
STAGE=$(mktemp -d /tmp/console10_stage.XXXXXX)
cleanup_stage() { rm -rf "$STAGE"; }
trap cleanup_stage EXIT
tar -C "$STAGE" -xzf "$TGZ"
test -f "$STAGE/index.html"
publish_webroot() {
local DEST="$1"
mkdir -p "$DEST"
if [[ "${PRUNE_STALE_ASSETS:-1}" == "1" && -d "$DEST/assets" && -d "$STAGE/assets" ]]; then
# I2: drop hashed assets no longer referenced by this build
find "$DEST/assets" -type f -print0 2>/dev/null | while IFS= read -r -d '' f; do
rel="${f#"$DEST/"}"
if [[ ! -e "$STAGE/$rel" ]]; then
rm -f "$f"
fi
done
find "$DEST/assets" -type d -empty -delete 2>/dev/null || true
fi
# overlay new tree (index.html, assets/*, vite extras)
cp -a "$STAGE"/. "$DEST"/
}
publish_webroot "$REMOTE"
publish_webroot "$REMOTE/dist"
rm -f "$TGZ"
echo '[deploy] web root index:'
head -12 "$REMOTE/index.html"
echo '[deploy] assets (head):'
ls -la "$REMOTE/assets" | head
REMOTE_SCRIPT
echo "[deploy] SPA on $HOST:$REMOTE (and $REMOTE/dist) — no control_api restart needed for static"
+107
View File
@@ -0,0 +1,107 @@
#!/usr/bin/env bash
# Local secret hygiene check — never prints file contents.
# Exit 0 = clean for git hygiene; 1 = tracked-secret or hard fail; 2 = warnings only.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
WARN=0
HARD=0
ok() { echo "[ok] $*"; }
warn() { echo "[warn] $*"; WARN=1; }
fail() { echo "[fail] $*"; HARD=1; }
echo "=== doctor_secrets (paths only, no content) ==="
# 1) Must not be tracked by git
TRACKED_BAD="$(
git ls-files 2>/dev/null | grep -E \
'(^|/)(config\.json|\.env|mail_credentials\.txt|accounts_cli\.txt)$|mail_assets/hotmail|cpa_auths/xai-|^backups/|^logs/' \
|| true
)"
if [[ -n "$TRACKED_BAD" ]]; then
fail "tracked secret/runtime paths:"
echo "$TRACKED_BAD" | sed 's/^/ /'
else
ok "no secret/runtime paths tracked by git"
fi
# 2) Example templates must exist and not be the live secret names only
for f in config.example.json config.simple.example.json mail_credentials.example.txt .env.example; do
if [[ -f "$f" ]]; then
ok "template present: $f"
else
warn "missing template: $f"
fi
done
# 3) Live secret files: prefer mode 600 when present
check_mode() {
local path="$1"
if [[ ! -e "$path" ]]; then
return 0
fi
if [[ ! -f "$path" ]]; then
ok "present (dir): $path"
return 0
fi
local mode
mode="$(stat -f '%OLp' "$path" 2>/dev/null || stat -c '%a' "$path" 2>/dev/null || echo '?')"
# last 3 digits; warn if group/other readable
if [[ "$mode" =~ ^[0-9]+$ ]]; then
local last3=$((10#$mode % 1000))
local go=$((last3 % 100))
if (( go != 0 )); then
warn "$path mode=$mode (recommend chmod 600; group/other bits set)"
else
ok "$path mode=$mode"
fi
else
ok "$path present (mode unknown)"
fi
}
check_mode config.json
check_mode .env
check_mode mail_credentials.txt
check_mode accounts_cli.txt
# 4) Runtime dirs size hints (counts only)
if [[ -d cpa_auths ]]; then
n="$(find cpa_auths -maxdepth 1 -name 'xai-*.json' 2>/dev/null | wc -l | tr -d ' ')"
ok "cpa_auths xai-*.json count=$n"
fi
if [[ -d backups ]]; then
ok "backups/ present (gitignored)"
fi
if [[ -d logs ]]; then
ok "logs/ present (gitignored)"
fi
# 5) Cloud sync risk (best-effort)
case "$ROOT" in
*"/Library/Mobile Documents/"*|*"/iCloud"*|*"/Dropbox"*|*"/Google Drive"*|*"/OneDrive"*)
warn "repo path looks cloud-synced — keep mail_credentials/cpa_auths off sync or use encrypted disk"
;;
esac
# 6) Accidental force-add patterns in index (staged)
STAGED_BAD="$(
git diff --cached --name-only 2>/dev/null | grep -E \
'(^|/)(config\.json|\.env|mail_credentials\.txt|accounts_cli\.txt)$|cpa_auths/xai-|^backups/|^logs/' \
|| true
)"
if [[ -n "$STAGED_BAD" ]]; then
fail "staged secret paths (unstage before commit):"
echo "$STAGED_BAD" | sed 's/^/ /'
fi
echo "=== end doctor_secrets ==="
if [[ "$HARD" -ne 0 ]]; then
exit 1
fi
if [[ "$WARN" -ne 0 ]]; then
exit 2
fi
exit 0
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/env python3
"""Convert ~/.grok/auth.json (Grok Build CLI) → CPA xai-<email>.json.
Usage (from grok_reg project root):
uv run python scripts/export_cpa_xai_from_grok_auth.py \\
--auth-json ~/.grok/auth.json \\
--out-dir ./cpa_auths
Then any agent can use CPA:
POST http://127.0.0.1:8317/v1/chat/completions model=grok-4.5
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
_ROOT = Path(__file__).resolve().parents[1]
if str(_ROOT) not in sys.path:
sys.path.insert(0, str(_ROOT))
from cpa_xai import ( # noqa: E402
DEFAULT_BASE_URL,
build_cpa_xai_auth,
write_cpa_xai_auth,
)
def load_grok_auth(path: Path) -> dict:
raw = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(raw, dict) or not raw:
raise SystemExit(f"empty or invalid auth.json: {path}")
# grok stores one top-level key: "https://auth.x.ai::<client_id>"
entry = next(iter(raw.values()))
if not isinstance(entry, dict):
raise SystemExit("auth.json entry is not an object")
return entry
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument(
"--auth-json",
default=str(Path.home() / ".grok" / "auth.json"),
help="Grok Build CLI auth.json path",
)
ap.add_argument(
"--out-dir",
default=str(_ROOT / "cpa_auths"),
help="Output dir for xai-*.json (register cpa_auths or CPA auth-dir)",
)
ap.add_argument(
"--base-url",
default=DEFAULT_BASE_URL,
help="Must be cli-chat-proxy for free Grok 4.5 promo",
)
ap.add_argument("--dry-run", action="store_true", help="Print JSON only, do not write")
args = ap.parse_args()
entry = load_grok_auth(Path(args.auth_json).expanduser())
access = entry.get("key") or entry.get("access_token") or ""
refresh = entry.get("refresh_token") or ""
email = entry.get("email") or ""
sub = entry.get("user_id") or entry.get("principal_id") or entry.get("sub") or ""
payload = build_cpa_xai_auth(
email=email,
access_token=access,
refresh_token=refresh,
sub=sub,
base_url=args.base_url,
)
if args.dry_run:
redacted = dict(payload)
for k in ("access_token", "refresh_token", "id_token"):
if k in redacted and isinstance(redacted[k], str) and redacted[k]:
v = redacted[k]
redacted[k] = v[:16] + f"...(len={len(v)})"
print(json.dumps(redacted, indent=2, ensure_ascii=False))
return 0
path = write_cpa_xai_auth(args.out_dir, payload)
print(f"wrote {path}")
print(f"email={payload.get('email')} base_url={payload.get('base_url')}")
print("CPA will hot-reload; test:")
print(' curl -sS http://127.0.0.1:8317/v1/models -H "Authorization: Bearer <CPA_KEY>" | grep grok-4.5')
return 0
if __name__ == "__main__":
raise SystemExit(main())
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env python3
"""Deprecated name — use scripts/import_nodes.py or:
python -m register_core nodes import <file>
"""
from __future__ import annotations
import runpy
import sys
from pathlib import Path
_HERE = Path(__file__).resolve().parent
print(
"[deprecated] import_clash_to_nodes.py → use scripts/import_nodes.py "
"or: python -m register_core nodes import …",
file=sys.stderr,
)
sys.argv[0] = str(_HERE / "import_nodes.py")
runpy.run_path(str(_HERE / "import_nodes.py"), run_name="__main__")
+849
View File
@@ -0,0 +1,849 @@
#!/usr/bin/env python3
"""Import a directory of xai-*.json into local cpa_auths + optional remote CPA.
Safety rules:
1) **Access-first**: reuse a still-valid access_token; do NOT refresh unless
access is expired/near-exp or models/chat return 401. Unconditional refresh
rotates RT and permanently revokes the previous one — that is the bug that
killed recoverable backups.
2) When refresh *is* required, ``ensure_auth_tokens`` / ``refresh_auth_file``
persist the new RT immediately and **re-read verify** before any probe.
3) Probe models + chat; only chat_ok may inject (product gate).
4) Never inject usage_exhausted / entitlement_denied / refresh-dead tokens.
5) After *any* live probe/import attempt (ok or fail), stamp the source auth as
tested/archived + append ledger so later runs skip used accounts.
6) Process in small batches (default 5) with a pause between batches to avoid
hammering Clash / token / chat endpoints.
Usage (project root):
uv run python -u scripts/import_cpa_auth_dir.py \\
--src /path/to/auth_dir \\
--proxy http://127.0.0.1:7897
# local only
uv run python -u scripts/import_cpa_auth_dir.py --src ./incoming --no-remote
# force token endpoint even when access still valid (ops only)
uv run python -u scripts/import_cpa_auth_dir.py --src ./incoming --force-refresh
# re-inject even if cpa_remote_injected stamp is set
uv run python -u scripts/import_cpa_auth_dir.py --src ./incoming --force-reinject
# batch size / pause (Clash-friendly; default 5 / 3s)
uv run python -u scripts/import_cpa_auth_dir.py --src ./incoming --batch-size 5 --batch-pause 3
"""
from __future__ import annotations
import argparse
import json
import os
import shutil
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
_ROOT = Path(__file__).resolve().parents[1]
if str(_ROOT) not in sys.path:
sys.path.insert(0, str(_ROOT))
from cpa_export import apply_multi_remote_inject, evaluate_remote_inject_gate # noqa: E402
from cpa_xai.probe import classify_chat_probe, probe_mini_response, probe_models # noqa: E402
from cpa_xai.refresh import ensure_auth_tokens # noqa: E402
from cpa_xai.schema import build_cpa_xai_auth # noqa: E402
from cpa_xai.writer import patch_cpa_xai_auth, write_cpa_xai_auth # noqa: E402
# On-disk product stamps + ledger. Auth files stay in cpa_auths (product count).
INJECTED_STAMP_KEY = "cpa_remote_injected"
INJECTED_AT_KEY = "cpa_remote_injected_at"
INJECTED_PATH_KEY = "cpa_remote_path"
TESTED_STAMP_KEY = "import_tested"
TESTED_AT_KEY = "import_tested_at"
TESTED_RESULT_KEY = "import_tested_result"
ARCHIVE_LEDGER_NAME = "cpa_import_archive.jsonl"
DEFAULT_ARCHIVE_DIR = "output/cpa_injected_archive"
DEFAULT_BATCH_SIZE = 5
DEFAULT_BATCH_PAUSE_SEC = 3.0
def _load_cfg(path: Path | None) -> dict:
p = path or (_ROOT / "config.json")
if not p.is_file():
return {}
try:
return json.loads(p.read_text(encoding="utf-8"))
except Exception:
return {}
def _config_bool(v, default=False): # noqa: ANN001
if v is None:
return default
if isinstance(v, bool):
return v
s = str(v).strip().lower()
if s in {"1", "true", "yes", "on", "y"}:
return True
if s in {"0", "false", "no", "off", "n", ""}:
return False
return default
def _is_auth_expired_response(probe: dict | None) -> bool:
"""Heuristic: models/chat probe failed due to expired/invalid access token."""
p = probe or {}
status = p.get("status") or p.get("http_status") or 0
try:
status_i = int(status)
except Exception:
status_i = 0
if status_i in {401, 403}:
# 403 may also be entitlement — only treat as auth if body hints token.
err = str(p.get("error") or p.get("body") or "").lower()
if status_i == 401:
return True
if any(
k in err
for k in (
"invalid_token",
"token expired",
"expired",
"unauthorized",
"access_token",
"jwt",
)
):
return True
err = str(p.get("error") or "").lower()
return any(
k in err
for k in (
"invalid_token",
"token expired",
"access token",
"unauthorized",
"jwt expired",
)
)
def _tokens_from_ensure(ref: dict) -> tuple[str, str, str, str]:
access = str(ref.get("access_token") or "")
refresh = str(ref.get("refresh_token") or "")
email = str(ref.get("email") or "")
id_token = str(ref.get("id_token") or "")
return access, refresh, email, id_token
def _read_auth_obj(path: Path) -> dict:
try:
data = json.loads(path.read_text(encoding="utf-8"))
except Exception:
return {}
return data if isinstance(data, dict) else {}
def _is_already_handled(path: Path) -> tuple[bool, dict, str]:
"""True when source was already injected or previously import-tested/archived."""
data = _read_auth_obj(path)
if data.get(INJECTED_STAMP_KEY) is True:
return True, data, "already_cpa_remote_injected"
if data.get("import_archived") is True and data.get("remote_live_ok") is True:
return True, data, "already_cpa_remote_injected"
# Any prior import attempt counts as used (ok or fail) — do not re-probe.
if data.get(TESTED_STAMP_KEY) is True or data.get("import_archived") is True:
return True, data, "already_import_tested"
return False, data, ""
def _is_already_injected(path: Path) -> tuple[bool, dict]:
"""Compat: injected-only check."""
handled, data, reason = _is_already_handled(path)
if handled and reason == "already_cpa_remote_injected":
return True, data
if data.get(INJECTED_STAMP_KEY) is True:
return True, data
return False, data
def _append_archive_ledger(
ledger_path: Path,
*,
email: str,
src_path: Path,
remote_path: str | None,
live_ok: bool,
inv_ok: bool | None,
extra: dict | None = None,
) -> None:
ledger_path.parent.mkdir(parents=True, exist_ok=True)
rec = {
"ts": datetime.now(timezone.utc).isoformat(),
"email": (email or "").strip().lower(),
"src": str(src_path),
"file": src_path.name,
"remote_path": remote_path or "",
"remote_live_ok": bool(live_ok),
"remote_inventory_ok": inv_ok,
"archived": True,
}
if extra:
for k, v in extra.items():
if k not in rec and v is not None:
rec[k] = v
with ledger_path.open("a", encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
f.flush()
try:
os.fsync(f.fileno())
except OSError:
pass
try:
os.chmod(ledger_path, 0o600)
except OSError:
pass
def _archive_copy(src_path: Path, archive_dir: Path) -> str | None:
"""Copy auth JSON into archive_dir (does not remove product file)."""
try:
archive_dir.mkdir(parents=True, exist_ok=True)
dest = archive_dir / src_path.name
shutil.copy2(src_path, dest)
try:
os.chmod(dest, 0o600)
except OSError:
pass
return str(dest)
except Exception:
return None
def _stamp_import_result(
src_path: Path,
local_path: Path | None,
*,
archive_dir: Path,
ledger_path: Path,
email: str,
result: dict,
) -> dict:
"""Stamp any import attempt (ok/fail) as tested+archived. Auth stays in cpa_auths.
Used accounts must not re-enter the import queue next run.
"""
now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
stage = str(result.get("stage") or "")
live_ok = bool(result.get("remote_live_ok"))
injected = live_ok and stage == "inject" and bool(result.get("ok"))
stamp = {
TESTED_STAMP_KEY: True,
TESTED_AT_KEY: now,
TESTED_RESULT_KEY: {
"ok": bool(result.get("ok")),
"stage": stage,
"error": str(result.get("error") or "")[:240],
"token_source": result.get("token_source"),
"chat_ok": result.get("chat_ok"),
"remote_live_ok": result.get("remote_live_ok"),
},
"import_archived": True,
"import_gate": result.get("import_gate")
or stage
or ("chat_ok" if result.get("chat_ok") else ""),
}
if injected:
stamp[INJECTED_STAMP_KEY] = True
stamp[INJECTED_AT_KEY] = now
stamp[INJECTED_PATH_KEY] = str(result.get("remote_path") or "")
stamp["remote_live_ok"] = True
stamp["remote_inventory_ok"] = result.get("remote_inventory_ok")
stamp["chat_ok"] = True
stamp["usable"] = True
stamp["import_gate"] = "chat_ok"
elif result.get("chat_ok") is False:
stamp["chat_ok"] = False
stamp["usable"] = False
if result.get("entitlement_denied") is not None:
stamp["entitlement_denied"] = bool(result.get("entitlement_denied"))
try:
patch_cpa_xai_auth(src_path, stamp)
except Exception as e: # noqa: BLE001
stamp["src_stamp_error"] = str(e)[:160]
if local_path and Path(local_path).is_file() and Path(local_path).resolve() != src_path.resolve():
try:
patch_cpa_xai_auth(Path(local_path), stamp)
except Exception as e: # noqa: BLE001
stamp["local_stamp_error"] = str(e)[:160]
arch = _archive_copy(src_path, archive_dir)
if arch:
stamp["archive_copy"] = arch
_append_archive_ledger(
ledger_path,
email=email or str(result.get("email") or ""),
src_path=src_path,
remote_path=str(result.get("remote_path") or ""),
live_ok=live_ok,
inv_ok=result.get("remote_inventory_ok"),
extra={
"archive_copy": arch,
"injected": injected,
"stage": stage,
"ok": bool(result.get("ok")),
"error": str(result.get("error") or "")[:240],
"token_source": result.get("token_source"),
"tested": True,
},
)
return stamp
def _stamp_injected(
src_path: Path,
local_path: Path | None,
*,
remote_path: str | None,
live_ok: bool,
inv_ok: bool | None,
archive_dir: Path,
ledger_path: Path,
email: str,
) -> dict:
"""Compat wrapper: successful live inject archive stamp."""
return _stamp_import_result(
src_path,
local_path,
archive_dir=archive_dir,
ledger_path=ledger_path,
email=email,
result={
"ok": True,
"stage": "inject",
"email": email,
"remote_live_ok": live_ok,
"remote_inventory_ok": inv_ok,
"remote_path": remote_path or "",
"chat_ok": True,
"import_gate": "chat_ok",
},
)
def import_one(
src_path: Path,
*,
out_dir: Path,
cfg: dict,
proxy: str | None,
remote: bool,
log,
force_refresh: bool = False,
force_reinject: bool = False,
skip_injected: bool = True,
archive_dir: Path | None = None,
ledger_path: Path | None = None,
) -> dict:
email_hint = src_path.name
rec: dict = {
"file": src_path.name,
"ts": datetime.now(timezone.utc).isoformat(),
}
# 0) Skip already-handled accounts (injected OR previously tested/archived).
if skip_injected and not force_reinject:
already, prev, skip_reason = _is_already_handled(src_path)
if already:
was_injected = skip_reason == "already_cpa_remote_injected" or bool(
prev.get(INJECTED_STAMP_KEY)
)
rec.update(
{
"ok": True,
"stage": "skip_injected" if was_injected else "skip_tested",
"email": str(prev.get("email") or email_hint),
"skipped": True,
"skip_reason": skip_reason or "already_handled",
"remote_live_ok": True if was_injected else prev.get("remote_live_ok"),
"chat_ok": prev.get("chat_ok"),
"remote_path": prev.get(INJECTED_PATH_KEY) or prev.get("remote_path"),
"injected_at": prev.get(INJECTED_AT_KEY),
"tested_at": prev.get(TESTED_AT_KEY),
"tested_result": prev.get(TESTED_RESULT_KEY),
}
)
return rec
# 1) Access-first: only hit token endpoint when access is dead / forced.
ref = ensure_auth_tokens(src_path, proxy=proxy, force_refresh=force_refresh)
rec["email"] = ref.get("email") or email_hint
rec["token_source"] = ref.get("source")
rec["refresh_rotated"] = bool(ref.get("refresh_rotated"))
rec["access_seconds_left"] = ref.get("access_seconds_left")
if not ref.get("ok"):
rec.update(
{
"ok": False,
"stage": "refresh" if ref.get("source") == "refresh" else "tokens",
"error": str(ref.get("error") or "")[:240],
"status": ref.get("status"),
"error_code": ref.get("error_code"),
}
)
return rec
access, refresh, email, id_token = _tokens_from_ensure(ref)
if not access or not refresh:
rec.update(
{
"ok": False,
"stage": "tokens",
"error": "missing access or refresh after ensure_auth_tokens",
}
)
return rec
# 2) Live usability probes with current access token.
models = probe_models(access, proxy=proxy)
# If access looked valid but upstream rejects auth → one forced refresh.
if not models.get("has_grok_45") and _is_auth_expired_response(models) and not force_refresh:
log(
f"[import] {email or email_hint}: models auth-fail → force refresh once"
)
ref2 = ensure_auth_tokens(src_path, proxy=proxy, force_refresh=True)
rec["token_source"] = f"{rec.get('token_source')}+retry_refresh"
rec["refresh_rotated"] = bool(ref2.get("refresh_rotated")) or rec["refresh_rotated"]
if not ref2.get("ok"):
rec.update(
{
"ok": False,
"stage": "refresh",
"error": str(ref2.get("error") or "retry refresh failed")[:240],
"status": ref2.get("status"),
"error_code": ref2.get("error_code"),
}
)
return rec
access, refresh, email, id_token = _tokens_from_ensure(ref2)
models = probe_models(access, proxy=proxy)
rec["models_has_grok_45"] = bool(models.get("has_grok_45"))
if not models.get("has_grok_45"):
rec.update(
{
"ok": False,
"stage": "models",
"chat_ok": False,
"usable": False,
"error": f"no grok-4.5 status={models.get('status')}",
}
)
return rec
ch = probe_mini_response(access, proxy=proxy)
if not ch.get("ok") and _is_auth_expired_response(ch) and not force_refresh:
# Access expired mid-flight (rare) — refresh once and re-probe chat only.
log(f"[import] {email or email_hint}: chat auth-fail → force refresh once")
ref3 = ensure_auth_tokens(src_path, proxy=proxy, force_refresh=True)
rec["token_source"] = f"{rec.get('token_source')}+chat_retry_refresh"
rec["refresh_rotated"] = bool(ref3.get("refresh_rotated")) or rec["refresh_rotated"]
if not ref3.get("ok"):
rec.update(
{
"ok": False,
"stage": "refresh",
"error": str(ref3.get("error") or "chat-retry refresh failed")[:240],
"status": ref3.get("status"),
"error_code": ref3.get("error_code"),
}
)
return rec
access, refresh, email, id_token = _tokens_from_ensure(ref3)
ch = probe_mini_response(access, proxy=proxy)
cls = classify_chat_probe(ch)
rec["chat_status"] = ch.get("status")
rec["chat_reason"] = cls.get("reason")
rec["chat_error_code"] = ch.get("error_code") or cls.get("error_code")
if not ch.get("ok"):
# still write local stamp for ops, but do not inject
try:
src_data = json.loads(src_path.read_text(encoding="utf-8"))
# Prefer disk RT (post ensure) over in-memory in case of partial.
disk_rt = str(src_data.get("refresh_token") or refresh)
disk_at = str(src_data.get("access_token") or access)
payload = build_cpa_xai_auth(
email=email,
access_token=disk_at,
refresh_token=disk_rt,
id_token=id_token or src_data.get("id_token") or "",
sub=str(src_data.get("sub") or ref.get("sub") or ""),
base_url=str(src_data.get("base_url") or ""),
priority=int(cfg.get("cpa_auth_priority") or src_data.get("priority") or 1000),
)
local_path = write_cpa_xai_auth(out_dir, payload)
gate_reason = str(cls.get("reason") or "chat_not_ok")
patch_cpa_xai_auth(
local_path,
{
"chat_ok": False,
"usable": False,
"entitlement_denied": bool(cls.get("entitlement_denied")),
"chat_retryable": bool(cls.get("retryable")),
"fail_reason": gate_reason,
"import_gate": gate_reason,
"chat_error_code": rec.get("chat_error_code") or "",
},
)
rec["path"] = str(local_path)
except Exception as e: # noqa: BLE001
rec["local_write_error"] = str(e)[:160]
rec.update(
{
"ok": False,
"stage": "chat",
"chat_ok": False,
"usable": False,
"error": (str(ch.get("error") or cls.get("reason") or "chat_failed"))[:240],
}
)
return rec
# 3) Write local CPA auth with chat_ok stamps — always from **disk** after ensure
# so we never invent a stale RT that differs from the authority file.
src_data = json.loads(src_path.read_text(encoding="utf-8"))
disk_rt = str(src_data.get("refresh_token") or refresh)
disk_at = str(src_data.get("access_token") or access)
if disk_rt != refresh:
# ensure refreshed but re-read diverged — trust disk, log.
log(
f"[import] WARN {email}: in-memory RT != disk after ensure; using disk"
)
refresh = disk_rt
if disk_at != access:
access = disk_at
payload = build_cpa_xai_auth(
email=email,
access_token=access,
refresh_token=refresh,
id_token=id_token or src_data.get("id_token") or "",
sub=str(src_data.get("sub") or ref.get("sub") or ""),
base_url=str(src_data.get("base_url") or ""),
priority=int(cfg.get("cpa_auth_priority") or src_data.get("priority") or 1000),
)
local_path = write_cpa_xai_auth(out_dir, payload)
patch_cpa_xai_auth(
local_path,
{
"chat_ok": True,
"usable": True,
"entitlement_denied": False,
"chat_retryable": False,
"import_gate": "chat_ok",
},
)
# Keep source stamps aligned too (no token rewrite — tokens already on source).
patch_cpa_xai_auth(
src_path,
{
"chat_ok": True,
"usable": True,
"entitlement_denied": False,
"chat_retryable": False,
"import_gate": "chat_ok",
},
)
result = {
"ok": True,
"path": str(local_path),
"email": email,
"chat_ok": True,
"usable": True,
"entitlement_denied": False,
"import_gate": "chat_ok",
}
gate = evaluate_remote_inject_gate(result, cfg, auth_path=local_path)
if not gate.get("allow"):
rec.update(
{
"ok": False,
"stage": "gate",
"path": str(local_path),
"chat_ok": True,
"error": gate.get("reason"),
}
)
return rec
if not remote:
rec.update(
{
"ok": True,
"stage": "local",
"path": str(local_path),
"chat_ok": True,
"usable": True,
"import_gate": "chat_ok",
"remote_skipped": True,
}
)
return rec
# 4) Remote inject under hard chat_ok gate.
inj = apply_multi_remote_inject(result, cfg, log_callback=log)
live_ok = inj.get("remote_live_ok")
inv_ok = inj.get("remote_inventory_ok")
rec.update(
{
"ok": bool(live_ok),
"stage": "inject",
"path": str(local_path),
"chat_ok": True,
"usable": True,
"import_gate": "chat_ok",
"remote_live_ok": live_ok,
"remote_inventory_ok": inv_ok,
"remote_path": inj.get("remote_path"),
"remote_error": inj.get("remote_inject_error"),
}
)
if not live_ok:
rec["ok"] = False
rec["error"] = (
inj.get("remote_inject_error")
or inj.get("remote_inject_skip_reason")
or "live inject failed"
)
# Archive/tested stamp happens in main for every non-skip attempt.
return rec
def _maybe_archive_attempt(
rec: dict,
src_path: Path,
*,
archive_dir: Path,
ledger_path: Path,
) -> dict:
"""Stamp+ledger+copy for any real attempt (not skip_*). Mutates rec."""
stage = str(rec.get("stage") or "")
if stage.startswith("skip_") or rec.get("skipped"):
return rec
local = Path(rec["path"]) if rec.get("path") else None
stamp_info = _stamp_import_result(
src_path,
local,
archive_dir=archive_dir,
ledger_path=ledger_path,
email=str(rec.get("email") or ""),
result=rec,
)
rec["archived"] = True
rec["tested"] = True
rec["archive_copy"] = stamp_info.get("archive_copy")
if stamp_info.get(INJECTED_AT_KEY):
rec[INJECTED_AT_KEY] = stamp_info.get(INJECTED_AT_KEY)
rec[TESTED_AT_KEY] = stamp_info.get(TESTED_AT_KEY)
return rec
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--src", required=True, help="Directory of xai-*.json")
ap.add_argument("--out-dir", default=str(_ROOT / "cpa_auths"))
ap.add_argument("--config", default=str(_ROOT / "config.json"))
ap.add_argument("--proxy", default="", help="Override proxy; default from config/env")
ap.add_argument("--no-remote", action="store_true", help="Skip tebi remote inject")
ap.add_argument(
"--remote",
action="store_true",
help=(
"Force tebi remote inject even when config.json has cpa_remote_inject=false "
"(batch-end / ops path; mint still stays inject-off)"
),
)
ap.add_argument(
"--force-refresh",
action="store_true",
help="Always hit token endpoint (default: reuse valid access, no RT rotation)",
)
ap.add_argument(
"--force-reinject",
action="store_true",
help="Re-inject even when cpa_remote_injected / import_tested stamp is set",
)
ap.add_argument(
"--no-skip-injected",
action="store_true",
help="Do not skip already-handled stamps (same as --force-reinject for skip gate)",
)
ap.add_argument(
"--archive-dir",
default="",
help=f"Copy tested/injected auths here (default: {_ROOT / DEFAULT_ARCHIVE_DIR})",
)
ap.add_argument(
"--batch-size",
type=int,
default=DEFAULT_BATCH_SIZE,
help=f"Accounts per batch before pause (default {DEFAULT_BATCH_SIZE}; 0=no batching)",
)
ap.add_argument(
"--batch-pause",
type=float,
default=DEFAULT_BATCH_PAUSE_SEC,
help=f"Seconds to sleep between batches (default {DEFAULT_BATCH_PAUSE_SEC})",
)
ap.add_argument("--limit", type=int, default=0)
args = ap.parse_args()
src = Path(args.src).expanduser().resolve()
out_dir = Path(args.out_dir).expanduser().resolve()
out_dir.mkdir(parents=True, exist_ok=True)
cfg = _load_cfg(Path(args.config).expanduser() if args.config else None)
proxy = (args.proxy or cfg.get("cpa_proxy") or cfg.get("proxy") or "").strip() or None
# Remote inject gate:
# --no-remote → always off
# --remote → force on (batch-end unified import; overrides prod disk-first config)
# else → follow config cpa_remote_inject
if args.no_remote:
remote = False
elif args.remote:
remote = True
else:
remote = _config_bool(cfg.get("cpa_remote_inject"), default=False)
cfg["cpa_remote_inject"] = remote
cfg["cpa_remote_inject_require_chat_ok"] = True
cfg["cpa_probe_chat"] = True
cfg["cpa_probe_chat_required"] = True
archive_dir = Path(args.archive_dir).expanduser() if args.archive_dir else (
_ROOT / DEFAULT_ARCHIVE_DIR
)
archive_dir = archive_dir.resolve()
ledger_path = out_dir / ARCHIVE_LEDGER_NAME
skip_injected = not (args.force_reinject or args.no_skip_injected)
batch_size = max(0, int(args.batch_size or 0))
batch_pause = max(0.0, float(args.batch_pause or 0.0))
files = sorted(src.glob("xai-*.json"))
if args.limit and args.limit > 0:
files = files[: args.limit]
if not files:
print(f"no xai-*.json under {src}", flush=True)
return 2
log_path = _ROOT / "logs" / f"import_auth_dir_{src.name}.jsonl"
state_path = _ROOT / "logs" / f"import_auth_dir_{src.name}_state.json"
log_path.parent.mkdir(parents=True, exist_ok=True)
def log(msg: str) -> None:
print(msg, flush=True)
print(
f"import src={src} n={len(files)} out={out_dir} remote={remote} "
f"force_refresh={bool(args.force_refresh)} skip_injected={skip_injected} "
f"batch_size={batch_size or 'off'} batch_pause={batch_pause}s "
f"archive={archive_dir} proxy={proxy or '(none)'}",
flush=True,
)
results: list[dict] = []
t0 = time.time()
attempted_in_batch = 0
batch_idx = 0
for i, p in enumerate(files, 1):
# Batch pause only counts non-skip attempts (real Clash/network work).
if batch_size > 0 and attempted_in_batch >= batch_size:
batch_idx += 1
log(
f"[import] batch {batch_idx} done (size={batch_size}); "
f"pause {batch_pause}s to ease Clash load"
)
if batch_pause > 0:
time.sleep(batch_pause)
attempted_in_batch = 0
rec = import_one(
p,
out_dir=out_dir,
cfg=cfg,
proxy=proxy,
remote=remote,
log=log,
force_refresh=bool(args.force_refresh),
force_reinject=bool(args.force_reinject),
skip_injected=skip_injected,
archive_dir=archive_dir,
ledger_path=ledger_path,
)
# Archive every real attempt (ok or fail) so the account is "used".
rec = _maybe_archive_attempt(
rec, p, archive_dir=archive_dir, ledger_path=ledger_path
)
if not rec.get("skipped"):
attempted_in_batch += 1
results.append(rec)
with log_path.open("a", encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
print(
f"[{i}/{len(files)}] {rec.get('email')}: ok={rec.get('ok')} "
f"stage={rec.get('stage')} src={rec.get('token_source')} "
f"live={rec.get('remote_live_ok')} rot={rec.get('refresh_rotated')} "
f"arch={rec.get('archived')} err={str(rec.get('error') or '')[:100]}",
flush=True,
)
ok_n = sum(1 for r in results if r.get("ok"))
state = {
"updated_at": datetime.now(timezone.utc).isoformat(),
"src": str(src),
"total": len(results),
"ok": ok_n,
"fail": len(results) - ok_n,
"live_ok": sum(1 for r in results if r.get("remote_live_ok")),
"inventory_ok": sum(1 for r in results if r.get("remote_inventory_ok")),
"chat_ok": sum(1 for r in results if r.get("chat_ok")),
"skipped_injected": sum(1 for r in results if r.get("stage") == "skip_injected"),
"skipped_tested": sum(1 for r in results if r.get("stage") == "skip_tested"),
"archived": sum(1 for r in results if r.get("archived")),
"tested": sum(1 for r in results if r.get("tested")),
"batch_size": batch_size,
"batch_pause_s": batch_pause,
"access_reuse": sum(1 for r in results if r.get("token_source") == "access_reuse"),
"refreshed": sum(
1
for r in results
if str(r.get("token_source") or "").startswith("refresh")
or "retry_refresh" in str(r.get("token_source") or "")
),
"refresh_fail": sum(
1 for r in results if r.get("stage") in {"refresh", "tokens"} and not r.get("ok")
),
"elapsed_s": round(time.time() - t0, 1),
"log": str(log_path),
"archive_dir": str(archive_dir),
"ledger": str(ledger_path),
"failed": [
{
"email": r.get("email"),
"stage": r.get("stage"),
"error": r.get("error"),
"token_source": r.get("token_source"),
}
for r in results
if not r.get("ok")
],
}
state_path.write_text(json.dumps(state, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print("=== STATE ===", flush=True)
print(json.dumps(state, ensure_ascii=False, indent=2), flush=True)
# Product exit: skip_* counts as ok; only hard fails pull exit=1.
return 0 if ok_n == len(results) else 1
if __name__ == "__main__":
raise SystemExit(main())
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""Import proxy profiles into project nodes (canonical script name).
Prefer:
python -m register_core nodes import path/to/profile.yaml
python -m register_core nodes validate path/to/profile.yaml
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
_ROOT = Path(__file__).resolve().parents[1]
if str(_ROOT) not in sys.path:
sys.path.insert(0, str(_ROOT))
from register_core.nodes.convert.cli_import import run_import # noqa: E402
from register_core.nodes.convert.types import DEFAULT_CONTROLLER, DEFAULT_MIXED_PORT # noqa: E402
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(
description="Import YAML / V2Ray JSON / URI into nodes.json + runtime.yaml"
)
ap.add_argument("paths", nargs="*", type=Path, help="profile files or dirs")
ap.add_argument("--format", default="", help="clash_yaml|v2ray_json|uri_list")
ap.add_argument("--dry-run", action="store_true")
ap.add_argument("--replace", action="store_true", help="replace nodes.json (default merge)")
ap.add_argument("--max-profile-proxies", type=int, default=400)
ap.add_argument("--mixed-port", type=int, default=DEFAULT_MIXED_PORT)
ap.add_argument("--controller", default=DEFAULT_CONTROLLER)
ap.add_argument("--nodes-home", type=Path, default=_ROOT / ".nodes")
ap.add_argument("--nodes-json", type=Path, default=_ROOT / "nodes.json")
ap.add_argument(
"--from-clash-verge",
action="store_true",
help="opt-in scan local Clash Verge profiles",
)
ap.add_argument("--clash-home", type=Path, default=None)
args = ap.parse_args(argv)
clash_home = args.clash_home
if args.from_clash_verge and clash_home is None:
clash_home = (
Path.home()
/ "Library/Application Support/io.github.clash-verge-rev.clash-verge-rev"
)
return run_import(
[str(p) for p in (args.paths or [])],
format_hint=args.format,
nodes_home=args.nodes_home,
nodes_json=args.nodes_json,
mixed_port=int(args.mixed_port),
controller=str(args.controller),
max_profile_proxies=int(args.max_profile_proxies),
dry_run=bool(args.dry_run),
replace_nodes=bool(args.replace),
from_clash_verge=bool(args.from_clash_verge),
clash_home=clash_home,
)
if __name__ == "__main__":
raise SystemExit(main())
+667
View File
@@ -0,0 +1,667 @@
#!/usr/bin/env bash
# Bulk Grok reg+mint disk supervisor on pxed (single-instance via flock).
# Restarts after fatal/exit until target new complete xai-*.json (access+refresh).
# Modes:
# residential — 1024proxy HTTP CONNECT only (家宽); --proxy-rotate off
# ordinary — Clash mixed-port leaf rotate (普通节点); --proxy-rotate clash
# Ordinary: healthy-only preflight before batch / after zero-gain;
# fail-fast Clash next-node on stuck; hybrid browser recycle (soft until recycle_every) via SUPERVISOR_CHUNK (default 3).
#
# CPA inject contract (disk-first):
# - Per-account mint path ALWAYS forces CPA_REMOTE_INJECT=false (never SSH mid-mint).
# - CPA_PROBE_CHAT is always false on mint path (disk-first; chat grant is external).
# - If inject intent is on (CPA_BATCH_END_INJECT / pre-freeze CPA_REMOTE_INJECT /
# config.json cpa_remote_inject), run unified healthy-only import only at
# batch boundaries — never after every single account:
# * every CPA_BATCH_IMPORT_EVERY new complete (default 100)
# * and once more after TARGET (remainder)
# - Import wave size inside the importer: CPA_BATCH_IMPORT_SIZE (default 100).
# - Watermark LAST_IMPORT_COMPLETE advances even on soft import failure so a
# flaky tebi import cannot spin and stall mint (product already on disk).
set -u
cd /personal/grok-register || exit 1
MODE=${1:-residential}
TARGET=${2:-100}
THREADS=${3:-1}
TAG_PREFIX=${4:-batch}
LOCK=/tmp/grok_batch_supervisor.lock
exec 9>"$LOCK"
if ! flock -n 9; then
echo "another supervisor holds $LOCK; exit"
exit 1
fi
# Prevent children (mihomo via preflight → start-clash) from inheriting the
# exclusive flock. Without CLOEXEC, a long-lived mihomo can hold fd 9 forever
# after the supervisor exits, blocking every subsequent launch.
if command -v python3 >/dev/null 2>&1; then
python3 -c 'import fcntl; fcntl.fcntl(9, fcntl.F_SETFD, fcntl.FD_CLOEXEC)' 2>/dev/null || true
fi
echo $$ > "${LOCK}.pid"
# ── Process-tree cleanup ────────────────────────────────────────────────
# A manually/externally launched supervisor is NOT a session leader (pid != pgid),
# so `kill -- -$$` does not reach the xvfb/Xvfb/python/clash children. SIGTERM from
# the control plane (or Ctrl-C) used to orphan those children — they kept ports
# 7897/9090/display bound and poisoned the next sub. Track the active foreground
# child PID (set by `run_child`) and on TERM/INT kill its whole process group,
# lenient of ESRCH (modeled on apps/control_api/process_registry._signal_tree).
ACTIVE_CHILD=""
kill_child_group() {
local pid="$1" sig="${2:-TERM}" pgid
[[ -z "$pid" ]] && return 0
if ! kill -0 "$pid" 2>/dev/null; then return 0; fi
pgid=$(ps -o pgid= -p "$pid" 2>/dev/null | tr -d ' ' || true)
if [[ -n "$pgid" && "$pgid" != "$$" ]]; then
kill "-$sig" -- -"$pgid" 2>/dev/null && return 0
fi
# ESRCH/bad pgid fallthrough → single pid
kill "-$sig" "$pid" 2>/dev/null || true
}
supervisor_cleanup() {
if [[ -n "$ACTIVE_CHILD" ]]; then
kill_child_group "$ACTIVE_CHILD" TERM
local i
for ((i = 0; i < 25; i++)); do # ~5s grace for graceful browser quit
kill -0 "$ACTIVE_CHILD" 2>/dev/null || break
sleep 0.2
done
if kill -0 "$ACTIVE_CHILD" 2>/dev/null; then
kill_child_group "$ACTIVE_CHILD" KILL
fi
fi
rm -f "${LOCK}.pid" 2>/dev/null || true
}
trap 'supervisor_cleanup; trap - EXIT; exit 130' INT
trap 'supervisor_cleanup; trap - EXIT; exit 143' TERM
trap 'supervisor_cleanup' EXIT
# Run a foreground child via xvfb-run / python and remember its pid for cleanup.
# Caller sets ACTIVE_CHILD="" again after the child has exited on its own.
run_child() {
"$@" &
ACTIVE_CHILD=$!
wait "$ACTIVE_CHILD"; local rc=$?
ACTIVE_CHILD=""
return $rc
}
TS0=$(date +%Y%m%d_%H%M%S)
RUN_TAG=${TAG_PREFIX}_${MODE}_${TARGET}_${TS0}
SUP_LOG=logs/${RUN_TAG}.supervisor.log
STATE=logs/${RUN_TAG}.state.json
IMPORT_LOG=logs/${RUN_TAG}.cpa_import.log
mkdir -p logs
RES_CREDS=(
"cchv57025-region-Rand-sid-itCWTF4X-t-5:tyfnvdhr"
"cchv57025-region-Rand-sid-7X3n2Kn1-t-5:tyfnvdhr"
"cchv57025-region-Rand-sid-tHzv1pL8-t-5:tyfnvdhr"
"cchv57025-region-Rand-sid-mzTjvSfh-t-5:tyfnvdhr"
"cchv57025-region-Rand-sid-bQ6kiCiJ-t-5:tyfnvdhr"
)
RES_HOST=us.1024proxy.io:3000
# Load .env as defaults only — never clobber keys already set by the control
# plane (start_run injects config.json → env) or the parent shell.
# Previously this overwrote EMAIL_PROVIDER etc., so console hotmail lost to a
# stale .env cloudflare line and the batch kept minting temp-mail addresses.
if [[ -f .env ]]; then
while IFS= read -r line || [ -n "$line" ]; do
case "$line" in ""|\#*) continue ;; esac
key=${line%%=*}
val=${line#*=}
# Skip if parent/control already exported this key (including empty).
if [[ -n "${key}" && -z "${!key+x}" ]]; then
export "$key=$val"
fi
done < .env
fi
# shellcheck source=/dev/null
source .venv/bin/activate
# Capture inject *intent* before freezing per-account inject off.
# Intent sources (any true wins): CPA_BATCH_END_INJECT, CPA_REMOTE_INJECT (env/.env),
# config.json cpa_remote_inject. Mint path still always uses false.
_truthy() {
case "${1:-}" in 1|true|TRUE|yes|YES|on|ON) return 0 ;; *) return 1 ;; esac
}
BATCH_CPA_INJECT_INTENT=false
if _truthy "${CPA_BATCH_END_INJECT:-}"; then
BATCH_CPA_INJECT_INTENT=true
elif _truthy "${CPA_REMOTE_INJECT:-}"; then
BATCH_CPA_INJECT_INTENT=true
elif [[ -f config.json ]] && .venv/bin/python - <<'PY'
import json, sys
from pathlib import Path
try:
c = json.loads(Path("config.json").read_text(encoding="utf-8"))
except Exception:
sys.exit(1)
v = c.get("cpa_remote_inject")
sys.exit(0 if v is True or str(v).lower() in {"1", "true", "yes", "on"} else 1)
PY
then
BATCH_CPA_INJECT_INTENT=true
fi
# Fallback only when neither control plane, parent, nor .env set a provider.
# Prefer config.json over the historical cloudflare hard-default so a console
# save that only touched config still wins on bare CLI launches.
if [[ -z "${EMAIL_PROVIDER:-}" ]]; then
if [[ -f config.json ]]; then
_cfg_ep=$(.venv/bin/python - <<'PY'
import json
from pathlib import Path
try:
c = json.loads(Path("config.json").read_text(encoding="utf-8"))
except Exception:
raise SystemExit(0)
v = str(c.get("email_provider") or "").strip()
if v:
print(v)
PY
)
if [[ -n "${_cfg_ep}" ]]; then
export EMAIL_PROVIDER="${_cfg_ep}"
fi
fi
fi
export EMAIL_PROVIDER=${EMAIL_PROVIDER:-cloudflare}
export CPA_EXPORT_ENABLED=true
export CPA_PROBE_CHAT=false
# Always freeze per-account remote inject during bulk mint (disk-first).
export CPA_REMOTE_INJECT=false
export PLAYWRIGHT_BROWSERS_PATH=${PLAYWRIGHT_BROWSERS_PATH:-/personal/browsers/ms-playwright}
# Ordinary mode preflights Clash leaves; residential sets SKIP=1 (1024proxy).
export SKIP_CLASH_PREFLIGHT=${SKIP_CLASH_PREFLIGHT:-0}
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY all_proxy || true
export NO_PROXY=127.0.0.1,localhost
export no_proxy=127.0.0.1,localhost
# Batch-boundary unified CPA import (healthy-only). Soft: never fails the mint batch.
# CPA_BATCH_IMPORT_SIZE = importer wave size (default 100).
# CPA_BATCH_IMPORT_EVERY = how many new complete auths between milestone imports (default 100).
run_batch_end_cpa_import() {
local why="${1:-target_reached}"
local batch_size="${CPA_BATCH_IMPORT_SIZE:-100}"
local batch_pause="${CPA_BATCH_IMPORT_PAUSE:-3}"
local proxy="${CPA_BATCH_IMPORT_PROXY:-http://127.0.0.1:7897}"
local cfg="${CPA_BATCH_IMPORT_CONFIG:-}"
local import_py=scripts/import_cpa_auth_dir.py
if [[ ! -f "$import_py" ]]; then
echo "[supervisor] batch-end import SKIP: missing $import_py why=$why" | tee -a "$SUP_LOG"
return 1
fi
# Prefer explicit import config; else production config.json (import --remote forces inject).
if [[ -z "$cfg" ]]; then
if [[ -f output/import_all_product_config.json ]]; then
cfg=output/import_all_product_config.json
else
cfg=config.json
fi
fi
echo "[supervisor] batch-end CPA import START why=$why cfg=$cfg batch=$batch_size pause=${batch_pause}s proxy=$proxy log=$IMPORT_LOG" | tee -a "$SUP_LOG"
set +e
# --remote: force live/inventory inject even if production config keeps cpa_remote_inject=false
# (mint path must stay inject-off; import is the only place that pushes tebi).
run_child .venv/bin/python -u "$import_py" \
--src cpa_auths \
--out-dir cpa_auths \
--config "$cfg" \
--proxy "$proxy" \
--remote \
--batch-size "$batch_size" \
--batch-pause "$batch_pause" \
>"$IMPORT_LOG" 2>&1
local ic=$?
set -e
if grep -q "=== STATE ===" "$IMPORT_LOG" 2>/dev/null; then
awk '/=== STATE ===/{p=1} p' "$IMPORT_LOG" | head -40 | tee -a "$SUP_LOG"
else
tail -20 "$IMPORT_LOG" | tee -a "$SUP_LOG"
fi
echo "[supervisor] batch-end CPA import DONE exit=$ic why=$why log=$IMPORT_LOG" | tee -a "$SUP_LOG"
return "$ic"
}
# Soft milestone import: only when intent on and enough new complete since last import.
maybe_milestone_cpa_import() {
local cur_complete="$1"
local why="${2:-milestone}"
if [[ "$BATCH_CPA_INJECT_INTENT" != "true" ]]; then
return 0
fi
local every="${CPA_BATCH_IMPORT_EVERY:-100}"
if ! [[ "$every" =~ ^[0-9]+$ ]] || (( every <= 0 )); then
every=100
fi
local gained_since=$((cur_complete - LAST_IMPORT_COMPLETE))
if (( gained_since < every )); then
return 0
fi
set +e
run_batch_end_cpa_import "${why}_every${every}_gained${gained_since}"
local ic=$?
set -e
# Advance watermark even on soft failure so import cannot spin and stall mint.
LAST_IMPORT_COMPLETE=$cur_complete
echo "[supervisor] milestone CPA import exit=$ic complete=$cur_complete last_import_at=$LAST_IMPORT_COMPLETE (soft)" | tee -a "$SUP_LOG"
return 0
}
baseline_count() {
.venv/bin/python - <<'PY'
import json
from pathlib import Path
need = ["access_token", "refresh_token", "email", "base_url", "token_endpoint", "headers"]
xs = list(Path("cpa_auths").glob("xai-*.json")) if Path("cpa_auths").exists() else []
complete = 0
for f in xs:
try:
j = json.loads(f.read_text())
except Exception:
continue
if all((j.get(k) or "") for k in need):
complete += 1
acc = sum(1 for l in Path("accounts_cli.txt").read_text().splitlines() if l.strip()) if Path("accounts_cli.txt").exists() else 0
print(f"{len(xs)} {complete} {acc}")
PY
}
run_clash_preflight() {
# Probe Clash leaves, rewrite GROK groups to healthy-only, restart mihomo.
local why="${1:-batch}"
if [[ "${SKIP_CLASH_PREFLIGHT:-0}" == "1" ]]; then
echo "[supervisor] preflight skipped SKIP_CLASH_PREFLIGHT=1 why=$why" | tee -a "$SUP_LOG"
return 0
fi
if [[ ! -f "$ROOT/preflight-clash-nodes.sh" ]]; then
echo "[supervisor] preflight script missing; skip why=$why" | tee -a "$SUP_LOG"
return 0
fi
echo "[supervisor] preflight-clash-nodes why=$why ..." | tee -a "$SUP_LOG"
set +e
run_child bash "$ROOT/preflight-clash-nodes.sh" >>"$SUP_LOG" 2>&1
local pc=$?
set -e
if [[ $pc -ne 0 ]]; then
echo "[supervisor] preflight exit=$pc why=$why (healthy=0?)" | tee -a "$SUP_LOG"
if [[ "${PREFLIGHT_REQUIRED:-0}" == "1" ]]; then
return "$pc"
fi
return 0
fi
echo "[supervisor] preflight OK why=$why" | tee -a "$SUP_LOG"
return 0
}
force_clash_next_node() {
# Lightweight path switch: advance dedicated GROK group to next leaf.
# When NODE_SCORE=1, prefer high-score / non-cooled; else classic round-robin.
set +e
.venv/bin/python - <<'PYN'
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(".").resolve()))
try:
from proxy_rotate import clash_list_nodes, clash_switch_node
except Exception as e:
print(f"[supervisor] force_clash_next import fail: {e}")
raise SystemExit(0)
cfg = json.loads(Path("config.json").read_text(encoding="utf-8"))
api = str(cfg.get("clash_api") or "http://127.0.0.1:9090")
secret = str(cfg.get("clash_secret") or "")
group = str(cfg.get("clash_proxy_group") or "GROK-REG")
excl = str(cfg.get("clash_node_exclude") or "")
incl = str(cfg.get("clash_node_include") or "")
try:
nodes, now, _ = clash_list_nodes(
api, group, secret=secret, exclude_re=excl, include_re=incl
)
except Exception as e:
print(f"[supervisor] force_clash_next list fail: {e}")
raise SystemExit(0)
if not nodes:
print("[supervisor] force_clash_next: empty pool")
raise SystemExit(0)
pick = "round_robin"
try:
import node_score as _ns
if _ns.scoring_enabled(cfg):
nxt = _ns.pick_next(nodes, now, cfg=cfg)
pick = "node_score"
else:
nxt = ""
except Exception:
nxt = ""
if not nxt or nxt not in nodes:
try:
idx = nodes.index(now)
nxt = nodes[(idx + 1) % len(nodes)]
except ValueError:
nxt = nodes[0]
pick = "round_robin"
# force_advanced UPSTREAM helper: keep parity with proxy_rotate._rotate_clash_locked
# force_advance branch — NEVER stay on the current leaf. pick_next returns `now`
# only when every other node is cooled and `now` is the sole active one; in that
# case pick the least-bad other node (cooled still beats the same known-dead
# leaf). Exit 3 signals the supervisor loop that the pool needs a reload rather
# than a silent no-op keeping the dead leaf.
def _force_advance(nodes, now, cfg):
try:
import node_score as _ns
return max([n for n in nodes if n != now], key=lambda n: _ns.get_score(n, cfg=cfg))
except Exception:
return None
if nxt == now:
others = [n for n in nodes if n != now]
if not others:
print(f"[supervisor] force_clash_next: pool has no node other than {now}; reload_needed", flush=True)
raise SystemExit(3)
nxt = _force_advance(nodes, now, cfg) or others[0]
pick = "force_advance_best_other"
if nxt == now:
print(f"[supervisor] force_clash_next: single node {now}")
raise SystemExit(0)
try:
clash_switch_node(api, group, nxt, secret=secret, flush=True)
print(f"[supervisor] force_clash_next: {now} -> {nxt} pool={len(nodes)} pick={pick}")
except Exception as e:
print(f"[supervisor] force_clash_next switch fail: {e}")
PYN
set -e
}
ROOT="$(pwd)"
read -r BASE_TOTAL BASE_COMPLETE BASE_ACC <<<"$(baseline_count)"
GOAL_COMPLETE=$((BASE_COMPLETE + TARGET))
# Watermark for milestone imports (only advances when a milestone import runs).
LAST_IMPORT_COMPLETE=$BASE_COMPLETE
CPA_IMPORT_EVERY=${CPA_BATCH_IMPORT_EVERY:-100}
if ! [[ "$CPA_IMPORT_EVERY" =~ ^[0-9]+$ ]] || (( CPA_IMPORT_EVERY <= 0 )); then
CPA_IMPORT_EVERY=100
fi
CPA_IMPORT_SIZE=${CPA_BATCH_IMPORT_SIZE:-100}
if ! [[ "$CPA_IMPORT_SIZE" =~ ^[0-9]+$ ]] || (( CPA_IMPORT_SIZE <= 0 )); then
CPA_IMPORT_SIZE=100
fi
export CPA_BATCH_IMPORT_EVERY=$CPA_IMPORT_EVERY
export CPA_BATCH_IMPORT_SIZE=$CPA_IMPORT_SIZE
{
echo "=== supervisor $RUN_TAG ==="
echo "start_utc=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "pid=$$ mode=$MODE target_new=$TARGET threads=$THREADS"
echo "baseline total=$BASE_TOTAL complete=$BASE_COMPLETE accounts=$BASE_ACC goal_complete=$GOAL_COMPLETE"
echo "CPA_PROBE_CHAT=false per_account_inject=false export=true (mint writes access+refresh)"
echo "batch_end_cpa_inject_intent=$BATCH_CPA_INJECT_INTENT (milestones every ${CPA_IMPORT_EVERY} new complete + remainder at TARGET; import wave size=${CPA_IMPORT_SIZE})"
echo "success criterion: new complete xai-*.json with refresh_token (not chat_ok)"
echo "lock=flock $LOCK (no inter-sub pkill)"
} | tee "$SUP_LOG"
echo "{\"baseline_complete\":$BASE_COMPLETE,\"target_new\":$TARGET,\"goal_complete\":$GOAL_COMPLETE,\"mode\":\"$MODE\",\"pid\":$$,\"batch_end_cpa_inject\":$BATCH_CPA_INJECT_INTENT,\"cpa_batch_import_every\":$CPA_IMPORT_EVERY,\"cpa_batch_import_size\":$CPA_IMPORT_SIZE}" > "$STATE"
attempt=0
# Turnstile fatals kill whole register_cli after partial gains (~0.5–2 complete/sub).
# Fixed 200 caps ~+150 on ordinary; scale with TARGET (override: SUPERVISOR_MAX_ATTEMPTS).
if [[ -n "${SUPERVISOR_MAX_ATTEMPTS:-}" ]]; then
max_attempts=$SUPERVISOR_MAX_ATTEMPTS
else
max_attempts=$((TARGET * 4))
if (( max_attempts < 400 )); then max_attempts=400; fi
if (( max_attempts > 8000 )); then max_attempts=8000; fi
fi
# 12h default was tight for 1k; 36h + env override.
deadline=$(( $(date +%s) + ${SUPERVISOR_DEADLINE_HOURS:-36}*3600 ))
consecutive_zero=0
HIT_TARGET=0
echo "[supervisor] max_attempts=$max_attempts deadline_hours=${SUPERVISOR_DEADLINE_HOURS:-36}" | tee -a "$SUP_LOG"
while true; do
now=$(date +%s)
if (( now > deadline )); then
echo "[supervisor] deadline reached" | tee -a "$SUP_LOG"
break
fi
read -r CUR_TOTAL CUR_COMPLETE CUR_ACC <<<"$(baseline_count)"
NEW=$((CUR_COMPLETE - BASE_COMPLETE))
echo "[supervisor] $(date -u +%H:%M:%SZ) complete=$CUR_COMPLETE (+$NEW/$TARGET) accounts=$CUR_ACC attempt=$attempt" | tee -a "$SUP_LOG"
if (( CUR_COMPLETE >= GOAL_COMPLETE )); then
echo "[supervisor] TARGET REACHED +$NEW complete auths" | tee -a "$SUP_LOG"
HIT_TARGET=1
break
fi
if (( attempt >= max_attempts )); then
echo "[supervisor] max_attempts=$max_attempts" | tee -a "$SUP_LOG"
break
fi
attempt=$((attempt + 1))
remain=$((GOAL_COMPLETE - CUR_COMPLETE))
# chunk=1 kills in-process browser reuse. ordinary default 3 (SUPERVISOR_CHUNK).
# Turnstile fatal still stops whole register_cli; smaller remain handled below.
if [[ "$MODE" == "residential" ]]; then
chunk=${SUPERVISOR_CHUNK:-2}
else
chunk=${SUPERVISOR_CHUNK:-3}
fi
if (( remain < chunk )); then chunk=$remain; fi
if (( chunk < 1 )); then chunk=1; fi
SUB_TS=$(date +%Y%m%d_%H%M%S)
SUB_LOG=logs/${RUN_TAG}.sub${attempt}_${SUB_TS}.log
# Per-mode register_cli flags. CRITICAL: CLI --proxy-rotate overrides env/config
# (register_cli: CLI > config > env). Residential MUST pass off or clash leaf
# rotation steals egress even when PROXY is 1024proxy CONNECT.
PROXY_ROTATE_CLI=clash
PROXY_ROTATE_EVERY_CLI=1
if [[ "$MODE" == "residential" ]]; then
idx=$(( (attempt - 1) % ${#RES_CREDS[@]} ))
cred=${RES_CREDS[$idx]}
user=${cred%%:*}
pass=${cred#*:}
export PROXY="http://${user}:${pass}@${RES_HOST}"
export CPA_PROXY="$PROXY"
# Front tunnel is optional fallback only; egress is 1024 CONNECT above.
# Do NOT enable Clash domain-group rotation — that was the residential bug.
unset REGISTER_FRONT_PROXY FRONT_PROXY || true
export PROXY_ROTATE_MODE=off
export SKIP_CLASH_PREFLIGHT=1
export NODE_SCORE=0
PROXY_ROTATE_CLI=off
PROXY_ROTATE_EVERY_CLI=1
echo "[supervisor] sub=$attempt chunk=$chunk mode=residential egress=1024proxy sid_idx=$idx host=${RES_HOST} rotate=off" | tee -a "$SUP_LOG"
else
export PROXY=http://127.0.0.1:7897
export CPA_PROXY=http://127.0.0.1:7897
unset REGISTER_FRONT_PROXY FRONT_PROXY || true
export PROXY_ROTATE_MODE=clash
# Dynamic egress weight (Turnstile fail cool / mint success boost).
# Default ON for ordinary bulk; set NODE_SCORE=0 to force classic round-robin.
export NODE_SCORE=${NODE_SCORE:-1}
export NODE_SCORE_PATH=${NODE_SCORE_PATH:-output/node_scores.json}
export SKIP_CLASH_PREFLIGHT=${SKIP_CLASH_PREFLIGHT_ORDINARY:-0}
PROXY_ROTATE_CLI=clash
PROXY_ROTATE_EVERY_CLI=1
# Node detection: healthy-only before first ordinary sub, and after zero-gain.
if (( attempt == 1 || consecutive_zero >= 1 )); then
if (( consecutive_zero >= 2 )); then
run_clash_preflight "ordinary_sub${attempt}_zero${consecutive_zero}"
elif (( attempt == 1 )); then
run_clash_preflight "ordinary_batch_start"
else
force_clash_next_node
if (( $? == 3 )); then
echo "[supervisor] force_clash_next reload_needed → preflight" | tee -a "$SUP_LOG"
run_clash_preflight "force_advance_reload_sub${attempt}"
fi
fi
fi
echo "[supervisor] sub=$attempt chunk=$chunk mode=ordinary clash_rotate zero=$consecutive_zero" | tee -a "$SUP_LOG"
fi
export CPA_EXPORT_ENABLED=true
export CPA_PROBE_CHAT=false
export CPA_REMOTE_INJECT=false
# PKCE consent_action_missing is currently 100% fail — skip to browser residual.
export CPA_PREFER_PROTOCOL=false
before_complete=$CUR_COMPLETE
# Do NOT pkill leftover register_cli here — that races multi-instance and kills live work.
# We await each sub to completion; only one sub runs at a time under flock.
set +e
# slot-retry>=1: browser_boot/ERR_CONNECTION_CLOSED can force-rotate + retry
# (ordinary/clash only; residential rotate=off → force-rotate is a no-op).
SLOT_RETRY=${ACCOUNT_SLOT_RETRY:-2}
# Fingerprint: off|light|anon.
# light/anon UA pool major must match CFT Chromium (149); spoofed older majors
# break Turnstile passive tokens. anon = light + hard recycle every account
# (fresh auto_port profile; no --incognito).
# Override: BROWSER_FINGERPRINT_MODE=off|light|anon
# Default off: known-good Turnstile path on pxed (anon was 0/N token_len=0).
FP_MODE=${BROWSER_FINGERPRINT_MODE:-off}
case "$FP_MODE" in
off|light|anon) ;;
anonymous|incognito|guest|private) FP_MODE=anon ;;
*) FP_MODE=off ;;
esac
# anon forces hard recycle inside register_cli; hybrid only applies for off/light.
RECYCLE_MODE=${BROWSER_RECYCLE_MODE:-hybrid}
if [[ "$FP_MODE" == "anon" ]]; then
RECYCLE_MODE=hard
fi
run_child xvfb-run -a -s "-screen 0 1280x900x24 -ac +extension GLX +render -noreset" \
python -u register_cli.py --extra "$chunk" --threads "$THREADS" --no-headless --fast \
--account-slot-retry "$SLOT_RETRY" \
--browser-recycle-mode "$RECYCLE_MODE" \
--browser-fingerprint-mode "$FP_MODE" \
--proxy-rotate "$PROXY_ROTATE_CLI" --proxy-rotate-every "$PROXY_ROTATE_EVERY_CLI" \
>"$SUB_LOG" 2>&1
code=$?
set -e
echo "[supervisor] sub=$attempt exit=$code log=$SUB_LOG rotate=${PROXY_ROTATE_CLI}" | tee -a "$SUP_LOG"
if grep -qE "SUMMARY_JSON|=== 完成|Fatal|FAIL-FAST|wrote |注册成功" "$SUB_LOG" 2>/dev/null; then
grep -E "SUMMARY_JSON|=== 完成|注册成功|Fatal|FAIL-FAST|wrote |token_ok" "$SUB_LOG" | tail -12 | tee -a "$SUP_LOG"
else
tail -12 "$SUB_LOG" | tee -a "$SUP_LOG"
fi
# Outlook artifact accounting (disjoint from the xai-*.json CPA pool).
# OutlookProvider writes private 0600 outlook-*.json under outlook_auths/;
# the count here is informational only and MUST NOT feed CPA import. The
# glob is strictly outlook-*.json over outlook_auths, never xai-*.json
# over cpa_auths, so the two products can never share a glob or directory.
outlook_auths_dir="${OUTLOOK_AUTHS_DIR:-outlook_auths}"
if [ -d "$outlook_auths_dir" ]; then
outlook_count=$(find "$outlook_auths_dir" -maxdepth 1 -type f -name 'outlook-*.json' | wc -l | tr -d ' ')
else
outlook_count=0
fi
echo "OUTLOOK_AUTH_COUNT=$outlook_count dir=$outlook_auths_dir" | tee -a "$SUP_LOG"
read -r _ AFTER_COMPLETE _ <<<"$(baseline_count)"
gained=$((AFTER_COMPLETE - before_complete))
if (( gained <= 0 )); then
consecutive_zero=$((consecutive_zero + 1))
else
consecutive_zero=0
fi
echo "[supervisor] sub=$attempt gained_complete=$gained consecutive_zero=$consecutive_zero" | tee -a "$SUP_LOG"
# Milestone CPA import only when intent on and every N new complete (default 100).
# Never per-account / never every sub; mint path stays inject-off.
if (( gained > 0 )); then
maybe_milestone_cpa_import "$AFTER_COMPLETE" "sub${attempt}"
fi
# Fail-fast path switch on zero-gain (ordinary): do not only sleep on dead nodes.
if (( consecutive_zero >= 1 )) && [[ "$MODE" == "ordinary" ]]; then
if (( consecutive_zero >= 3 )); then
run_clash_preflight "post_sub_zero${consecutive_zero}"
else
force_clash_next_node
if (( $? == 3 )); then
echo "[supervisor] post_sub_zero${consecutive_zero} force_clash_next reload_needed → preflight" | tee -a "$SUP_LOG"
run_clash_preflight "post_sub_zero_reload${consecutive_zero}"
fi
fi
fi
if (( consecutive_zero >= 8 )); then
sleep 20
elif (( consecutive_zero >= 4 )); then
sleep 8
elif (( consecutive_zero >= 2 )); then
sleep 4
else
sleep 2
fi
done
read -r END_TOTAL END_COMPLETE END_ACC <<<"$(baseline_count)"
NEW=$((END_COMPLETE - BASE_COMPLETE))
{
echo "=== supervisor done $(date -u +%Y-%m-%dT%H:%M:%SZ) ==="
echo "mode=$MODE new_complete=$NEW target=$TARGET final_complete=$END_COMPLETE accounts=$END_ACC hit_target=$HIT_TARGET"
echo "batch_end_cpa_inject_intent=$BATCH_CPA_INJECT_INTENT"
echo "STATE=$STATE SUP_LOG=$SUP_LOG"
} | tee -a "$SUP_LOG"
.venv/bin/python - <<PY | tee -a "$SUP_LOG"
import json
from pathlib import Path
sup = Path("$SUP_LOG")
start = sup.stat().st_mtime if sup.exists() else 0
need = ["access_token", "refresh_token", "email", "base_url", "token_endpoint", "headers"]
new, bad = [], []
for f in Path("cpa_auths").glob("xai-*.json"):
if f.stat().st_mtime < start - 2:
continue
try:
j = json.loads(f.read_text())
except Exception as e:
bad.append((f.name, str(e))); continue
miss = [k for k in need if not j.get(k)]
if miss:
bad.append((f.name, miss))
else:
new.append(f.name)
print(f"audit_new_complete={len(new)} bad={len(bad)}")
if bad[:5]:
print("bad_sample", bad[:5])
if new[:5]:
print("new_sample", new[:5])
PY
# Final remainder import after TARGET (or leftover if intent on and some new complete).
# Milestones already imported every CPA_BATCH_IMPORT_EVERY; this only covers remainder.
if [[ "$BATCH_CPA_INJECT_INTENT" == "true" ]]; then
remainder=$((END_COMPLETE - LAST_IMPORT_COMPLETE))
if (( remainder > 0 )); then
if (( HIT_TARGET == 1 )); then
why="target_reached_remainder${remainder}"
else
why="batch_stop_remainder${remainder}"
fi
set +e
run_batch_end_cpa_import "$why"
IMPORT_EXIT=$?
set -e
LAST_IMPORT_COMPLETE=$END_COMPLETE
# Soft: import failure must not rewrite disk-first success of the batch.
echo "[supervisor] batch-end import exit=$IMPORT_EXIT why=$why (soft; mint product already on disk)" | tee -a "$SUP_LOG"
else
echo "[supervisor] batch-end CPA import SKIP: no remainder since last milestone (last_import_at=$LAST_IMPORT_COMPLETE complete=$END_COMPLETE hit_target=$HIT_TARGET)" | tee -a "$SUP_LOG"
fi
else
echo "[supervisor] batch-end CPA import SKIP: intent=false (set CPA_BATCH_END_INJECT=true or config cpa_remote_inject)" | tee -a "$SUP_LOG"
fi
+634
View File
@@ -0,0 +1,634 @@
#!/usr/bin/env python3
"""Probe mihomo leaf proxies via controller delay API; filter dead from GROK groups.
Production authority for **Grok on Clash mixed-port** (pxed default):
bash preflight-clash-nodes.sh → this script --apply-config → restart mihomo
This is **not** the monorepo ``nodes.json`` / ``preflight_nodes_for_register`` path
(list|auto). Both strip dead leaves before batch work; backends differ.
Usage:
python3 scripts/probe_clash_nodes.py # probe + select
python3 scripts/probe_clash_nodes.py --dry-run # probe only
python3 scripts/probe_clash_nodes.py --apply-config # rewrite config groups
python3 scripts/probe_clash_nodes.py --rounds 3 --purge-proxies --apply-config
# 3× delay probe; only leaves that fail ALL rounds are dead;
# --purge-proxies also drops them from proxies: (not just group lists)
Env:
CLASH_DIR default /personal/clash
CLASH_API default http://127.0.0.1:9090
CLASH_REPORT_DIR default <repo>/output
CLASH_CONFIG override config.yaml path
CLASH_MERGED override config.mac-merged.yaml path
"""
from __future__ import annotations
import argparse
import concurrent.futures
import json
import os
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
_REPO = Path(__file__).resolve().parents[1]
CLASH_DIR = Path(os.environ.get("CLASH_DIR") or "/personal/clash")
CFG = Path(os.environ.get("CLASH_CONFIG") or (CLASH_DIR / "config.yaml"))
MERGED = Path(
os.environ.get("CLASH_MERGED") or (CLASH_DIR / "config.mac-merged.yaml")
)
SECRET_FILE = CLASH_DIR / ".controller-secret"
API = (os.environ.get("CLASH_API") or "http://127.0.0.1:9090").rstrip("/")
REPORT_DIR = Path(
os.environ.get("CLASH_REPORT_DIR") or (_REPO / "output")
)
DEFAULT_URL = "http://www.gstatic.com/generate_204"
DEFAULT_TIMEOUT_MS = 5000
# 每族 .pre-health-* 备份保留份数。不清理会无界增长: 每轮写 2 份,
# 曾累积 1300+ 份 / 343MB 把 /personal/clash 撑到 579MB。
_BAK_RETAIN = int(os.environ.get("CLASH_BAK_RETAIN") or 20)
GROUP_TYPES = {
"Selector",
"URLTest",
"Fallback",
"LoadBalance",
"Relay",
"Direct",
"Reject",
"Compatible",
"Pass",
"PassRule",
"RejectDrop",
}
# Groups whose leaf lists we rewrite to healthy-only for register batches
REGISTER_GROUPS = ("🎯Grok注册", "♻️Grok优选", "PROXY", "🔰ChatGPT")
# Dog VPS (35.212.179.13 / mango9502) + hairpin dialer leaves — traffic-precious,
# never front-load into Grok register rotate pool. Prefer residential 家宽 instead.
REGISTER_POOL_EXCLUDE = (
"GVPS-AnyTLS-googlevps",
"GVPS-TUIC-googlevps",
)
REGISTER_POOL_EXCLUDE_RE = re.compile(
r"GVPS-AnyTLS-googlevps|GVPS-TUIC-googlevps|googlevps|P1024-"
)
# Prefer these markers (substring) at front of register groups when healthy
PREFERRED_MARKERS = ("家宽",)
# Legacy explicit names (still preferred if healthy and not excluded)
PREFERRED = (
"GVPS-VLESS-CF-LSJ",
"GVPS-VLESS-CF-DLD",
)
def load_secret() -> str:
"""Load controller secret from config.yaml or CLASH_DIR/.controller-secret.
Never embed a default secret in the repo — missing secret is a hard error.
"""
if CFG.is_file():
text = CFG.read_text(encoding="utf-8")
m = re.search(r'^secret:\s*["\']?([^"\'\n]+)', text, re.M)
if m:
secret = m.group(1).strip()
if secret:
return secret
if SECRET_FILE.is_file():
secret = SECRET_FILE.read_text(encoding="utf-8").strip()
if secret:
return secret
raise SystemExit(
f"ERROR: mihomo controller secret not found "
f"(set secret: in {CFG} or write {SECRET_FILE})"
)
def api_request(
path: str, secret: str, method: str = "GET", data: bytes | None = None
) -> Any:
req = urllib.request.Request(
f"{API}{path}",
data=data,
method=method,
headers={
"Authorization": f"Bearer {secret}",
"Content-Type": "application/json",
},
)
with urllib.request.urlopen(req, timeout=180) as resp:
body = resp.read()
if not body:
return None
return json.loads(body.decode())
def list_leaves(secret: str) -> list[str]:
data = api_request("/proxies", secret)
prox = data.get("proxies") or {}
leaves: list[str] = []
for name, info in prox.items():
t = info.get("type") or ""
if t in GROUP_TYPES:
continue
if name in ("DIRECT", "REJECT", "PASS", "COMPATIBLE"):
continue
leaves.append(name)
return sorted(leaves)
def probe_one(
name: str, secret: str, timeout_ms: int, url: str
) -> tuple[str, int | None, str]:
q = urllib.parse.urlencode({"timeout": timeout_ms, "url": url})
path = f"/proxies/{urllib.parse.quote(name, safe='')}/delay?{q}"
try:
data = api_request(path, secret)
delay = data.get("delay") if isinstance(data, dict) else None
if isinstance(delay, int) and delay > 0:
return name, delay, "ok"
return name, None, f"no_delay:{data!r}"
except urllib.error.HTTPError as e:
try:
body = e.read().decode(errors="replace")
except Exception:
body = str(e)
return name, None, f"http_{e.code}:{body[:120]}"
except Exception as e:
return name, None, f"{type(e).__name__}:{e}"
def probe_all(
names: list[str],
secret: str,
timeout_ms: int,
url: str,
workers: int,
) -> dict[str, dict[str, Any]]:
results: dict[str, dict[str, Any]] = {}
total = len(names)
done = 0
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as ex:
futs = {
ex.submit(probe_one, n, secret, timeout_ms, url): n for n in names
}
for fut in concurrent.futures.as_completed(futs):
name, delay, status = fut.result()
results[name] = {
"delay_ms": delay,
"status": status,
"ok": delay is not None,
}
done += 1
if done % 10 == 0 or done == total:
ok_n = sum(1 for v in results.values() if v["ok"])
print(f" progress {done}/{total} ok={ok_n}", flush=True)
return results
def classify(name: str) -> str:
if name.startswith("IK-"):
return "ikuuu"
if name.startswith("BK-"):
return "pokemon"
if name.startswith("GVPS-"):
return "gvps"
return "other"
def put_group_now(secret: str, group: str, node: str) -> None:
path = f"/proxies/{urllib.parse.quote(group, safe='')}"
body = json.dumps({"name": node}).encode()
try:
api_request(path, secret, method="PUT", data=body)
print(f" set {group} -> {node}")
except Exception as e:
print(f" WARN set {group}: {e}")
def _leaf_ok(r: dict[str, Any], max_latency_ms: int) -> bool:
d = r.get("delay_ms")
return bool(r.get("ok")) and isinstance(d, int) and d > 0 and d <= max_latency_ms
def _require_yaml():
try:
import yaml # type: ignore
except ImportError as exc:
raise SystemExit(
"PyYAML required for --apply-config / --purge-proxies "
"(use repo .venv: .venv/bin/python scripts/probe_clash_nodes.py …)"
) from exc
return yaml
def _backup_and_dump(cfg_path: Path, text: str, data: dict, header_note: str) -> Path:
yaml = _require_yaml()
ts = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
bak = cfg_path.with_suffix(cfg_path.suffix + f".pre-health-{ts}")
bak.write_text(text, encoding="utf-8")
# 每轮 --apply-config 写 2 份备份 (config.yaml + merged), 不清理会无界增长:
# 曾在 /personal/clash 累积 1300+ 份 / 343MB。只删同族(.pre-health-)最旧的。
try:
fam = sorted(cfg_path.parent.glob(cfg_path.name + ".pre-health-*"))
for stale in fam[:-_BAK_RETAIN]:
stale.unlink()
except OSError:
pass
class NoAliasDumper(yaml.SafeDumper):
def ignore_aliases(self, data): # type: ignore[no-untyped-def]
return True
header = ""
if text.lstrip().startswith("#"):
lines = text.splitlines(keepends=True)
buf: list[str] = []
for ln in lines:
if ln.startswith("#") or ln.strip() == "":
buf.append(ln)
if len(buf) > 20:
break
else:
break
header = "".join(buf)
if header and not header.endswith("\n"):
header += "\n"
header += f"# {header_note}\n"
body = yaml.dump(
data,
Dumper=NoAliasDumper,
allow_unicode=True,
sort_keys=False,
width=120,
default_flow_style=False,
)
cfg_path.write_text(header + body, encoding="utf-8")
print(f" wrote {cfg_path} (bak {bak.name})")
return bak
def rewrite_config_groups(
cfg_path: Path,
healthy: list[str],
preferred_first: list[str],
) -> Path:
"""Rewrite proxy-groups leaf lists for register-related groups; backup first."""
yaml = _require_yaml()
text = cfg_path.read_text(encoding="utf-8")
data = yaml.safe_load(text)
ordered = list(preferred_first) + [
n for n in healthy if n not in preferred_first
]
groups = data.get("proxy-groups") or []
healthy_set = set(healthy)
for g in groups:
name = g.get("name")
if name not in REGISTER_GROUPS:
continue
old = list(g.get("proxies") or [])
if g.get("type") == "url-test":
g["proxies"] = ordered[:] if ordered else old
else:
# select groups keep their curated member list (e.g. the 17-node
# per-exit-IP trim) — strip only leaves dead in every round and
# preserve order, so rotation still hits distinct exit IPs. Fall
# back to the full healthy pool only when nothing survives.
new = [m for m in old if m in healthy_set]
if not new:
new = ordered[:]
for m in ("♻️Grok优选", "DIRECT"):
if m not in new and m in old:
new.append(m)
g["proxies"] = new if new else ["DIRECT"]
print(f" group {name}: {len(old)} -> {len(g['proxies'])}")
ts = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
return _backup_and_dump(
cfg_path,
text,
data,
f"health-filter {ts} healthy={len(healthy)} "
f"dead_stripped_from {','.join(REGISTER_GROUPS)}",
)
def purge_dead_proxies(
cfg_path: Path,
dead: list[str],
) -> Path:
"""Delete all-fail leaves from proxies: and every group list. Backup first.
Safer than only rewriting REGISTER_GROUPS: dead leaves cannot re-enter via
other selectors after mihomo reload.
"""
yaml = _require_yaml()
dead_set = {n for n in dead if n}
if not dead_set:
print(f" purge {cfg_path}: nothing to delete")
return cfg_path
text = cfg_path.read_text(encoding="utf-8")
data = yaml.safe_load(text)
proxies = data.get("proxies") or []
before = len(proxies)
kept = []
removed_names: list[str] = []
for p in proxies:
if not isinstance(p, dict):
kept.append(p)
continue
name = str(p.get("name") or "")
if name in dead_set:
removed_names.append(name)
continue
kept.append(p)
data["proxies"] = kept
stripped_groups = 0
for g in data.get("proxy-groups") or []:
old = list(g.get("proxies") or [])
new = [n for n in old if n not in dead_set]
if len(new) != len(old):
stripped_groups += 1
g["proxies"] = new if new else ["DIRECT"]
ts = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
print(
f" purge {cfg_path.name}: proxies {before}->{len(kept)} "
f"removed={len(removed_names)} groups_touched={stripped_groups}"
)
if removed_names[:12]:
for n in removed_names[:12]:
print(f" - {n}")
if len(removed_names) > 12:
print(f" … +{len(removed_names) - 12} more")
return _backup_and_dump(
cfg_path,
text,
data,
f"purge-dead {ts} removed={len(removed_names)} "
f"proxies {before}->{len(kept)}",
)
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--url", default=DEFAULT_URL)
ap.add_argument("--timeout-ms", type=int, default=DEFAULT_TIMEOUT_MS)
ap.add_argument("--workers", type=int, default=12)
ap.add_argument(
"--rounds",
type=int,
default=1,
help="probe each leaf this many times; dead = failed ALL rounds "
"(default 1; use 3 to only purge stable dead)",
)
ap.add_argument(
"--dry-run",
action="store_true",
help="probe only, no group select / config write",
)
ap.add_argument(
"--apply-config",
action="store_true",
help="rewrite config.yaml + merged yaml groups to healthy leaves",
)
ap.add_argument(
"--purge-proxies",
action="store_true",
help="delete leaves that failed ALL rounds from proxies: + all groups "
"(stronger than group rewrite alone)",
)
ap.add_argument(
"--select",
default="",
help="force group selection to this node if healthy",
)
ap.add_argument(
"--max-latency-ms",
type=int,
default=4500,
help="treat delay above this as dead",
)
args = ap.parse_args()
rounds = max(1, int(args.rounds or 1))
secret = load_secret()
print(
f"clash_dir={CLASH_DIR} api={API} secret_len={len(secret)} "
f"url={args.url} timeout_ms={args.timeout_ms} rounds={rounds}"
)
leaves = list_leaves(secret)
print(f"leaves={len(leaves)}")
t0 = time.time()
round_results: list[dict[str, dict[str, Any]]] = []
for i in range(rounds):
print(f"\n=== probe round {i + 1}/{rounds} ===", flush=True)
rr = probe_all(leaves, secret, args.timeout_ms, args.url, args.workers)
round_results.append(rr)
ok_n = sum(
1 for n in leaves if _leaf_ok(rr.get(n) or {}, args.max_latency_ms)
)
print(f" round {i + 1} ok={ok_n}/{len(leaves)}", flush=True)
elapsed = time.time() - t0
# Aggregate: dead only if failed every round (3次不通才删).
healthy: list[str] = []
dead: list[str] = []
results: dict[str, dict[str, Any]] = {}
fail_counts: dict[str, int] = {}
for name in leaves:
fails = 0
best_delay: int | None = None
last_status = ""
for rr in round_results:
r = rr.get(name) or {"ok": False, "delay_ms": None, "status": "missing"}
last_status = str(r.get("status") or last_status)
if _leaf_ok(r, args.max_latency_ms):
d = int(r["delay_ms"])
if best_delay is None or d < best_delay:
best_delay = d
else:
fails += 1
fail_counts[name] = fails
if fails >= rounds:
dead.append(name)
results[name] = {
"delay_ms": None,
"status": f"fail_{fails}/{rounds}:{last_status}",
"ok": False,
"fail_rounds": fails,
}
else:
healthy.append(name)
results[name] = {
"delay_ms": best_delay,
"status": f"ok_best fail_{fails}/{rounds}",
"ok": True,
"fail_rounds": fails,
}
healthy.sort(key=lambda n: results[n]["delay_ms"] or 99999)
# Register pool: drop dog VPS / dialer-hairpin leaves even if delay-healthy.
healthy_reg = [
n
for n in healthy
if n not in REGISTER_POOL_EXCLUDE and not REGISTER_POOL_EXCLUDE_RE.search(n)
]
preferred_residential = [
n
for n in healthy_reg
if any(m in n for m in PREFERRED_MARKERS)
]
preferred_named = [n for n in PREFERRED if n in set(healthy_reg)]
preferred_first = preferred_residential + [
n for n in preferred_named if n not in preferred_residential
]
by_cls_ok = Counter(classify(n) for n in healthy)
by_cls_dead = Counter(classify(n) for n in dead)
print("\n=== SUMMARY ===")
print(f"elapsed_s={elapsed:.1f} rounds={rounds}")
print(f"healthy={len(healthy)} dead_all_rounds={len(dead)}")
print(f"healthy_by_class={dict(by_cls_ok)}")
print(f"dead_by_class={dict(by_cls_dead)}")
print("\n--- HEALTHY (best delay ms) ---")
for n in healthy:
print(
f" OK {results[n]['delay_ms']:>5} fail={results[n]['fail_rounds']}/{rounds} {n}"
)
print("\n--- DEAD ALL ROUNDS (purge candidates) ---")
for n in dead:
print(f" DEAD {results[n]['status'][:80]} {n}")
REPORT_DIR.mkdir(parents=True, exist_ok=True)
ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
report = {
"ts": ts,
"url": args.url,
"timeout_ms": args.timeout_ms,
"max_latency_ms": args.max_latency_ms,
"rounds": rounds,
"healthy_count": len(healthy),
"dead_count": len(dead),
"healthy": [
{
"name": n,
"delay_ms": results[n]["delay_ms"],
"fail_rounds": results[n]["fail_rounds"],
"class": classify(n),
}
for n in healthy
],
"dead": [
{
"name": n,
"status": results[n]["status"],
"fail_rounds": results[n]["fail_rounds"],
"class": classify(n),
}
for n in dead
],
"preferred_first": preferred_first,
"healthy_reg": healthy_reg,
"register_pool_excluded": [
n for n in healthy if n not in set(healthy_reg)
],
}
report_path = REPORT_DIR / f"clash_node_health_{ts}.json"
report_path.write_text(
json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8"
)
latest = REPORT_DIR / "clash_node_health_latest.json"
latest.write_text(
json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8"
)
(REPORT_DIR / "clash_nodes_healthy.txt").write_text(
"\n".join(healthy) + ("\n" if healthy else ""), encoding="utf-8"
)
(REPORT_DIR / "clash_nodes_dead.txt").write_text(
"\n".join(dead) + ("\n" if dead else ""), encoding="utf-8"
)
print(f"\nreport={report_path}")
if args.dry_run:
print("dry-run: skip group select / config rewrite / purge")
return 0 if healthy else 2
pick = args.select.strip()
if pick and pick not in set(healthy_reg):
if pick in set(healthy) and pick not in set(healthy_reg):
print(
f"WARN requested --select {pick!r} is register-pool-excluded "
f"(dog VPS / dialer hairpin); ignoring"
)
else:
print(f"WARN requested --select {pick!r} not healthy; ignoring")
pick = ""
if not pick:
pick = (
preferred_first[0]
if preferred_first
else (healthy_reg[0] if healthy_reg else "")
)
if pick:
for g in ("GLOBAL", "PROXY", "🎯Grok注册", "🔰ChatGPT", "♻️Grok优选"):
put_group_now(secret, g, pick)
else:
print(
"ERROR: no healthy register-pool nodes "
f"(healthy={len(healthy)} reg={len(healthy_reg)}) — not changing selection"
)
return 2
if args.purge_proxies and dead:
print("\n=== purge dead proxies (failed all rounds) ===")
for p in (CFG, MERGED):
if p.is_file():
purge_dead_proxies(p, dead)
# After full delete, register groups still need healthy-only rewrite.
if not args.apply_config:
print("\n=== rewrite config groups (post-purge) ===")
for p in (CFG, MERGED):
if p.is_file():
rewrite_config_groups(p, healthy_reg, preferred_first)
if args.apply_config:
print("\n=== rewrite config groups ===")
for p in (CFG, MERGED):
if p.is_file():
rewrite_config_groups(p, healthy_reg, preferred_first)
print(
"NOTE: restart mihomo to load rewritten groups:\n"
" bash start-clash-for-grok.sh"
)
excluded_live = [n for n in healthy if n not in set(healthy_reg)]
if excluded_live:
print(
"register_pool_excluded_healthy="
+ ",".join(excluded_live[:12])
+ (f"...(+{len(excluded_live)-12})" if len(excluded_live) > 12 else "")
)
print(
f"\nREADY for register batch: select={pick} "
f"healthy={len(healthy)} reg_pool={len(healthy_reg)} dead={len(dead)} "
f"preferred_first={preferred_first[:5]}"
)
return 0 if healthy_reg else 2
if __name__ == "__main__":
raise SystemExit(main())
+351
View File
@@ -0,0 +1,351 @@
#!/usr/bin/env python3
"""CLI: sample/full-pool probe Hotmail/Outlook mail credentials (OAuth refresh only).
Usage:
python scripts/probe_mail_pool.py --domains hotmail.com,outlook.com --limit 30
python scripts/probe_mail_pool.py --limit 10 --seed 20260724 --json
python scripts/probe_mail_pool.py --limit 20 --quarantine-dead
# full pool, sequential waves of 200:
python scripts/probe_mail_pool.py --all --limit 200 --concurrency 8 --wall-seconds 300
Env:
HOTMAIL_ACCOUNTS_FILE override pool path
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
_REPO = Path(__file__).resolve().parents[1]
if str(_REPO) not in sys.path:
sys.path.insert(0, str(_REPO))
from mail_pool_probe import ( # noqa: E402
KNOWN_DOMAINS,
QUARANTINABLE_STATUSES,
STATUS_OK,
compact_pool,
dead_archive_path,
is_quarantinable,
pool_stats,
probe_sample,
quarantine,
resolve_pool_path,
)
def _parse_domains(raw: str | None) -> list[str] | None:
if not raw or not str(raw).strip():
return None
parts = [p.strip() for p in str(raw).split(",") if p.strip()]
return parts or None
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description="Probe mail credential pool (OAuth refresh)")
ap.add_argument(
"--file",
default="",
help="pool file path (default: HOTMAIL_ACCOUNTS_FILE / config / mail_credentials.txt)",
)
ap.add_argument(
"--domains",
default="",
help=f"comma-separated domains (known: {','.join(KNOWN_DOMAINS)}); empty=all",
)
ap.add_argument(
"--limit",
type=int,
default=30,
help="per-wave size (1-500, default 30; with --all = batch size)",
)
ap.add_argument("--seed", type=int, default=None, help="RNG seed for reproducible sample")
ap.add_argument(
"--offset",
type=int,
default=None,
help="sequential start index (stable order; implies one wave, no shuffle)",
)
ap.add_argument(
"--all",
action="store_true",
help="scan full filtered pool in sequential waves of --limit until done",
)
ap.add_argument("--concurrency", type=int, default=4, help="workers (1-8, default 4)")
ap.add_argument(
"--wall-seconds",
type=float,
default=90.0,
help="max wall-clock seconds PER wave (default 90, max 600)",
)
ap.add_argument("--json", action="store_true", help="machine-readable JSON output")
ap.add_argument(
"--quarantine-dead",
action="store_true",
help=(
"after probe, archive quarantinable failures from THIS run only "
f"(statuses: {', '.join(sorted(QUARANTINABLE_STATUSES))}; "
"skips network_error/unknown)"
),
)
ap.add_argument(
"--no-writeback",
action="store_true",
help="do not write rotated refresh_token back to the pool",
)
ap.add_argument(
"--stats-only",
action="store_true",
help="print pool stats and exit (no network)",
)
ap.add_argument(
"--compact",
action="store_true",
help="dedupe live pool by email (first wins); backup first",
)
ap.add_argument(
"--compact-dry-run",
action="store_true",
help="preview compact without rewriting the pool",
)
ap.add_argument(
"--drop-comments",
action="store_true",
help="with --compact, also strip # comments and blank lines",
)
args = ap.parse_args(argv)
if args.file:
live = Path(args.file).expanduser()
if not live.is_absolute():
live = (_REPO / live).resolve()
else:
live = resolve_pool_path(_REPO)
if not live.is_file():
print(f"ERROR: pool file not found: {live}", file=sys.stderr)
return 2
if args.stats_only:
st = pool_stats(live)
if args.json:
print(json.dumps(st, ensure_ascii=False, indent=2))
else:
print(f"path: {st['path']}")
print(f"total: {st['total']}")
print(
f"raw_lines: {st.get('raw_lines')} "
f"duplicate_extra: {st.get('duplicate_extra')} "
f"invalid: {st.get('invalid_lines')} "
f"needs_compact: {st.get('needs_compact')}"
)
for dom, n in (st.get("by_domain") or {}).items():
print(f" {dom}: {n}")
print(f"dead_path: {st['dead_path']} ({st['dead_total']})")
return 0
if args.compact or args.compact_dry_run:
# --compact-dry-run alone (or with --compact) previews; --compact alone writes.
dry = bool(args.compact_dry_run) or not bool(args.compact)
if args.compact and not args.compact_dry_run:
dry = False
out = compact_pool(
live,
dry_run=dry,
drop_invalid=True,
drop_comments=bool(args.drop_comments),
)
if args.json:
print(json.dumps(out, ensure_ascii=False, indent=2))
else:
print(out.get("summary") or out)
print(
f"unique={out.get('unique')} dup_extra={out.get('duplicate_extra')} "
f"invalid_dropped={out.get('invalid_dropped')} "
f"backup={out.get('backup_path')}"
)
return 0
domains = _parse_domains(args.domains)
limit = max(1, min(int(args.limit), 500))
concurrency = max(1, min(int(args.concurrency), 8))
wall = max(5.0, min(float(args.wall_seconds), 600.0))
if args.all and args.offset is not None:
print("ERROR: use either --all or --offset, not both", file=sys.stderr)
return 2
def _one_wave(offset: int | None) -> dict:
return probe_sample(
live,
domains=domains,
limit=limit,
seed=None if offset is not None else args.seed,
offset=offset,
concurrency=concurrency,
writeback_rotated=not args.no_writeback,
wall_seconds=wall,
)
def _maybe_quarantine(wave: dict) -> None:
if not args.quarantine_dead:
return
dead_emails = [
r["email"]
for r in wave.get("results") or []
if is_quarantinable(str(r.get("status") or "")) and r.get("email")
]
skipped = [
r["email"]
for r in wave.get("results") or []
if r.get("status") != STATUS_OK
and not is_quarantinable(str(r.get("status") or ""))
and r.get("email")
]
if dead_emails:
q = quarantine(
live,
dead_emails,
reason="probe:cli",
dead_path=dead_archive_path(live),
)
q["skipped_soft_fail"] = skipped
wave["quarantine"] = q
else:
wave["quarantine"] = {
"removed": 0,
"not_found": 0,
"skipped_soft_fail": skipped,
}
try:
if args.all:
# Multi-wave sequential full scan.
# IMPORTANT: do NOT quarantine between waves — removing rows shrinks
# the pool and makes integer next_offset skip unprobed accounts.
# Quarantine once at the end from the aggregated dead set.
offset = 0
waves: list[dict] = []
total_ok = total_dead = total_q = total_probed = 0
by_status: dict[str, int] = {}
timed_any = False
all_results: list[dict] = []
while True:
wave = _one_wave(offset)
waves.append(wave)
total_probed += int(wave.get("probed") or 0)
total_ok += int(wave.get("ok") or 0)
total_dead += int(wave.get("dead") or 0)
total_q += int(wave.get("quarantinable") or 0)
timed_any = timed_any or bool(wave.get("timed_out"))
for k, v in (wave.get("by_status") or {}).items():
by_status[k] = by_status.get(k, 0) + int(v)
# Cap in-memory results for --json / human table (full q via emails).
all_results.extend(wave.get("results") or [])
if not args.json:
print(
f"wave offset={wave.get('offset')} next={wave.get('next_offset')} "
f"probed={wave.get('probed')} ok={wave.get('ok')} "
f"dead={wave.get('dead')} q={wave.get('quarantinable')} "
f"pool={wave.get('pool_filtered_total')}"
+ (" TIMED_OUT" if wave.get("timed_out") else ""),
flush=True,
)
if wave.get("done") or not wave.get("probed"):
break
nxt = wave.get("next_offset")
if nxt is None or int(nxt) <= offset:
break
offset = int(nxt)
out = {
"mode": "sequential_all",
"probed": total_probed,
"ok": total_ok,
"dead": total_dead,
"quarantinable": total_q,
"by_status": by_status,
"timed_out": timed_any,
"waves": len(waves),
"pool_filtered_total": (waves[-1].get("pool_filtered_total") if waves else 0),
"done": True,
"results": all_results,
"wave_summaries": [
{
"offset": w.get("offset"),
"next_offset": w.get("next_offset"),
"probed": w.get("probed"),
"ok": w.get("ok"),
"dead": w.get("dead"),
"quarantinable": w.get("quarantinable"),
"timed_out": w.get("timed_out"),
}
for w in waves
],
}
# Single end-of-scan quarantine so offsets stay valid across waves.
_maybe_quarantine(out)
if out.get("quarantine") and waves:
out["wave_summaries"][-1]["quarantine_removed"] = (
out["quarantine"] or {}
).get("removed")
else:
out = _one_wave(args.offset)
_maybe_quarantine(out)
except RuntimeError as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 3
if args.json:
print(json.dumps(out, ensure_ascii=False, indent=2))
return 0
print(f"pool: {live}")
if domains:
print(f"domains: {', '.join(domains)}")
if out.get("mode"):
print(f"mode: {out.get('mode')} offset={out.get('offset')} next={out.get('next_offset')} done={out.get('done')}")
print(
f"probed={out['probed']} ok={out['ok']} dead={out['dead']} "
f"quarantinable={out.get('quarantinable', 0)}"
+ (" TIMED_OUT" if out.get("timed_out") else "")
)
by = out.get("by_status") or {}
if by:
print("by_status: " + ", ".join(f"{k}={v}" for k, v in sorted(by.items())))
print("-" * 72)
print(f"{'label':<8} {'status':<16} {'q':<3} {'domain':<14} email reason")
# Cap human table to avoid dumping 64k lines; full set is in --json.
rows = out.get("results") or []
show = rows if len(rows) <= 500 else rows[:500]
if len(rows) > 500:
print(f"(showing first 500 of {len(rows)} rows; use --json for full)")
for r in show:
st = r.get("status") or ""
if st == STATUS_OK:
label = "好用"
elif is_quarantinable(st):
label = "挂了"
else:
label = "不定"
qflag = "Y" if r.get("quarantinable") else "-"
reason = (r.get("ms_error") or r.get("reason") or "")[:60]
print(
f"{label:<8} {st:<16} {qflag:<3} {r.get('domain', ''):<14} "
f"{r.get('email', '')} {reason}"
)
if "quarantine" in out:
q = out["quarantine"]
print("-" * 72)
print(
f"quarantine: removed={q.get('removed')} "
f"not_found={q.get('not_found')} "
f"skipped_soft={len(q.get('skipped_soft_fail') or [])} "
f"backup={q.get('backup_path', '')}"
)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+107
View File
@@ -0,0 +1,107 @@
#!/usr/bin/env python3
"""Watch accounts_cli growth; every +100 accounts run quality sample (--live).
Designed to run beside register_cli. State file tracks last milestone.
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
import time
from pathlib import Path
_ROOT = Path(__file__).resolve().parents[1]
STATE = _ROOT / "logs" / "quality_watch_state.json"
ACCOUNTS = _ROOT / "accounts_cli.txt"
PY = _ROOT / ".venv" / "bin" / "python"
if not PY.is_file():
PY = Path(sys.executable)
def _count() -> int:
if not ACCOUNTS.is_file():
return 0
n = 0
with ACCOUNTS.open(encoding="utf-8", errors="replace") as f:
for line in f:
if line.strip() and not line.lstrip().startswith("#"):
n += 1
return n
def _load_state() -> dict:
if STATE.is_file():
try:
return json.loads(STATE.read_text(encoding="utf-8"))
except Exception:
pass
return {"last_milestone": 0, "runs": []}
def _save_state(st: dict) -> None:
STATE.parent.mkdir(parents=True, exist_ok=True)
STATE.write_text(json.dumps(st, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
def _run_quality(milestone: int) -> int:
out = _ROOT / "logs" / "quality" / f"milestone_{milestone}.json"
out.parent.mkdir(parents=True, exist_ok=True)
cmd = [
str(PY),
"-u",
str(_ROOT / "scripts" / "quality_sample_accounts.py"),
"--sample",
"3",
"--live",
"--milestone",
str(milestone),
"--out",
str(out),
]
print(f"[watch] run quality milestone={milestone}", flush=True)
p = subprocess.run(cmd, cwd=str(_ROOT))
return int(p.returncode)
def main() -> int:
step = int(os.environ.get("QUALITY_STEP", "100"))
target = int(os.environ.get("QUALITY_TARGET", "10000"))
poll = float(os.environ.get("QUALITY_POLL_SEC", "30"))
st = _load_state()
last = int(st.get("last_milestone") or 0)
# align last to floor of current if unset
cur0 = _count()
if last <= 0:
last = (cur0 // step) * step
st["last_milestone"] = last
_save_state(st)
print(
f"[watch] start accounts={cur0} last_milestone={last} step={step} target={target}",
flush=True,
)
while True:
n = _count()
# next milestone strictly greater than last
next_m = last + step
while next_m <= n:
rc = _run_quality(next_m)
st.setdefault("runs", []).append(
{"milestone": next_m, "accounts": n, "rc": rc, "ts": int(time.time())}
)
st["last_milestone"] = next_m
last = next_m
_save_state(st)
print(f"[watch] milestone {next_m} done rc={rc} accounts={n}", flush=True)
next_m = last + step
if n >= target:
print(f"[watch] target {target} reached (accounts={n}); exit", flush=True)
return 0
# stop if register meta says dead for long? keep watching until target
time.sleep(poll)
if __name__ == "__main__":
raise SystemExit(main())
+381
View File
@@ -0,0 +1,381 @@
#!/usr/bin/env python3
"""Quality sample for registered accounts + CPA auths (no secret echo).
Checks ledger shape, SSO normalize, CPA file presence/schema, optional live
API probe (models + short chat) when --live and network/proxy allow.
Example:
uv run python -u scripts/quality_sample_accounts.py --sample 2 --live
uv run python -u scripts/quality_sample_accounts.py --milestone 200 --live
"""
from __future__ import annotations
import argparse
import json
import os
import random
import sys
import time
from pathlib import Path
from typing import Any
_ROOT = Path(__file__).resolve().parents[1]
if str(_ROOT) not in sys.path:
sys.path.insert(0, str(_ROOT))
from cpa_xai.accounts import ( # noqa: E402
email_in_existing,
existing_cpa_emails,
normalize_sso_cookie,
parse_accounts_file,
)
from cpa_xai.schema import credential_file_name # noqa: E402
def _load_cfg(path: Path) -> dict:
if not path.is_file():
return {}
try:
raw = json.loads(path.read_text(encoding="utf-8"))
except Exception:
return {}
if not isinstance(raw, dict):
return {}
return {
k: v
for k, v in raw.items()
if not (isinstance(k, str) and (k.startswith("//") or k.startswith("#")))
}
def _proxy_from_cfg(cfg: dict) -> str:
p = (cfg.get("cpa_proxy") or cfg.get("proxy") or "").strip()
if p:
return p
return (
os.environ.get("https_proxy")
or os.environ.get("HTTPS_PROXY")
or os.environ.get("http_proxy")
or ""
).strip()
def _cpa_path_for_email(auth_dir: Path, email: str) -> Path | None:
name = credential_file_name(email)
p = auth_dir / name
if p.is_file():
return p
# fallback scan by JSON email
for f in auth_dir.glob("xai-*.json"):
try:
d = json.loads(f.read_text(encoding="utf-8"))
if str(d.get("email") or "").strip().lower() == email.lower():
return f
except Exception:
continue
return None
def _check_cpa_file(path: Path) -> dict[str, Any]:
out: dict[str, Any] = {"path": str(path), "ok": False}
try:
d = json.loads(path.read_text(encoding="utf-8"))
except Exception as e: # noqa: BLE001
out["error"] = f"json: {e}"
return out
if not isinstance(d, dict):
out["error"] = "not object"
return out
out["type"] = d.get("type")
out["has_access"] = bool(d.get("access_token"))
out["has_refresh"] = bool(d.get("refresh_token"))
out["has_email"] = bool(str(d.get("email") or "").strip())
out["base_url"] = str(d.get("base_url") or "")[:80]
mode = path.stat().st_mode & 0o777
out["mode"] = oct(mode)
if d.get("type") != "xai":
out["error"] = f"type={d.get('type')!r}"
return out
if not out["has_access"]:
out["error"] = "missing access_token"
return out
out["ok"] = True
out["access_token"] = d.get("access_token") # internal only, never print
out["email"] = d.get("email")
out["headers"] = d.get("headers") if isinstance(d.get("headers"), dict) else {}
return out
def _live_api(
token: str,
proxy: str,
base_url: str,
*,
headers_extra: dict | None = None,
try_chat: bool = False,
) -> dict[str, Any]:
"""Probe /v1/models (required). Optional chat — free Build tokens often 403 chat.
Pass criteria (same as production cpa_xai.probe): models HTTP 200 + grok-4.5 listed.
Never logs token.
"""
base = (base_url or "https://cli-chat-proxy.grok.com/v1").rstrip("/")
result: dict[str, Any] = {"ok": False, "models": None, "chat": None}
try:
from curl_cffi import requests as cf_requests
except ImportError as e:
result["error"] = f"curl_cffi missing: {e}"
return result
try:
from cpa_xai.schema import DEFAULT_CLIENT_HEADERS
except Exception:
DEFAULT_CLIENT_HEADERS = {
"x-grok-client-version": "0.2.93",
"x-xai-token-auth": "xai-grok-cli",
"User-Agent": "grok-shell/0.2.93 (linux; x86_64)",
}
try:
sess = cf_requests.Session(impersonate="chrome")
except TypeError:
sess = cf_requests.Session()
if proxy:
sess.proxies = {"http": proxy, "https": proxy}
headers = dict(DEFAULT_CLIENT_HEADERS)
if isinstance(headers_extra, dict):
headers.update({k: str(v) for k, v in headers_extra.items() if v is not None})
headers["Authorization"] = f"Bearer {token}"
headers["Content-Type"] = "application/json"
try:
r = sess.get(f"{base}/models", headers=headers, timeout=45)
result["models_status"] = r.status_code
if r.status_code != 200:
result["error"] = f"models HTTP {r.status_code}"
return result
data = r.json()
ids = []
if isinstance(data, dict):
for m in data.get("data") or []:
if isinstance(m, dict) and m.get("id"):
ids.append(str(m["id"]))
result["models"] = ids[:20]
result["has_grok_45"] = any(i == "grok-4.5" or "grok-4.5" in i for i in ids)
result["ok"] = bool(result["has_grok_45"])
if not result["ok"]:
result["error"] = "models missing grok-4.5"
except Exception as e: # noqa: BLE001
result["error"] = f"models: {e}"
return result
if not try_chat:
return result
try:
r2 = sess.post(
f"{base}/chat/completions",
headers=headers,
json={
"model": "grok-4.5",
"messages": [{"role": "user", "content": "Reply with exactly OK"}],
"max_tokens": 16,
"stream": False,
},
timeout=90,
)
result["chat_status"] = r2.status_code
if r2.status_code == 200:
body = r2.json()
text = ""
try:
text = (
body.get("choices", [{}])[0]
.get("message", {})
.get("content", "")
)
except Exception:
text = ""
result["chat"] = (text or "")[:40]
else:
# informational only — free tokens often deny chat on direct proxy
result["chat_error"] = f"chat HTTP {r2.status_code}"
except Exception as e: # noqa: BLE001
result["chat_error"] = f"chat: {e}"
return result
def sample_quality(
*,
accounts_file: Path,
auth_dir: Path,
sample_n: int = 2,
live: bool = False,
proxy: str = "",
seed: int | None = None,
) -> dict[str, Any]:
rows = parse_accounts_file(accounts_file)
have = existing_cpa_emails(auth_dir)
report: dict[str, Any] = {
"ts": int(time.time()),
"accounts_total": len(rows),
"cpa_files": len(list(auth_dir.glob("xai-*.json"))) if auth_dir.is_dir() else 0,
"sample_n": 0,
"ok": True,
"items": [],
"summary": {},
}
if not rows:
report["ok"] = False
report["error"] = "empty accounts"
return report
rng = random.Random(seed if seed is not None else time.time_ns())
# Prefer recent accounts for quality of current pipeline
pool = rows[-min(len(rows), max(50, sample_n * 20)) :]
picks = pool if len(pool) <= sample_n else rng.sample(pool, sample_n)
report["sample_n"] = len(picks)
ledger_ok = sso_ok = cpa_ok = live_ok = 0
live_ran = 0
for acc in picks:
item: dict[str, Any] = {
"email": acc.email,
"line_no": acc.line_no,
"ledger_ok": False,
"sso_ok": False,
"cpa_ok": False,
"live_ok": None,
}
# ledger
if acc.email and "@" in acc.email and acc.password:
item["ledger_ok"] = True
ledger_ok += 1
sso = normalize_sso_cookie(acc.sso)
item["sso_prefix"] = (sso[:4] + "…") if sso else ""
if sso.startswith("eyJ") and sso.count(".") >= 2:
item["sso_ok"] = True
sso_ok += 1
else:
item["sso_problem"] = "missing_or_not_jwt"
# cpa present / schema
matched = email_in_existing(acc.email, have)
item["cpa_matched"] = matched
cpath = _cpa_path_for_email(auth_dir, acc.email)
if cpath:
cinfo = _check_cpa_file(cpath)
item["cpa_ok"] = bool(cinfo.get("ok"))
item["cpa_file"] = cpath.name
item["cpa_type"] = cinfo.get("type")
item["cpa_has_access"] = cinfo.get("has_access")
if cinfo.get("ok"):
cpa_ok += 1
else:
item["cpa_error"] = cinfo.get("error")
if live and cinfo.get("ok") and cinfo.get("access_token"):
live_ran += 1
lres = _live_api(
str(cinfo["access_token"]),
proxy,
str(cinfo.get("base_url") or "https://cli-chat-proxy.grok.com/v1"),
headers_extra=cinfo.get("headers") if isinstance(cinfo.get("headers"), dict) else None,
try_chat=False,
)
item["live_ok"] = bool(lres.get("ok"))
item["live_models_status"] = lres.get("models_status")
item["live_has_grok_45"] = lres.get("has_grok_45")
if lres.get("error"):
item["live_error"] = lres["error"]
if item["live_ok"]:
live_ok += 1
else:
item["cpa_error"] = "file_missing"
if not item["ledger_ok"] or not item["sso_ok"] or not item["cpa_ok"]:
report["ok"] = False
if live and item.get("live_ok") is False:
report["ok"] = False
report["items"].append(item)
report["summary"] = {
"ledger_ok": f"{ledger_ok}/{len(picks)}",
"sso_ok": f"{sso_ok}/{len(picks)}",
"cpa_ok": f"{cpa_ok}/{len(picks)}",
"live_ok": f"{live_ok}/{live_ran}" if live else "skipped",
"cpa_coverage_hint": f"cpa_files={report['cpa_files']} accounts={report['accounts_total']}",
}
return report
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--accounts", default=str(_ROOT / "accounts_cli.txt"))
ap.add_argument("--auth-dir", default=str(_ROOT / "cpa_auths"))
ap.add_argument("--config", default=str(_ROOT / "config.json"))
ap.add_argument("--sample", type=int, default=2, help="how many accounts to sample")
ap.add_argument("--live", action="store_true", help="hit cli-chat-proxy with access_token")
ap.add_argument("--milestone", type=int, default=0, help="label only")
ap.add_argument("--seed", type=int, default=None)
ap.add_argument(
"--out",
default="",
help="optional JSON report path (no tokens written)",
)
args = ap.parse_args()
cfg = _load_cfg(Path(args.config))
proxy = _proxy_from_cfg(cfg)
auth_dir = Path(args.auth_dir)
if not auth_dir.is_absolute():
auth_dir = (_ROOT / auth_dir).resolve()
report = sample_quality(
accounts_file=Path(args.accounts),
auth_dir=auth_dir,
sample_n=max(1, args.sample),
live=bool(args.live),
proxy=proxy,
seed=args.seed,
)
if args.milestone:
report["milestone"] = args.milestone
# Print safe summary only
print(
f"[quality] milestone={args.milestone or '-'} "
f"accounts={report['accounts_total']} cpa={report['cpa_files']} "
f"ok={report['ok']} summary={report['summary']}",
flush=True,
)
for it in report.get("items") or []:
email = it.get("email") or ""
# redact local-part middle
if "@" in email:
local, _, domain = email.partition("@")
safe = (local[:3] + "***@" + domain) if len(local) > 3 else "***@" + domain
else:
safe = "***"
print(
f" - {safe} ledger={it.get('ledger_ok')} sso={it.get('sso_ok')} "
f"cpa={it.get('cpa_ok')} live={it.get('live_ok')} "
f"err={it.get('cpa_error') or it.get('live_error') or it.get('sso_problem') or '-'}",
flush=True,
)
if args.out:
out_path = Path(args.out)
out_path.parent.mkdir(parents=True, exist_ok=True)
safe = json.loads(json.dumps(report, ensure_ascii=False, default=str))
for it in safe.get("items") or []:
it.pop("access_token", None)
out_path.write_text(json.dumps(safe, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
print(f"[quality] wrote {out_path}", flush=True)
return 0 if report.get("ok") else 2
if __name__ == "__main__":
raise SystemExit(main())
+383
View File
@@ -0,0 +1,383 @@
#!/usr/bin/env python3
"""Remint expired/missing CPA xai auths from ledger SSO, then inject live CPA auth-dir.
Local write: ./cpa_auths
Remote inject (default):
1) /root/.cli-proxy-api — CPA config auth-dir (live pool)
2) /personal/cpa/auths — inventory/backup dir used by register inject
Does NOT start new registration. Fail-fast on missing curl_cffi / no SSO pool.
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
_ROOT = Path(__file__).resolve().parents[1]
if str(_ROOT) not in sys.path:
sys.path.insert(0, str(_ROOT))
from cpa_xai.accounts import normalize_sso_cookie, parse_accounts_file # noqa: E402
from cpa_xai.schema import credential_file_name # noqa: E402
def _load_config(path: Path) -> dict:
if not path.is_file():
return {}
try:
raw = json.loads(path.read_text(encoding="utf-8"))
except Exception as e: # noqa: BLE001
print(f"warn: config read failed: {e}", flush=True)
return {}
if not isinstance(raw, dict):
return {}
return {
k: v
for k, v in raw.items()
if not (isinstance(k, str) and (k.startswith("//") or k.startswith("#")))
}
def _is_expired(payload: dict, now: datetime) -> bool:
exp = (payload.get("expired") or "").strip()
if not exp:
return True
try:
dt = datetime.strptime(exp.replace("Z", "+0000"), "%Y-%m-%dT%H:%M:%S%z")
return dt < now
except Exception:
return True
def _collect_todo(
accounts_path: Path,
auth_dir: Path,
*,
include_missing: bool,
include_expired: bool,
include_chat_retryable: bool,
only_email: str,
limit: int,
denied_emails: set[str] | None = None,
) -> tuple:
from cpa_xai.writer import is_chat_retryable_auth, is_entitlement_denied_auth
accounts = parse_accounts_file(str(accounts_path))
by_email = {a.email.lower(): a for a in accounts if a.email and normalize_sso_cookie(a.sso)}
now = datetime.now(timezone.utc)
denied = {e.lower() for e in (denied_emails or set())}
existing: dict[str, Path] = {}
existing_payload: dict[str, dict] = {}
for p in auth_dir.glob("xai-*.json"):
if "_selftest" in str(p):
continue
try:
d = json.loads(p.read_text(encoding="utf-8"))
except Exception:
continue
em = (d.get("email") or "").strip().lower()
if em:
existing[em] = p
existing_payload[em] = d if isinstance(d, dict) else {}
todo = []
reasons: dict[str, int] = {
"expired": 0,
"missing": 0,
"chat_retryable": 0,
"skipped_denied": 0,
"skipped_chat_ok": 0,
}
def _skip_denied(em: str) -> bool:
if em in denied:
reasons["skipped_denied"] += 1
return True
payload = existing_payload.get(em) or {}
if is_entitlement_denied_auth(payload):
reasons["skipped_denied"] += 1
return True
return False
# missing first (never minted)
if include_missing:
for em, acc in by_email.items():
if only_email and em != only_email.lower():
continue
if _skip_denied(em):
continue
if em not in existing:
todo.append((acc, "missing"))
reasons["missing"] += 1
# expired rewrite — never remint entitlement_denied accounts
if include_expired:
for em, p in existing.items():
if only_email and em != only_email.lower():
continue
if em not in by_email:
continue
if _skip_denied(em):
continue
d = existing_payload.get(em) or {}
# Already chat_ok: expired tokens can still remint, but never denied.
if _is_expired(d, now):
todo.append((by_email[em], "expired"))
reasons["expired"] += 1
# unexpired but chat probe was transient — re-probe without waiting for token expiry
if include_chat_retryable:
for em, p in existing.items():
if only_email and em != only_email.lower():
continue
if em not in by_email:
continue
if _skip_denied(em):
continue
d = existing_payload.get(em) or {}
# Never re-queue permanent chat_ok=False entitlement via retryable path
if d.get("chat_ok") is True and d.get("usable") is not False and not _is_expired(d, now):
reasons["skipped_chat_ok"] += 1
continue
if is_chat_retryable_auth(d) and not _is_expired(d, now):
todo.append((by_email[em], "chat_retryable"))
reasons["chat_retryable"] += 1
# de-dup keep first reason
seen = set()
out = []
for acc, reason in todo:
key = acc.email.lower()
if key in seen:
continue
seen.add(key)
out.append((acc, reason))
if limit and len(out) >= limit:
break
return out, reasons
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--accounts", default=str(_ROOT / "accounts_cli.txt"))
ap.add_argument("--config", default=str(_ROOT / "config.json"))
ap.add_argument("--out-dir", default="")
ap.add_argument("--limit", type=int, default=0, help="0=all candidates")
ap.add_argument("--email", default="")
ap.add_argument("--sleep", type=float, default=3.0)
ap.add_argument("--no-missing", action="store_true")
ap.add_argument("--no-expired", action="store_true")
ap.add_argument(
"--include-chat-retryable",
action="store_true",
default=True,
help="Also remint unexpired auths stamped chat_retryable (transient chat fail)",
)
ap.add_argument(
"--no-chat-retryable",
action="store_false",
dest="include_chat_retryable",
)
ap.add_argument(
"--include-denied",
action="store_true",
default=False,
help="Do NOT skip entitlement_denied ledger (debug only; remint cannot grant chat)",
)
ap.add_argument(
"--no-remote",
action="store_true",
help="Only local remint, skip tebi inject",
)
ap.add_argument(
"--auth-dirs",
default="/root/.cli-proxy-api,/personal/cpa/auths",
help="Comma-separated remote CPA dirs to inject into (live first)",
)
ap.add_argument(
"--fail-log",
default=str(_ROOT / "cpa_auths" / "remint_failed.jsonl"),
)
ap.add_argument(
"--state",
default=str(_ROOT / "logs" / "remint_sync_state.json"),
)
args = ap.parse_args()
cfg = _load_config(Path(args.config))
out_dir = Path(args.out_dir or cfg.get("cpa_auth_dir") or (_ROOT / "cpa_auths"))
if not out_dir.is_absolute():
out_dir = (_ROOT / out_dir).resolve()
out_dir.mkdir(parents=True, exist_ok=True)
from cpa_xai.writer import load_entitlement_denied_emails
denied = set() if args.include_denied else load_entitlement_denied_emails(out_dir)
if denied:
print(f"entitlement_denied ledger size={len(denied)} (skipped unless --include-denied)", flush=True)
todo, reasons = _collect_todo(
Path(args.accounts),
out_dir,
include_missing=not args.no_missing,
include_expired=not args.no_expired,
include_chat_retryable=bool(args.include_chat_retryable),
only_email=args.email,
limit=args.limit,
denied_emails=denied,
)
remote_dirs = [d.strip() for d in (args.auth_dirs or "").split(",") if d.strip()]
if args.no_remote:
remote_dirs = []
print(
f"candidates={len(todo)} reasons={reasons} out={out_dir} "
f"remote_dirs={remote_dirs} sleep={args.sleep}",
flush=True,
)
if not todo:
print("nothing to do", flush=True)
return 0
import cpa_export
ok_n = fail_n = inject_ok = inject_fail = 0
chat_ok_n = chat_denied_n = chat_fail_n = 0
t0 = time.time()
state_path = Path(args.state)
state_path.parent.mkdir(parents=True, exist_ok=True)
for i, (acc, reason) in enumerate(todo, 1):
print(f"\n=== [{i}/{len(todo)}] {reason} {acc.email} ===", flush=True)
def log(msg: str, _email=acc.email) -> None:
print(f"[{time.strftime('%H:%M:%S')}] [{_email}] {msg}", flush=True)
run_cfg = dict(cfg)
run_cfg["cpa_auth_dir"] = str(out_dir)
run_cfg["cpa_prefer_protocol"] = True
run_cfg["cpa_protocol_only"] = True
run_cfg["cpa_probe_after_write"] = True
# Remint cannot grant free Build chat entitlement. Probe chat so we
# fail-fast and skip tebi inject for permission-denied accounts.
run_cfg["cpa_probe_chat"] = True
run_cfg["cpa_probe_chat_required"] = True
# Prefer unified multi-dir inject from cpa_export (same as register one-click).
if remote_dirs:
run_cfg["cpa_remote_inject"] = True
run_cfg["cpa_remote_auth_dirs"] = remote_dirs
else:
run_cfg["cpa_remote_inject"] = False
run_cfg["cpa_auth_priority"] = int(cfg.get("cpa_auth_priority", 1000) or 1000)
r = cpa_export.export_cpa_xai_for_account(
acc.email,
acc.password or "x",
page=None,
sso=acc.sso or None,
config=run_cfg,
log_callback=log,
)
rec = {
"email": acc.email,
"reason": reason,
"ok": bool(r.get("ok")),
"chat_ok": r.get("chat_ok"),
"entitlement_denied": bool(r.get("entitlement_denied")),
"chat_retryable": bool(r.get("chat_retryable")),
"import_gate": r.get("import_gate"),
"fail_reason": r.get("fail_reason"),
"error": r.get("error"),
"path": r.get("path"),
"mint_method": r.get("mint_method"),
"priority": r.get("priority"),
"remote": r.get("remote_injects") or [],
"ts": datetime.now(timezone.utc).isoformat(),
}
if r.get("entitlement_denied"):
chat_denied_n += 1
elif r.get("chat_ok") is True:
chat_ok_n += 1
elif r.get("chat_ok") is False or r.get("fail_reason") or r.get("error"):
chat_fail_n += 1
if r.get("ok") and r.get("path") and r.get("chat_ok") is True:
ok_n += 1
multi = r.get("remote_injects") or []
if multi:
for item in multi:
if item.get("ok"):
inject_ok += 1
elif not item.get("skipped"):
inject_fail += 1
elif remote_dirs and not r.get("remote_inject_skipped"):
# export should have multi-injected; count as fail visibility
inject_fail += len(remote_dirs)
else:
fail_n += 1
Path(args.fail_log).parent.mkdir(parents=True, exist_ok=True)
with open(args.fail_log, "a", encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False, default=str) + "\n")
# Ensure entitlement lands in ledger even if export path missed it
if r.get("entitlement_denied"):
try:
from cpa_xai.writer import record_entitlement_denied
record_entitlement_denied(
out_dir,
acc.email,
extra={
"path": r.get("path"),
"source": "remint",
"chat_error_code": r.get("chat_error_code"),
},
)
except Exception as e: # noqa: BLE001
log(f"entitlement ledger write failed: {e}")
# periodic state
if i == 1 or i % 10 == 0 or i == len(todo):
state = {
"updated_at": datetime.now(timezone.utc).isoformat(),
"done": i,
"total": len(todo),
"ok": ok_n,
"fail": fail_n,
"chat_ok": chat_ok_n,
"chat_denied": chat_denied_n,
"chat_fail": chat_fail_n,
"skipped_denied": reasons.get("skipped_denied", 0),
"inject_ok": inject_ok,
"inject_fail": inject_fail,
"elapsed_s": round(time.time() - t0, 1),
"last_email": acc.email,
"last_ok": bool(r.get("ok")),
"last_chat_ok": r.get("chat_ok"),
"last_import_gate": r.get("import_gate"),
}
state_path.write_text(json.dumps(state, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
if args.sleep and i < len(todo):
time.sleep(args.sleep)
print(
f"\n=== done ok={ok_n} fail={fail_n} "
f"chat_ok={chat_ok_n} chat_denied={chat_denied_n} chat_fail={chat_fail_n} "
f"skipped_denied={reasons.get('skipped_denied', 0)} "
f"inject_ok={inject_ok} inject_fail={inject_fail} "
f"elapsed={round(time.time()-t0,1)}s ===",
flush=True,
)
return 0 if fail_n == 0 or ok_n > 0 else 1
if __name__ == "__main__":
raise SystemExit(main())
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env bash
# Start project-owned Web control plane (FastAPI + static UI).
#
# Production (pxed): prefer durable secret files under $ROOT (mode 0600):
# .control_api_session_secret password-login cookie HMAC
# .control_api_token optional Bearer for scripts
# .control_api_users.json operators
# Bare `python -m apps.control_api` also auto-loads those files now; still prefer
# this wrapper so env + ops logs stay consistent.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
export REGISTER_PROJECT_ROOT="${REGISTER_PROJECT_ROOT:-$ROOT}"
export CONTROL_API_HOST="${CONTROL_API_HOST:-127.0.0.1}"
export CONTROL_API_PORT="${CONTROL_API_PORT:-8787}"
_read_secret_file() {
# first non-empty, non-# line; never echo value
local f="$1"
[[ -f "$f" ]] || return 1
# shellcheck disable=SC2162
while IFS= read -r line || [[ -n "$line" ]]; do
line="${line//$'\r'/}"
[[ -z "$line" || "$line" == \#* ]] && continue
printf '%s' "$line"
return 0
done <"$f"
return 1
}
SECRET_SRC="missing"
TOKEN_SRC="missing"
# Bearer token: env → file
if [[ -z "${CONTROL_API_TOKEN:-}" ]]; then
if tok="$(_read_secret_file "$ROOT/.control_api_token")"; then
export CONTROL_API_TOKEN="$tok"
TOKEN_SRC="file:.control_api_token"
fi
else
TOKEN_SRC="env"
fi
# Session secret: env → file → token → ephemeral (dev)
if [[ -z "${CONTROL_API_SESSION_SECRET:-}" ]]; then
if sec="$(_read_secret_file "$ROOT/.control_api_session_secret")"; then
export CONTROL_API_SESSION_SECRET="$sec"
SECRET_SRC="file:.control_api_session_secret"
elif [[ -n "${CONTROL_API_TOKEN:-}" ]]; then
export CONTROL_API_SESSION_SECRET="$CONTROL_API_TOKEN"
SECRET_SRC="token"
fi
else
SECRET_SRC="env"
fi
if [[ -z "${CONTROL_API_SESSION_SECRET:-}" ]]; then
# Ephemeral secret so password login works after first user is created (dev).
export CONTROL_API_ALLOW_EPHEMERAL_SESSION="${CONTROL_API_ALLOW_EPHEMERAL_SESSION:-1}"
SECRET_SRC="ephemeral(allow)"
fi
echo "[control_api] start root=$ROOT host=${CONTROL_API_HOST} port=${CONTROL_API_PORT}" >&2
echo "[control_api] auth session_secret=${SECRET_SRC} token=${TOKEN_SRC:-missing} users_file=$([ -f "$ROOT/.control_api_users.json" ] && echo yes || echo no)" >&2
if [[ "$SECRET_SRC" == "missing" || "$SECRET_SRC" == "ephemeral(allow)" ]]; then
echo "[control_api] WARN password login needs a durable secret on production:" >&2
echo " printf '%s' \"\$(openssl rand -hex 32)\" > $ROOT/.control_api_session_secret && chmod 600 $ROOT/.control_api_session_secret" >&2
fi
if [[ ! -f "$ROOT/.control_api_users.json" && -z "${CONTROL_API_BOOTSTRAP_USER:-}" && -z "${CONTROL_API_TOKEN:-}" ]]; then
echo "[control_api] No operators yet. Create one:" >&2
echo " uv run python scripts/control_api_user.py set admin" >&2
echo " # or once: CONTROL_API_BOOTSTRAP_USER=admin CONTROL_API_BOOTSTRAP_PASSWORD='…'" >&2
fi
if [[ -z "${CONTROL_API_TOKEN:-}" ]]; then
echo "[control_api] NOTE: CONTROL_API_TOKEN unset — scripts without cookie need password login or open mode (no users)." >&2
fi
if [[ -x "$ROOT/.venv/bin/python" ]]; then
exec "$ROOT/.venv/bin/python" -m apps.control_api
fi
exec uv run python -m apps.control_api
+268
View File
@@ -0,0 +1,268 @@
#!/usr/bin/env bash
# One-shot bootstrap for outsiders (Aaron-style: clone → config → doctor → run).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
WARN=0
warn() { echo "[warn] $*" >&2; WARN=1; }
ok() { echo "[ok] $*"; }
skip() { echo "[skip] $*"; }
# --- write templates (idempotent) ---
if [[ ! -f config.json ]]; then
if [[ -f config.simple.example.json ]]; then
cp config.simple.example.json config.json
ok "wrote config.json from config.simple.example.json"
elif [[ -f config.example.json ]]; then
cp config.example.json config.json
ok "wrote config.json from config.example.json"
else
echo "[error] no config template found" >&2
exit 1
fi
else
skip "config.json already exists"
fi
if [[ ! -f mail_credentials.txt ]]; then
if [[ -f mail_credentials.example.txt ]]; then
cp mail_credentials.example.txt mail_credentials.txt
ok "wrote mail_credentials.txt (only needed for hotmail/outlookmail)"
else
warn "mail_credentials.example.txt missing"
fi
else
skip "mail_credentials.txt already exists"
fi
# --- deps ---
if command -v uv >/dev/null 2>&1; then
if uv sync; then
ok "uv sync done"
else
warn "uv sync failed — fix Python 3.13 / network, then: uv sync"
fi
else
warn "uv not found — install: https://docs.astral.sh/uv/ then re-run: uv sync"
fi
# --- doctor: environment ---
echo
echo "=== doctor ==="
if command -v uv >/dev/null 2>&1; then
PY_VER="$(uv run python -c 'import sys; print("%d.%d"%sys.version_info[:2])' 2>/dev/null || true)"
if [[ "$PY_VER" == "3.13" ]]; then
ok "Python $PY_VER (required)"
elif [[ -n "$PY_VER" ]]; then
warn "Python $PY_VER via uv — project requires 3.13 (see pyproject.toml)"
else
warn "could not resolve Python via uv run"
fi
else
if command -v python3 >/dev/null 2>&1; then
warn "system $(python3 -V 2>&1); install uv + Python 3.13 for this project"
fi
fi
# Chrome / Chromium presence (best-effort)
if command -v google-chrome >/dev/null 2>&1 \
|| command -v google-chrome-stable >/dev/null 2>&1 \
|| command -v chromium >/dev/null 2>&1 \
|| command -v chromium-browser >/dev/null 2>&1 \
|| [[ -d "/Applications/Google Chrome.app" ]] \
|| [[ -d "/Applications/Chromium.app" ]]; then
ok "Chrome/Chromium detected"
else
warn "Chrome/Chromium not found — registration needs a real browser"
fi
# proxy port from config (default 7890)
PROXY_URL="$(
if command -v uv >/dev/null 2>&1; then
uv run python - <<'PY' 2>/dev/null || true
import json
from pathlib import Path
p = Path("config.json")
if not p.is_file():
raise SystemExit
raw = json.loads(p.read_text(encoding="utf-8"))
cfg = {k: v for k, v in raw.items() if not str(k).startswith(("//", "#"))}
print((cfg.get("proxy") or cfg.get("cpa_proxy") or "").strip())
PY
fi
)"
if [[ -n "${PROXY_URL}" ]]; then
# extract host:port for tcp check (http://host:port or http://user:pass@host:port)
HOSTPORT="$(
PROXY_URL="$PROXY_URL" uv run python - <<'PY' 2>/dev/null || true
import os, re
u = os.environ.get("PROXY_URL", "")
m = re.search(r"@([^/]+)$", u) or re.search(r"://([^/]+)", u)
print(m.group(1) if m else "")
PY
)"
if [[ -z "$HOSTPORT" ]]; then
HOSTPORT="127.0.0.1:7890"
fi
# strip credentials if still present
HOSTPORT="${HOSTPORT##*@}"
H="${HOSTPORT%%:*}"
P="${HOSTPORT##*:}"
if [[ -n "$H" && -n "$P" && "$P" =~ ^[0-9]+$ ]]; then
if (echo >/dev/tcp/"$H"/"$P") >/dev/null 2>&1; then
ok "proxy port open $H:$P ($PROXY_URL)"
else
warn "proxy port closed $H:$P — start your proxy or edit config.json proxy"
fi
else
ok "proxy configured: $PROXY_URL (could not parse host:port for probe)"
fi
else
warn "proxy empty in config.json — xAI access usually needs a local proxy"
fi
# --- doctor: mail credentials / keys ---
MAIL_STATUS="$(
if command -v uv >/dev/null 2>&1; then
uv run python - <<'PY' 2>/dev/null || true
import json, re
from pathlib import Path
def load_cfg():
raw = json.loads(Path("config.json").read_text(encoding="utf-8"))
return {k: v for k, v in raw.items() if not str(k).startswith(("//", "#"))}
cfg = load_cfg() if Path("config.json").is_file() else {}
provider = str(cfg.get("email_provider") or "duckmail").strip().lower()
print(f"provider={provider}")
if provider in ("hotmail", "outlook", "outlookmail", "microsoft"):
p = Path(str(cfg.get("hotmail_accounts_file") or "mail_credentials.txt"))
if not p.is_file():
print("mail=missing_file")
raise SystemExit
lines = []
for ln in p.read_text(encoding="utf-8", errors="replace").splitlines():
s = ln.strip()
if not s or s.startswith("#"):
continue
lines.append(s)
if not lines:
print("mail=empty")
raise SystemExit
placeholders = ("your@hotmail.com", "mailPassword", "client-id", "refresh-token", "xxxx")
bad = 0
good = 0
for s in lines:
parts = s.split("----")
if len(parts) < 4:
bad += 1
continue
blob = s.lower()
if any(ph.lower() in blob for ph in placeholders):
bad += 1
elif parts[3].strip() in ("", "token", "refresh_token"):
bad += 1
else:
good += 1
if good == 0:
print("mail=placeholder_or_invalid")
else:
print(f"mail=ok good={good} bad={bad}")
elif provider == "duckmail":
key = str(cfg.get("duckmail_api_key") or "").strip()
if not key:
print("mail=duckmail_key_missing")
else:
print("mail=duckmail_key_set")
elif provider == "cloudmail":
if not str(cfg.get("cloudmail_url") or "").strip():
print("mail=cloudmail_url_missing")
else:
print("mail=cloudmail_configured")
elif provider == "cloudflare":
if not str(cfg.get("cloudflare_api_base") or "").strip():
print("mail=cloudflare_base_missing")
else:
print("mail=cloudflare_configured")
else:
print(f"mail=provider_{provider}_check_manual")
PY
fi
)"
if [[ -n "$MAIL_STATUS" ]]; then
while IFS= read -r line; do
case "$line" in
provider=*)
ok "email_provider=${line#provider=}"
;;
mail=ok*)
ok "mail credentials look filled ($line)"
;;
mail=duckmail_key_set)
ok "duckmail_api_key is set"
;;
mail=duckmail_key_missing)
warn "duckmail_api_key empty — set it in config.json (email_provider=duckmail)"
;;
mail=placeholder_or_invalid)
warn "mail_credentials.txt still placeholder/invalid — replace before hotmail register"
;;
mail=missing_file|mail=empty)
warn "mail_credentials.txt missing/empty (required for hotmail)"
;;
mail=cloudmail_url_missing)
warn "cloudmail_url empty in config.json"
;;
mail=cloudflare_base_missing)
warn "cloudflare_api_base empty in config.json"
;;
mail=*)
ok "$line"
;;
esac
done <<< "$MAIL_STATUS"
else
warn "could not run mail doctor (need uv + config.json)"
fi
echo "=== end doctor ==="
echo
if [[ "$WARN" -ne 0 ]]; then
echo "[note] setup finished with warnings — fix them before register_cli"
else
ok "setup looks ready"
fi
cat <<'EOF'
Next (after fixing any [warn] above):
1) config.json
- proxy → your local proxy
- duckmail: set duckmail_api_key
- hotmail: email_provider=hotmail + real mail_credentials.txt lines
2) Register one account (headed browser recommended):
uv run python -u register_cli.py --extra 1 --threads 1 --no-headless --fast
3) Re-run doctor only:
bash scripts/setup_simple.sh
4) Outputs:
ls accounts_cli.txt cpa_auths/
# Product success = chat probe ok (not models-only)
# entitlement_denied → no free Build chat; do not remint
Typical blockers: proxy down · Turnstile · duckmail key · hotmail placeholder · chat 403 (no entitlement)
Secret hygiene (paths/modes only, never prints tokens):
bash scripts/doctor_secrets.sh
Docs: README.md | Full config: config.example.json | Production: cpa_remote_inject
EOF
+209
View File
@@ -0,0 +1,209 @@
#!/usr/bin/env bash
# Official single-shot disk-first Grok reg+mint smoke (pxed / local).
#
# Success criterion: +1 complete cpa_auths/xai-*.json with access+refresh
# (mint_token_ok / product_batch_success when CPA_PROBE_CHAT=false).
# Does NOT require chat_ok or remote inject.
#
# Single-instance:
# - flock /tmp/grok_smoke_diskfirst.lock (this wrapper)
# - register_cli also flocks /tmp/grok_register_cli.lock (process-level)
#
# Usage:
# bash scripts/smoke_diskfirst_one.sh
# SKIP_CLASH_PREFLIGHT=1 bash scripts/smoke_diskfirst_one.sh # no Clash rewrite
# SMOKE_TIMEOUT=900 bash scripts/smoke_diskfirst_one.sh
#
# Env freeze (always):
# CPA_EXPORT_ENABLED=true CPA_PROBE_CHAT=false CPA_REMOTE_INJECT=false
set -uo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT" || exit 1
# Prefer /data symlink on pxed; fall back to checkout.
if [[ -d /data/grok-register && -f /data/grok-register/register_cli.py ]]; then
# When invoked from monorepo checkout that is not the runtime, prefer runtime.
if [[ "$ROOT" != /data/grok-register && "$ROOT" != /personal/grok-register ]]; then
if [[ -d /data/grok-register ]]; then
:
fi
fi
fi
LOCK=/tmp/grok_smoke_diskfirst.lock
exec 9>"$LOCK"
if ! flock -n 9; then
echo "another smoke_diskfirst holds $LOCK; exit 1"
exit 1
fi
echo $$ > "${LOCK}.pid"
TS=$(date +%Y%m%d_%H%M%S)
mkdir -p logs
LOG="logs/smoke_diskfirst_${TS}.log"
export SMOKE_LOG_PATH="$LOG"
# Line-safe .env load (never source whole file — may contain bare exports / comments).
if [[ -f .env ]]; then
while IFS= read -r line || [ -n "$line" ]; do
case "$line" in ""|\#*) continue ;; esac
key=${line%%=*}
val=${line#*=}
# Only export known-safe keys; never clobber disk-first freeze below.
case "$key" in
EMAIL_PROVIDER|EMAIL_PROVIDERS|EMAIL_PROVIDER_STRATEGY|MAIL_TIMEOUT|PLAYWRIGHT_BROWSERS_PATH|PROXY|CPA_PROXY|GROK_NODE|DISPLAY)
export "$key=$val"
;;
esac
done < .env
fi
if [[ -f .venv/bin/activate ]]; then
# shellcheck source=/dev/null
source .venv/bin/activate
fi
# Smoke always pins Cloudflare Worker temp-mail (verified product path).
# Override only with SMOKE_EMAIL_PROVIDER=... for deliberate channel experiments.
# Multi-select EMAIL_PROVIDERS is cleared so duckmail/gmail RR cannot hijack.
export EMAIL_PROVIDER=${SMOKE_EMAIL_PROVIDER:-cloudflare}
unset EMAIL_PROVIDERS || true
export MAIL_TIMEOUT=${MAIL_TIMEOUT:-20}
export CPA_EXPORT_ENABLED=true
export CPA_PROBE_CHAT=false
export CPA_REMOTE_INJECT=false
export CPA_PREFER_PROTOCOL=${CPA_PREFER_PROTOCOL:-false}
export PROXY=${PROXY:-http://127.0.0.1:7897}
export CPA_PROXY=${CPA_PROXY:-$PROXY}
export PLAYWRIGHT_BROWSERS_PATH=${PLAYWRIGHT_BROWSERS_PATH:-/personal/browsers/ms-playwright}
export SKIP_CLASH_PREFLIGHT=${SKIP_CLASH_PREFLIGHT:-0}
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY all_proxy || true
export NO_PROXY=127.0.0.1,localhost
export no_proxy=127.0.0.1,localhost
SMOKE_TIMEOUT=${SMOKE_TIMEOUT:-900}
PY=${ROOT}/.venv/bin/python
if [[ ! -x "$PY" ]]; then
PY=python3
fi
EXIT_FILE=/tmp/grok_smoke_diskfirst_exit.txt
rm -f "$EXIT_FILE"
baseline_complete() {
"$PY" - <<'PY'
import json
from pathlib import Path
need = ["access_token", "refresh_token", "email", "base_url", "token_endpoint", "headers"]
xs = list(Path("cpa_auths").glob("xai-*.json")) if Path("cpa_auths").exists() else []
complete = 0
for f in xs:
try:
j = json.loads(f.read_text())
except Exception:
continue
if all((j.get(k) or "") for k in need):
complete += 1
print(complete)
PY
}
{
echo "=== smoke_diskfirst_one start $(date -u +%Y-%m-%dT%H:%M:%SZ) ==="
echo "root=$ROOT"
echo "EMAIL_PROVIDER=$EMAIL_PROVIDER EMAIL_PROVIDERS=${EMAIL_PROVIDERS:-} MAIL_TIMEOUT=${MAIL_TIMEOUT:-} CPA_EXPORT=$CPA_EXPORT_ENABLED PROBE=$CPA_PROBE_CHAT INJECT=$CPA_REMOTE_INJECT PROXY=$PROXY"
echo "SKIP_CLASH_PREFLIGHT=$SKIP_CLASH_PREFLIGHT CPA_PREFER_PROTOCOL=$CPA_PREFER_PROTOCOL timeout=$SMOKE_TIMEOUT"
echo "success criterion: +1 complete xai-*.json with access+refresh (not chat_ok)"
BASE=$(baseline_complete)
echo "baseline_complete=$BASE"
echo "$BASE" > /tmp/grok_smoke_baseline_complete.txt
if [[ "${SKIP_CLASH_PREFLIGHT}" != "1" && -f preflight-clash-nodes.sh ]]; then
echo "[smoke] preflight-clash-nodes ..."
set +e
bash preflight-clash-nodes.sh 2>&1 | tail -40
pc=$?
set -e
echo "preflight_exit=$pc"
else
echo "[smoke] preflight skipped SKIP_CLASH_PREFLIGHT=$SKIP_CLASH_PREFLIGHT"
fi
# Optional: BROWSER_FINGERPRINT_MODE=off|light or SMOKE_BROWSER_FINGERPRINT_MODE
FP_MODE=${SMOKE_BROWSER_FINGERPRINT_MODE:-${BROWSER_FINGERPRINT_MODE:-}}
FP_ARGS=()
if [[ -n "$FP_MODE" ]]; then
FP_ARGS=(--browser-fingerprint-mode "$FP_MODE")
echo "[smoke] browser_fingerprint_mode=$FP_MODE"
fi
set +e
if command -v xvfb-run >/dev/null 2>&1 && [[ -z "${DISPLAY:-}" || "${FORCE_XVFB:-0}" == "1" ]]; then
timeout "$SMOKE_TIMEOUT" xvfb-run -a -s "-screen 0 1280x900x24 -ac +extension GLX +render -noreset -nolisten tcp" \
"$PY" -u register_cli.py --extra 1 --threads 1 --no-headless --fast "${FP_ARGS[@]}"
code=$?
else
timeout "$SMOKE_TIMEOUT" \
"$PY" -u register_cli.py --extra 1 --threads 1 --no-headless --fast "${FP_ARGS[@]}"
code=$?
fi
set -e
echo "register_cli_exit=$code"
echo "$code" > "$EXIT_FILE"
date -u +%Y-%m-%dT%H:%M:%SZ
"$PY" - <<'PY'
import json
from pathlib import Path
need = ["access_token", "refresh_token", "email", "base_url", "token_endpoint", "headers"]
try:
base = int(Path("/tmp/grok_smoke_baseline_complete.txt").read_text().strip() or "0")
except Exception:
base = 0
xs = sorted(Path("cpa_auths").glob("xai-*.json"), key=lambda p: p.stat().st_mtime, reverse=True) if Path("cpa_auths").exists() else []
complete = 0
newest = None
for f in xs:
try:
j = json.loads(f.read_text())
except Exception:
continue
ok = all((j.get(k) or "") for k in need)
if ok:
complete += 1
if newest is None:
newest = {
"file": f.name,
"email": j.get("email"),
"has_refresh": bool(j.get("refresh_token")),
"chat_ok": j.get("chat_ok"),
"mint_method": j.get("mint_method"),
}
print(f"complete_now={complete} baseline={base} delta={complete - base}")
print("newest", newest)
if complete > base:
print("SMOKE_PRODUCT_OK=1")
else:
print("SMOKE_PRODUCT_OK=0")
PY
echo "=== smoke_diskfirst_one end exit=$code ==="
} >"$LOG" 2>&1
# Surface path + product line for operators
echo "$LOG"
if grep -q "SMOKE_PRODUCT_OK=1" "$LOG" 2>/dev/null; then
echo "smoke product ok (complete delta>=1)"
# Prefer product ok over raw exit when disk-first wrote tokens
exit 0
fi
# Fall through to register_cli exit (1=not product, 2=fatal). code lives in EXIT_FILE
# because the log block is a redirected group (not a subshell variable scope leak).
code=1
if [[ -f "$EXIT_FILE" ]]; then
code=$(cat "$EXIT_FILE" 2>/dev/null || echo 1)
fi
tail -n 30 "$LOG" || true
exit "${code:-1}"