Giao hàng Telegram bền vững
Mọi kết quả cuối và câu hỏi chặn của Codex, Claude và Grok được ghi bền vững vào SQLite trước khi gửi Telegram. Runtime dùng bảy module telegram_delivery*.py được khai báo chính xác trong telegram_delivery_runtime.json; không được nâng cấp thiếu một module.
- Code/venv là release root-owned, bất biến;
.env, session, usage, uploads và SQLite state nằm ngoài release và được giữ nguyên khi update. - SQLite dùng rollback journal
DELETEvàsynchronous=EXTRA. Store, marker, application id, schema và integrity phải được validate trước khi service chạy. - Ngữ nghĩa gửi là at-least-once: ưu tiên tuyệt đối không mất final/question. Khi Telegram đã nhận nhưng ACK bị mất hoặc không xác định, có thể hiếm khi gửi lặp; không được xóa bản ghi pending để che sự mơ hồ.
- Updater Linux là giao dịch nhiều instance: preflight tất cả, stage release mới, đổi pointer, health check cùng PID, ghi version sau cùng; bất kỳ lỗi nào phải rollback toàn bộ hoặc báo rollback incomplete rõ ràng.
Bố trí runtime Linux
/opt/bot/tg-<kind>-bot/ # .env và dữ liệu thay đổi
/opt/bot/state/tg-<kind>-bot/ # SQLite state 0700 của service
/opt/bot/releases/tg-<kind>-bot/<id>/ # code + venv bất biến
/opt/bot/releases/tg-<kind>-bot/current # pointer release atomic
macOS dùng cùng phân tách cho launchd Codex/Claude. Windows bảo vệ state bằng DACL không kế thừa, chỉ cho SID hiện tại, SYSTEM và Builtin Administrators.
v0.0.194 unbacked wakeup safety
v0.0.194 fixes missed Claude wakeups when a due wakeup returns a final message that still promises background follow-up but forgets to call ScheduleWakeup. The bot now recognizes Vietnamese follow-up markers such as em sẽ báo and đang chạy nền, keeps a safety continuation, and reopens the same session to finish the promised check instead of silently closing the schedule.
v0.0.193 update already-current reply
v0.0.193 makes Telegram /update explicitly report when the installed bot package is already the latest public version. In that case the bot replies Bạn đang ở phiên bản mới nhất: <version>. and does not start the package updater unnecessarily.
v0.0.192 stops Claude quota/logout retry spam by treating quota-limit and not-logged-in as terminal single-notification failures. The dispatcher completes any legacy deferred terminal items without re-executing Claude while keeping transient recovery retries intact. v0.0.191 uses explicit /thinking off and /thinking on Telegram controls for final-only output preferences with verified Vietnamese text cleanup while preserving final answers, blocking questions, quota/login notices, and durable delivery auditability. Default mode stays live thinking/progress until an allowed chat or topic runs /thinking off. v0.0.188 fixes add-bot `.env` creation and repair. v0.0.187 adds admin-only private Telegram `/login`. v0.0.186 adds not-logged-in status, and v0.0.184 adds weekly quota-limit status.
v0.0.192 Claude quota/logout terminal stop
v0.0.192 stops Claude quota/logout retry spam by treating quota-limit and not-logged-in as terminal single-notification failures. The dispatcher completes any legacy deferred terminal items without re-executing Claude while keeping transient recovery retries intact.
v0.0.191 uses explicit /thinking off and /thinking on Telegram controls for final-only output preferences with verified Vietnamese text cleanup while preserving final answers, blocking questions, quota/login notices, and durable delivery auditability. Default mode stays live thinking/progress until an allowed chat or topic runs /thinking off. v0.0.188 fixes add-bot `.env` creation and repair. v0.0.187 adds admin-only private Telegram `/login`. v0.0.186 adds not-logged-in status, and v0.0.184 adds weekly quota-limit status.
v0.0.144 fleet recovery
v0.0.144 adds verified repair bootstrap, trusted Python selection, service-authoritative inventory, legacy service state recovery for v0.0.131 through v0.0.142, orphan directory preservation, and truthful updater exits. CMS force update downloads the public manifest and immutable ZIP, validates SHA-256 and archive paths, syntax-checks repair.sh, then executes the installed bridge.
Claude legacy wakeup recovery now delivers recovered transcript events without replaying the old prompt and sends due notices through durable delivery using stable wakeup-due:<work_id> identities.
Tổng quan
AHV CLI Bot là gói cài đặt bot Telegram cho Codex CLI, Claude Code và Grok CLI. Gói public nằm tại:
https://bot.ahvclaw.com/downloads/telegram-cli-bot-setupNhận tin Telegram, gọi Codex CLI, giữ session và gửi kết quả dài theo nhiều phần.
Nhận tin Telegram, gọi Claude Code, gửi tiến trình trong transcript, theo dõi task dài tới kết quả cuối.
Nhận tin Telegram, gọi Grok CLI chính thức bằng headless mode và hỗ trợ login từ xa qua CMS.
Timer systemd tải manifest, kiểm tra SHA256, kích hoạt package runtime đầy đủ theo giao dịch và chỉ ghi version sau khi mọi service vượt health check.
Trang chủ tự đọc manifest để hiển thị phiên bản hiện tại và hash gói cài đặt.
Cài đặt nhanh
Linux
bash <(curl -fsSL https://bot.ahvclaw.com/downloads/telegram-cli-bot-setup/install.sh)Windows PowerShell
irm https://bot.ahvclaw.com/downloads/telegram-cli-bot-setup/install.ps1 | iexmacOS
bash <(curl -fsSL https://bot.ahvclaw.com/downloads/telegram-cli-bot-setup/install-mac.sh)Nếu cài trên server sản xuất, hãy giữ lại file .env hiện có. Script cập nhật được thiết kế để bảo toàn cấu hình token/model/chat id.
Cập nhật thủ công
Dùng khi muốn chủ động kéo bản mới nhất thay vì chờ timer.
Linux có systemd timer
sudo systemctl start telegram-cli-bot-package-update.service
sudo journalctl -u telegram-cli-bot-package-update.service -n 100 --no-pagerKiểm tra phiên bản sau update
cat /opt/bot/tg-claude-bot/VERSION
cat /opt/bot/tg-codex-bot/VERSION
systemctl is-active tg-claude-bot tg-codex-bot tg-grok-botWindows/macOS
Chạy lại trình cài đặt tương ứng. Đây là đường cập nhật/sửa lỗi chuẩn cho môi trường không dùng systemd.
Non-root ops SSH
Linux installer và add-bot-instance.sh tự cài AHV_OPS_SSH_PUBLIC_KEY vào proxy user. Quy tắc vận hành: khong dung SSH root cho bảo trì bot; login vào user chạy service.
ssh claudeproxy@SERVER_IP
ssh codexproxy@SERVER_IP
ssh grokproxy@SERVER_IPMuốn thay key thì set AHV_OPS_SSH_PUBLIC_KEY trước khi cài. Chỉ set AHV_OPS_SSH_KEY_INSTALL=0 cho host cố tình cô lập. Từ v0.0.160, updater runtime script cũng là transactional support asset để host already-current vẫn tự nhận logic backfill key. Từ v0.0.161, updater runtime tự có root helper để backfill key không phụ thuộc outer installer. Từ v0.0.162, package tự bật scoped sshd pubkey-auth drop-in bằng Match User claudeproxy,codexproxy,grokproxy khi host đang có PubkeyAuthentication disabled. Từ v0.0.163, updater verify cả AuthorizedKeysFile effective config bằng sshd -T -C user=... và reload bằng systemctl reload ssh || systemctl reload sshd, không restart daemon. Tu v0.0.164, overdue wakeup recovery canonicalizes legacy transcript cursor metadata after maintenance without replaying prompts. Tu v0.0.165, hosts with existing AllowUsers restrictions keep non-root ops SSH by appending proxy users safely; host-scoped user@host/user@CIDR patterns are preserved.
Thêm bot token mới
Khi cần làm việc đồng thời, hãy tạo thêm một bot instance riêng thay vì dùng chung một token. Mỗi instance có service, app dir và project dir riêng; updater vẫn cập nhật tất cả service đang active.
Thêm Codex Bot instance
curl -fsSL https://bot.ahvclaw.com/downloads/telegram-cli-bot-setup/add-bot-instance.sh | sudo bash -s -- codex main PASTE_CODEX_BOT_TOKEN 6348110855Thêm Claude Bot instance
curl -fsSL https://bot.ahvclaw.com/downloads/telegram-cli-bot-setup/add-bot-instance.sh | sudo bash -s -- claude support PASTE_CLAUDE_BOT_TOKEN 6348110855Thêm Grok Bot instance
curl -fsSL https://bot.ahvclaw.com/downloads/telegram-cli-bot-setup/add-bot-instance.sh | sudo bash -s -- grok lab PASTE_GROK_BOT_TOKEN 6348110855Kiểm tra
systemctl status tg-codex-bot-main --no-pager
journalctl -u tg-codex-bot-main -n 80 --no-pagerKhông dùng cùng một Telegram bot token cho hai service. Nếu muốn hai session song song, hãy tạo hai bot token khác nhau trong BotFather.
Login Codex và Claude CLI
Bot Telegram chỉ là lớp điều khiển. Codex CLI, Claude Code CLI và Grok CLI vẫn cần đăng nhập trên server bằng đúng Linux user chạy service. Mỗi CLI login một lần, token/session sẽ nằm trong home của user tương ứng.
Login Codex Bot
sudo -u codexproxy -H codex login --device-auth
sudo systemctl restart tg-codex-bot
sudo journalctl -u tg-codex-bot -n 80 --no-pagerLogin Claude Bot
sudo -u claudeproxy -H claude login
sudo systemctl restart tg-claude-bot
sudo journalctl -u tg-claude-bot -n 80 --no-pagerLogin Grok Bot
sudo -u grokproxy -H grok login
sudo systemctl restart tg-grok-bot
sudo journalctl -u tg-grok-bot -n 80 --no-pagerKiểm tra nhanh
sudo -u codexproxy -H codex --version
sudo -u claudeproxy -H claude --version
sudo -u grokproxy -H grok --version
systemctl is-active tg-codex-bot tg-claude-bot tg-grok-botNếu login mở link hoặc mã xác thực, hãy hoàn tất ngay trên terminal đó. Không chạy cùng một Telegram bot token cho cả Codex, Claude và Grok vì các service sẽ xung đột polling.
Thêm Telegram ID được phép dùng bot
Người dùng nhắn /whoami cho bot để lấy Telegram user id. Từ v0.0.29, Codex Bot, Claude Bot và Grok Bot tự đọc lại ALLOWED_USER_ID, ALLOWED_CHAT_ID, ALLOWED_TOPIC_ID khi file .env đổi, nên thêm ID xong nhận ngay không cần restart.
Thêm ID cho cả Codex và Claude
curl -fsSL https://bot.ahvclaw.com/downloads/telegram-cli-bot-setup/allow-telegram-id.sh | sudo bash -s -- both 638048624Chỉ thêm cho một bot
curl -fsSL https://bot.ahvclaw.com/downloads/telegram-cli-bot-setup/allow-telegram-id.sh | sudo bash -s -- codex 638048624
curl -fsSL https://bot.ahvclaw.com/downloads/telegram-cli-bot-setup/allow-telegram-id.sh | sudo bash -s -- claude 638048624Restart thủ công khi cần
sudo systemctl restart tg-codex-bot tg-claude-botLệnh sửa lỗi khi bot lỗi
Repair tải manifest và ZIP immutable vào thư mục tạm riêng của root, kiểm tra SHA-256, đường dẫn archive và VERSION nhúng, rồi cài package updater, timer CLI và CMS repair bridge từ đúng ZIP đã xác minh. Repair không tự restart bot; chỉ transactional updater được phép stop/start sau khi active-task gate đã qua.
Linux sửa toàn bộ bộ cập nhật + bot
curl -fsSL https://bot.ahvclaw.com/downloads/telegram-cli-bot-setup/repair.sh | sudo BOT_PACKAGE_BASE_URL=https://bot.ahvclaw.com/downloads/telegram-cli-bot-setup AUTO_UPDATE_NOTIFY_CHAT_ID=638048624 bashWindows sửa/cập nhật
irm https://bot.ahvclaw.com/downloads/telegram-cli-bot-setup/install.ps1 | iexmacOS sửa/cập nhật
bash <(curl -fsSL https://bot.ahvclaw.com/downloads/telegram-cli-bot-setup/install-mac.sh)Xử lý lỗi thường gặp
| Triệu chứng | Cách xử lý |
|---|---|
| Bot im, không trả lời Telegram | Kiểm tra service: systemctl status tg-claude-bot tg-codex-bot tg-grok-bot. Xem log: journalctl -u tg-claude-bot -n 120 --no-pager. |
| Claude có transcript nhưng Telegram không nhận kết quả cuối | Đảm bảo package từ v0.0.23 trở lên. Chạy cập nhật thủ công, sau đó kiểm tra log có Telegram sendMessage ok. |
| Grok chưa trả lời | Kiểm tra sudo -u grokproxy -H grok auth status hoặc đăng nhập lại bằng CMS remote login / sudo -u grokproxy -H grok login. |
| Model Claude bị từ chối | Kiểm tra CLAUDE_MODEL trong /opt/bot/tg-claude-bot/.env. Nếu model không còn quyền truy cập, đổi model hợp lệ rồi khởi động lại service. |
| Cập nhật lỗi do SHA256 không khớp | Không chạy zip đó. Tải lại manifest/zip, so sánh SHA256, kiểm tra public manifest trên domain mới. |
| Bot gửi được nhưng text bị thiếu | Xem log từng phần: Telegram sendMessage ok ... chars=... preview=.... Nếu không có dòng này, lỗi nằm trước bước gửi Telegram. |
Khôi phục stranded first rollout
Bản v0.0.138 chỉ tự khôi phục các máy bị mắc từ v0.0.132 đến v0.0.136 khi version global và instance trùng nhau, chưa có release pointer, và state chưa tồn tại hoặc là thư mục riêng tư 0700 hoàn toàn rỗng. Toàn bộ .env, session, lịch hẹn, usage và uploads cũ được giữ nguyên.
Mọi partial or ambiguous state đều bị từ chối. Không tự tạo, xóa hay sao chép SQLite database, marker, journal, WAL hoặc SHM để ép cập nhật.
Máy còn updater cũ cần chạy một lần đường repair public đã nêu ở trên. Sau đó CMS force update sẽ gọi repair bridge đã xác minh để luôn làm mới updater/timer trước activation. Timer CLI thử prefix riêng của proxy user trước, chỉ fallback sang npm global bằng root khi prefix cũ thực sự không ghi được, và không báo thành công nếu CLI không chạy được.
Phát triển tiếp
Repository gốc trên máy build:
C:\Users\Administrator\telegram-cli-bot-setupCác file chính:
claude-bot/bot.py: wrapper Telegram cho Claude Code.codex-bot/bot.py: wrapper Telegram cho Codex CLI.grok-bot/bot.py: wrapper Telegram cho Grok CLI.install-package-update-linux.sh: cài timer updater cho Linux.manifest.jsonvàVERSION: metadata public package.landing/bot-ahvclaw/: landing page và wiki public.
Checklist khi sửa code
python -m pytest -q test_package_update_assets.py
python -m unittest discover claude-bot
python -m unittest discover codex-bot
python -m py_compile claude-bot\bot.py codex-bot\bot.pyMọi fix bot phải sửa ở package gốc, bump version, rebuild zip, upload public và ép updater trên server cần cập nhật. Không được chỉ vá nóng live server rồi bỏ quên package.
Quy trình release
- Sửa code/tài liệu trong package gốc.
- Tăng phiên bản trong
VERSIONvàmanifest.json. - Đóng gói lại zip bằng script POSIX zip của workspace.
- Cập nhật SHA256 thật vào manifest.
- Chạy kiểm tra đầy đủ.
- Upload lên
ahvclaw:/srv/telegram-cli-bot-setup. - Kiểm tra HTTPS ở
bot.ahvclaw.comvà đường dẫn tương thích cũ. - Ép bộ cập nhật trên server cần nhận bản mới.
v0.0.211 transaction-backed updater rollback recovery release
v0.0.211 repairs package-updater recovery when a refreshed bootstrap updater is installed to rescue a host stuck in health-passed rollback recovery. The updater now restores the transaction-backed self-updater over that refreshed bootstrap copy while finalizing rollback metadata, so VpNrice can install the transcript startup fixes instead of remaining stuck on the failed v0.0.208 activation.
v0.0.210 missing intake gate rollback recovery release
v0.0.210 repairs package-updater recovery when an interrupted health-passed activation has already restored the old release and the durable intake gate is missing. The updater now finalizes rollback metadata so a newer public release can supersede the failed activation instead of looping on recovery status 42.
v0.0.209 stale transcript watch startup recovery release
v0.0.209 repairs Claude startup recovery when a stale transcript watch points behind delivery records that were already sent before context compaction. The startup scan now advances the watch through replayed delivered mandatory chains instead of restart-looping on a dependency mismatch.
v0.0.208 dangling pre-tool prelude release
v0.0.208 stops Claude transcript delivery from treating dangling pre-tool report preludes as final Telegram answers. Telegram now waits for the complete post-tool answer instead of sending clipped context-compaction fragments such as Em xac nhan du: before the tool result exists.
v0.0.207 transcript parse and model persistence release
v0.0.207 keeps Claude scheduled follow-ups stable when an old historical malformed transcript JSON line exists earlier in the same session. Later ScheduleWakeup turns are classified from the current turn instead of being poisoned by old parse damage, and /models selections persist across service restarts.
v0.0.206 transcript monitor fallback release
v0.0.206 lets Claude fall back to a committed stdout final when transcript monitor internals fail after spawn. Durable persistence failures still stay on the recovery path so storage safety is preserved.
v0.0.205 passive transcript watcher release
v0.0.205 keeps Claude passive transcript wakeup watchers out of the durable work lane. Already-queued passive wakeup rows are completed so they cannot hold chat busy while the background watcher waits for transcript progress.
v0.0.204 empty-stdout ScheduleWakeup release
v0.0.204 recovers Claude empty-stdout ScheduleWakeup turns as ordered schedule statuses. When Claude schedules a follow-up without final text, Telegram receives the wakeup status instead of bogus retry prompts.
v0.0.203 post-exit final release
v0.0.203 bounds Claude post-exit transcript final waiting and makes memory capture best-effort after delivery. That prevents lane-busy queues after a user-facing final has already been delivered while preserving transcript question release and durable recovery.
v0.0.202 terminal transcript question release
v0.0.202 releases Claude foreground work when a durable transcript question is committed for the active origin. Recovery reuses that committed terminal question instead of continuing Claude, preventing lane busy recovery loops and queued Telegram messages after the user-facing terminal question was delivered. Normal transcript final chunks still stream without closing active tool work early.
v0.0.201 delivered transcript fallback suppression
v0.0.201 suppresses Claude's no-final stdout fallback when a durable transcript question/final is already delivered for the same origin. That prevents bogus tool-still-running messages after a completed answer while preserving wakeup transition handling.
v0.0.200 Claude login code entry
v0.0.200 makes Claude Telegram /login code entry explicit and safer. Login responses now explain that browser auth codes can be submitted with /login <code> or /login code <code>, and private admin plain-code replies are routed into the active login session without enqueueing those codes as Claude prompts.
v0.0.199 OAuth auth classifier hardening
v0.0.199 stops Claude OAuth-expired retry spam without hiding transient auth outages. OAuth sessions that expired and cannot be refreshed remain terminal not-logged-in failures, but auth timeout, unreachable, and retry-later failures remain recoverable even when Claude reports loggedIn=false. Durable automatic retries no longer repeat the Em trả lời ngay đây... start/progress line. First attempts and queue receipts are preserved.
v0.0.197 final-only queue receipt
v0.0.197 keeps final-only chats responsive without re-enabling noisy thinking: /thinking off still suppresses live progress, but Claude sends one foreground queue receipt when a new task is accepted. Quota/logout terminal notices remain mandatory, and terminal retries never re-run Claude.
v0.0.196 unchanged watcher status suppression
v0.0.196 stops repeated pending-tool watcher status spam. Claude and Grok still forward new transcript progress, real final answers, explicit schedules, and background follow-up promises, but they no longer resend the unchanged tool chua tra ket luan cuoi watcher message on a timer.
v0.0.195 passive final close
v0.0.195 stops passive transcript watcher spam after Claude or Grok already sends a final answer that waits for user feedback. Same-text passive watchers are closed, explicit schedules are preserved, and mixed background-progress messages that promise a later update still keep their follow-up.