#!/bin/bash # Cài / cập nhật Codex dùng codex.fosta.app, kèm vẽ ảnh qua Images API của fosta (macOS, Linux). # curl -fsSL https://codex.fosta.app/install.sh | bash # Hỏi key và model. Chạy lại bất cứ lúc nào để đổi key hoặc model: script chỉ thay # đúng các khối "fosta" nó đã ghi, phần cấu hình khác của bạn được giữ nguyên. # Không hỏi: FOSTA_KEY=... FOSTA_MODEL=gpt-6.2-sol bash install.sh set -euo pipefail CODEX_HOME="${CODEX_HOME:-$HOME/.codex}" BASE_URL="https://codex.fosta.app/v1" KEY="${FOSTA_KEY:-}" MODEL="${FOSTA_MODEL:-}" command -v curl >/dev/null 2>&1 || { echo "Cần cài curl trước (vd: sudo apt install curl)."; exit 1; } echo "== Cài Codex dùng codex.fosta.app ==" echo "Chưa có key? Mua trong bot Telegram @mmo_api_codex_bot." echo if [ -z "$KEY" ]; then printf "Dán API key rồi bấm Enter (key không hiện ra màn hình): " read -rs KEY >> fosta (script cài fosta ghi; chạy lại script sẽ thay khối này)" echo "model_provider = \"fosta\"" echo "model = \"$MODEL\"" echo "# <<< fosta" awk ' /^# >>> fosta/ { skip = 1; next } /^# <<< fosta/ { skip = 0; next } skip { next } /^[ \t]*\[/ { intable = 1; drop = ($0 ~ /^[ \t]*\[model_providers\.fosta\]/) } drop { next } !intable && /^[ \t]*(model|model_provider)[ \t]*=/ { next } !intable && /^[ \t]*(openai_base_url|model_catalog_json)[ \t]*=.*fosta/ { next } /^[ \t]*$/ { blank++; next } { while (blank > 0) { print ""; blank-- } print } ' "$cfg" echo echo "# >>> fosta" echo "[model_providers.fosta]" echo "name = \"codex.fosta.app\"" echo "base_url = \"$BASE_URL\"" echo "wire_api = \"responses\"" echo "experimental_bearer_token = \"$KEY\"" echo "# <<< fosta" } > "$tmp" mv "$tmp" "$cfg" chmod 600 "$cfg" # 2. Công cụ vẽ: đọc key và địa chỉ từ provider fosta trong config.toml, gọi Images API bằng curl. # Chỉ dùng bash + curl + base64 để chạy được cả macOS lẫn Linux. cat > "$CODEX_HOME/fosta/imagegen.sh" <<'IMAGEGEN' #!/bin/bash # Vẽ hoặc sửa ảnh qua codex.fosta.app. # imagegen.sh -p "mô tả" -o out.png [-s 1024x1024|1536x1024|1024x1536] [-q low|medium|high] [-r ref.png ...] # Có -r thì gửi ảnh mẫu (sửa ảnh / giữ nhân vật), không có thì vẽ mới. set -euo pipefail DIR="$(cd "$(dirname "$0")" && pwd)" CFG="$DIR/../config.toml" BASE=$(awk '/^\[model_providers\.fosta\]/{f=1;next} /^\[/{f=0} f&&/^base_url/' "$CFG" | sed -E 's/.*"([^"]+)".*/\1/') KEY=$(awk '/^\[model_providers\.fosta\]/{f=1;next} /^\[/{f=0} f&&/^experimental_bearer_token/' "$CFG" | sed -E 's/.*"([^"]+)".*/\1/') [ -n "$KEY" ] && [ -n "$BASE" ] || { echo "Không thấy key fosta trong $CFG, chạy lại script cài." >&2; exit 1; } prompt="" out="" size="1024x1024" quality="" refs=() while getopts "p:o:s:q:r:" opt; do case $opt in p) prompt=$OPTARG ;; o) out=$OPTARG ;; s) size=$OPTARG ;; q) quality=$OPTARG ;; r) refs+=("$OPTARG") ;; *) echo "Dùng: imagegen.sh -p \"mô tả\" -o out.png [-s 1024x1024] [-q high] [-r ref.png ...]" >&2; exit 2 ;; esac done [ -n "$prompt" ] && [ -n "$out" ] || { echo "Cần -p và -o" >&2; exit 2; } mkdir -p "$(dirname "$out")" resp=$(mktemp); b64=$(mktemp) trap 'rm -f "$resp" "$b64"' EXIT json_str() { local s=$1 s=${s//\\/\\\\}; s=${s//\"/\\\"}; s=${s//$'\n'/\\n}; s=${s//$'\r'/\\r}; s=${s//$'\t'/\\t} printf '"%s"' "$s" } # b64_json của ảnh đầu tiên → $b64 (python3, plutil trên macOS, hoặc sed). extract_b64() { if command -v python3 >/dev/null 2>&1 && python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["data"][0]["b64_json"])' "$resp" > "$b64" 2>/dev/null; then return; fi if command -v plutil >/dev/null 2>&1 && plutil -extract data.0.b64_json raw -o - "$resp" > "$b64" 2>/dev/null; then return; fi tr -d '\n' < "$resp" | sed -E 's/.*"b64_json"[ ]*:[ ]*"([^"]*)".*/\1/' | tr -d '\\' > "$b64" } # GNU base64 dùng -d; macOS cũ chỉ có -D. decode_b64() { base64 -d < "$b64" > "$out" 2>/dev/null || base64 -D < "$b64" > "$out" 2>/dev/null; } ok=0 for attempt in 1 2 3 4 5 6; do rc=0 if [ ${#refs[@]} -gt 0 ]; then args=(-F model=gpt-image-2 --form-string "prompt=$prompt" -F "size=$size") [ -n "$quality" ] && args+=(-F "quality=$quality") for r in "${refs[@]}"; do args+=(-F "image[]=@$r"); done code=$(curl -s -o "$resp" -w '%{http_code}' -m 300 "$BASE/images/edits" -H "Authorization: Bearer $KEY" "${args[@]}") || rc=$? else body="{\"model\":\"gpt-image-2\",\"prompt\":$(json_str "$prompt"),\"size\":$(json_str "$size"),\"n\":1" [ -n "$quality" ] && body="$body,\"quality\":$(json_str "$quality")" body="$body}" code=$(curl -s -o "$resp" -w '%{http_code}' -m 300 "$BASE/images/generations" -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" --data-binary "$body") || rc=$? fi if [ "$rc" = 0 ] && [ "$code" = 200 ]; then extract_b64; decode_b64 || true # LC_ALL=C: grep ở locale UTF-8 không khớp được byte 0x89 đầu file PNG. if [ -s "$out" ] && head -c 8 "$out" | LC_ALL=C grep -q PNG; then ok=1; break; fi rm -f "$out" echo "Lần $attempt: máy chủ trả 200 nhưng không giải mã được ảnh ($(wc -c < "$resp") byte): $(head -c 120 "$resp")" >&2 else echo "Lần $attempt lỗi (curl $rc, mã $code): $(head -c 200 "$resp" 2>/dev/null)" >&2 fi # Máy chủ báo "reset after Ns" khi tài khoản vẽ đang bị khoá tạm; đợi đúng chừng đó. wait_s=$(grep -o "reset after [0-9]*s" "$resp" 2>/dev/null | grep -o "[0-9]*" || true) [ $attempt -lt 6 ] && sleep $(( ${wait_s:-30} + 3 )) done [ "$ok" = 1 ] || { echo "Vẽ không được sau 6 lần (máy chủ vẽ đang bận hoặc hết lượt). Thử lại sau vài phút." >&2; exit 1; } echo "Đã lưu: $out" IMAGEGEN chmod 755 "$CODEX_HOME/fosta/imagegen.sh" # 3. AGENTS.md: dặn Codex dùng công cụ trên thay cho image_gen (cần đăng nhập ChatGPT nên không có). agents="$CODEX_HOME/AGENTS.md" touch "$agents" awk '/^ ## Image generation on this machine The built-in \`image_gen\` tool is not available here (it needs a ChatGPT login). The user has pre-approved this replacement: whenever they ask to draw, generate or edit an image, run "$CODEX_HOME/fosta/imagegen.sh" -p "" -o [-s 1024x1024|1536x1024|1024x1536] [-q low|medium|high] [-r reference.png ...] - Use \`-r\` (repeatable) to pass reference or source images for edits and consistent characters. - It needs network access: if the sandbox blocks it, rerun it with escalated permissions. - It retries by itself when the image server is busy and can take up to 6 minutes. Wait for it to exit; do not interrupt it or start a second copy. - Do not use the imagegen skill's \`scripts/image_gen.py\` and do not ask for OPENAI_API_KEY. - One call per image; after it saves, look at the result with view_image before reporting. - If the script fails, tell the user it failed and why. Never fake the result by drawing or editing the image yourself with code (PIL, SVG, canvas...) unless the user asks for that. AGENTS mv "$agents.tmp-fosta" "$agents" echo echo "Xong. Codex giờ chạy qua codex.fosta.app (model $MODEL) và vẽ được ảnh." echo "Bản sao config cũ: $cfg.bak-fosta-$stamp" echo "Đổi key hoặc model: chạy lại lệnh cài này." echo "Mở lại Codex rồi thử: \"vẽ cho t một quả táo pixel art, lưu ra apple.png\"."