71 lines
1.9 KiB
Python
Executable File
71 lines
1.9 KiB
Python
Executable File
#!/usr/bin/env bash
|
||
# 透過 codex app-server 的 JSON-RPC account/read 取得目前登入帳號的 email。
|
||
#
|
||
# 這是 TUI `/status` Account 欄位的程式化來源,不解析本地 OAuth token,
|
||
# 而是由 codex 自身回報登入帳號。將 email 印到 stdout(取不到時印空字串)。
|
||
|
||
set -uo pipefail
|
||
|
||
timeout_seconds="${1:-25}"
|
||
if ! [[ "$timeout_seconds" =~ ^[0-9]+([.][0-9]+)?$ ]]; then
|
||
echo "timeout_seconds must be a number." >&2
|
||
exit 2
|
||
fi
|
||
|
||
if ! command -v jq >/dev/null 2>&1; then
|
||
echo "jq is required." >&2
|
||
exit 2
|
||
fi
|
||
|
||
email=""
|
||
|
||
cleanup() {
|
||
if [[ -n "${CODEX_SERVER_PID:-}" ]]; then
|
||
kill "$CODEX_SERVER_PID" >/dev/null 2>&1 || true
|
||
wait "$CODEX_SERVER_PID" >/dev/null 2>&1 || true
|
||
fi
|
||
}
|
||
trap cleanup EXIT
|
||
|
||
coproc CODEX_SERVER { codex app-server 2>/dev/null; }
|
||
exec {codex_server_stdin}>&"${CODEX_SERVER[1]}"
|
||
exec {codex_server_stdout}<&"${CODEX_SERVER[0]}"
|
||
|
||
send_json() {
|
||
printf '%s\n' "$1" >&"$codex_server_stdin"
|
||
}
|
||
|
||
send_json '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"clientInfo":{"name":"ci","version":"1.0"}}}'
|
||
send_json '{"jsonrpc":"2.0","method":"initialized","params":{}}'
|
||
send_json '{"jsonrpc":"2.0","id":2,"method":"account/read","params":{}}'
|
||
|
||
deadline="$(
|
||
awk -v now="$(date +%s)" -v timeout="$timeout_seconds" 'BEGIN { printf "%.3f", now + timeout }'
|
||
)"
|
||
|
||
while awk -v now="$(date +%s)" -v deadline="$deadline" 'BEGIN { exit !(now < deadline) }'; do
|
||
remaining="$(
|
||
awk -v now="$(date +%s)" -v deadline="$deadline" 'BEGIN {
|
||
remaining = deadline - now
|
||
if (remaining < 1) {
|
||
remaining = 1
|
||
}
|
||
printf "%.0f", remaining
|
||
}'
|
||
)"
|
||
|
||
if ! IFS= read -r -t "$remaining" line <&"$codex_server_stdout"; then
|
||
break
|
||
fi
|
||
|
||
message_id="$(jq -r 'try .id catch empty' <<<"$line" 2>/dev/null || true)"
|
||
if [[ "$message_id" != "2" ]]; then
|
||
continue
|
||
fi
|
||
|
||
email="$(jq -r 'try (.result.account.email // "") catch ""' <<<"$line" 2>/dev/null || true)"
|
||
break
|
||
done
|
||
|
||
printf '%s\n' "$email"
|