Skip to content
Time4MindPublic
forked from six-ddc/ccbot

About

DM-only Telegram bot for driving multiple parallel Claude Code sessions in tmux. Single user, bypass-only, MarkdownV2.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Β 
Β 

Repository files navigation

ccbot

test secrets-scan

δΈ­ζ–‡ζ–‡ζ‘£ Β· Русская докумСнтация

A personal Telegram bot for parallel Claude Code, Codex, ZCode, and OpenCode sessions running in tmux. Each session uses its own CLI. An inline switcher in the most recent bot message selects which session receives input.

Why

Your agent lives in the terminal. Walk away from the desk and you lose visibility β€” but the session keeps running. ccbot lets you:

  • Switch from desktop to phone mid-conversation. An agent is doing a refactor; you go for a walk and keep monitoring + replying from Telegram.
  • Switch back to the desktop anytime. Sessions live in real tmux windows, so tmux attach brings you straight back into the terminal with full scrollback.
  • Run several sessions in parallel. Each session is its own tmux window with its own agent process. Switching the active session in Telegram doesn't pause any of the others.

CCBot sends input to the native CLI in tmux and displays its output in Telegram.

Differences from upstream

This fork deviates from upstream ccbot in ways that are intentional and not negotiable:

  • DM-only. No supergroup, no forum topics, no thread routing. The only chat the bot ever sees is a private 1-1 DM with an allowlisted Telegram user id.
  • Personal, allowlist-gated. ALLOWED_USERS normally holds a single numeric Telegram id. Several ids are supported as a shared workspace β€” the session pool is global and every claude event is fanned out to each allowed user's own DM (own live card, own switcher). It is not multi-tenant: everybody sees everything. Any message from a non-allowlisted sender is silently dropped (no reply, no callback toast) β€” the bot looks inert to outsiders.
  • Bypass-only. Claude is launched with --dangerously-skip-permissions; Codex uses --dangerously-bypass-approvals-and-sandbox. There is no permission relay UI in Telegram β€” if you don't trust the model with full host access, run upstream instead. (The residual Yes/No prompts that bypass mode does not cover β€” e.g. WebFetch domain trust β€” surface as a keyboard, or can be auto-answered via Settings β†’ Auto-approve.)
  • Multi-session, inline-switcher. A single user can have many sessions in the same DM; an inline keyboard under the most recent bot message switches between them.
  • Rich messages first. Output goes out as a Bot API 10.3 rich message (native markdown: GFM tables ≀ 20 columns, headings, <details>, footnotes, math), falling back to the MarkdownV2 pipeline (telegramify-markdown) and then to plain text on any failure. Fenced shell commands (including PowerShell and cmd) become copyable code text so Telegram exposes Copy; source-code blocks retain their highlighting and layout. Existing absolute file paths become a filename stem plus an extension-only download button. Kill switch: CCBOT_RICH_MESSAGES=off. Upstream uses HTML.
  • Hook-based session tracking. Lifecycle hooks or the OpenCode plugin bind each tmux window to the native session ID. The monitor uses that binding for live output, history, and restore.
  • Voice transcription is local-first. Parakeet via NeMo-Speech.cpp (default, matching Bria), legacy whisper.cpp, or Apple Speech via PyObjC on macOS - no API key required to run.

The full design rationale lives in doc/dm-multisession-spec.md. The implementation map is in doc/dm-multisession-plan.md.

Prerequisites

  • tmux in PATH
  • At least one native CLI installed and available on the host. CCBot supports Claude Code (claude), Codex (codex), ZCode (zcode), and OpenCode (opencode). See backend setup for login and hooks.
  • Python 3.12+
  • uv (recommended) for dependency management
  • macOS (Apple Silicon) or Linux x86_64/arm64

Optional:

  • ffmpeg + nemo-speech and the Parakeet q8 model for the default local voice transcription backend
  • pyobjc-framework-Speech for the native Apple Speech backend (uv sync --extra apple-speech)

Quick start

git clone https://github.com/Time4Mind/ccbot.git
cd ccbot
uv sync
cp .env.example ~/.ccbot/.env   # fill in TELEGRAM_BOT_TOKEN + ALLOWED_USERS
ccbot hook --install --backend claude  # use the backend you installed
ccbot                           # foreground; for prod use the systemd unit

A full step-by-step Linux install (written for an AI agent to follow) lives in doc/install-linux.md. Automatic worker-node connection through the direct CLI handle is documented in doc/multi-node-bootstrap.md.

Configuration

Required env vars in ~/.ccbot/.env (or ./.env):

Variable Description
TELEGRAM_BOT_TOKEN Bot token from @BotFather
ALLOWED_USERS Single Telegram numeric user id

Most-frequently-tweaked optionals:

Variable Default Effect
CCBOT_DIR ~/.ccbot Config and state directory
TMUX_SESSION_NAME ccbot tmux session that holds all session windows
CCBOT_AGENT_BACKEND claude initial backend (claude, codex, zcode, opencode) for a new state file
CLAUDE_COMMAND claude binary used to start a session
CLAUDE_FLAGS --dangerously-skip-permissions flags appended to claude
CODEX_COMMAND codex Codex CLI binary (an absolute Termux path is accepted)
CODEX_FLAGS bypass + hook trust + hooks + --no-alt-screen flags appended to codex
ZCODE_COMMAND zcode installed official ZCode CLI
ZCODE_FLAGS --mode yolo --locale en-US native TUI flags
OPENCODE_COMMAND opencode official OpenCode CLI
OPENCODE_MODEL openai/gpt-6-luna initial and naming model using OpenCode's own OAuth login
CODEX_NAMING_MODEL gpt-5.6-luna lightweight Codex model for automatic session names
ARCHIVE_PURGE_AFTER 20d archived sessions purged from state after this
QUOTA_ALERT_POLL_INTERVAL 10m how often the live /usage modal is sampled
VOICE_BACKEND auto auto / parakeet / whisper / apple / off; auto selects Parakeet
PARAKEET_BIN nemo-speech NeMo-Speech.cpp binary
PARAKEET_MODEL_PATH ~/.ccbot/models/parakeet-tdt-0.6b-v3.q8_0.gguf Bria-compatible local Parakeet model
WHISPER_MODEL_PATH ~/.ccbot/models/ggml-medium-q8_0.bin whisper.cpp model (falls back to a pre-existing ggml-medium.bin)
WHISPER_LANG_MODEL_PATH ~/.ccbot/models/ggml-tiny.bin tiny model for the language-detect pre-pass
WHISPER_LANG_DEFAULT ru language assumed when detection isn't confident
WHISPER_THREADS 6 threads for whisper-cli (its own default is 4)
BG_STATUS_MAX 4 max badges in the bg-status panel; older entries collapse to +N more
CARD_EDIT_LAG 2.0 coalescing window for live-card edits (seconds)
CCBOT_FILE_DELIVERY_CONCURRENCY 3 global background file-delivery limit; one active delivery per user
CCBOT_FILE_WORKER_TIMEOUT 2m timeout for fetching one worker file
CCBOT_FILE_TELEGRAM_TIMEOUT 2m timeout for one Telegram document upload
CCBOT_RICH_MESSAGES on off disables Bot API 10.3 rich messages (MarkdownV2 only)
CCBOT_HOST hostname deployment label exported to sessions as CCBOT_HOST
TG_PROXY_URL (unset) outbound proxy for the Bot API (socks5://… or http://…)
TG_MEDIA_PROXY_URLS (unset) ordered JSON array of voice retry proxies; direct first, up to 10 total attempts
TG_MEDIA_PROXY_URL (unset) opt in to alternating proxy/direct voice download retries; supplies the proxy when TG_PROXY_URL is unset
TG_DISABLE_IPV6 false use IPv4 for direct Bot API requests and polling; leaves proxy routing unchanged (TG_FORCE_IPV4 is a legacy alias)
CCBOT_POLL_STALE_SECONDS 180 exit non-zero when real getUpdates has not completed successfully for this long
CCBOT_POLL_STARTUP_GRACE_SECONDS 180 grace before the first successful poll is required
CCBOT_POLL_HEALTH_FILE ~/.ccbot/poll-health.json atomic local polling-health state; use /run/ccbot/poll-health.json in Docker

The full list lives in .env.example and in doc/dm-multisession-spec.md Β§ 12. Per-user UI preferences (card size, notifications, voice backend, language, …) are not env vars β€” they live behind ≑ Menu β†’ Settings, see below. The agent is also a persisted setting at Settings β†’ Agent: enable backends and choose the default for new sessions. Existing sessions retain their backend. CCBOT_AGENT_BACKEND is only the initial default when the state file has no saved selection.

Docker polling health

ccbot records progress only after the dedicated PTB getUpdates request returns successfully, including an empty long-poll response. If that heartbeat stays stale while the event loop remains healthy, the OS-thread watchdog exits PID 1 non-zero. With restart: unless-stopped, Compose then replaces the whole container instead of leaving an alive-but-deaf bot running.

Use deploy/docker-compose.healthcheck.yml as an override for Docker health observability. Docker/Compose marks stale polling as unhealthy, but health status alone does not restart a container; the in-process watchdog is the primary restart actuator. A host fallback should be a narrowly scoped systemd unit allowed to restart only the named ccbot container. Do not mount the Docker socket into a third-party autoheal container.

Backend setup

Install the hooks or plugin for each CLI you plan to enable. In Telegram, use Menu β†’ Settings β†’ Sessions and backends β†’ Agent to enable backends and set a default. With multiple backends available on the selected node, the new-session picker asks which to use before opening the directory browser.

Claude Code and Codex

Claude Code and Codex use SessionStart and UserPromptSubmit to track native session IDs. Codex supports its device-code sign-in flow through Telegram.

ccbot hook --install

The Codex hooks are installed in ~/.codex/hooks.json.

ccbot hook --install --backend codex

ZCode

Install the official Agent CLI and configure its provider on the host. Then install its lifecycle hooks.

ccbot hook --install --backend zcode

ZCode uses its native TUI and --resume sess_<uuid>. CCBot reads the native SQLite store in read-only mode and writes a separate history to $CCBOT_DIR/zcode-transcripts/. ZCODE_SESSION_DB_PATH selects a custom store. The provider configuration remains in ~/.zcode/v2/provider_config.json (or ZCODE_PERSONAL_PROVIDER_CONFIG_FILE); never put a key in a launch command.

The ZCode model selector uses direct Telegram buttons, with a checkmark on the current model, like Codex. Effort and mode selectors use the Telegram arrow controls. Cancel also clears the selector's command draft. /compact, /stop, history, archives and cross-agent handoff use the existing surfaces. Image support follows the selected model. Usage reports recorded session tokens; absent account quotas/reset times remain unknown.

See the backend contract. The opt-in real-provider acceptance is CCBOT_RUN_ZCODE_LIVE=1 uv run pytest tests/ccbot/test_zcode_live.py; it uses isolated fixtures and restores temporary user-hook configuration.

OpenCode

Install the official OpenCode 1.x CLI. Sign in to OpenAI with ChatGPT Pro/Plus inside OpenCode, then install the CCBot lifecycle plugin.

opencode auth login --provider openai
ccbot hook --install --backend opencode

OpenCode uses --session ses_... for native resume. CCBot reads SQLite snapshots in read-only mode and writes its own history to $CCBOT_DIR/opencode-transcripts/. In local sessions, /model shows named Telegram buttons from the actual OpenCode catalogue and then the selected model's effort variants. OPENCODE_MODEL sets the initial model and naming model used by CCBot. OpenCode launches outside CCBot use OpenCode's own config.

The menu shows recorded OpenCode token usage. It also shows the shared Codex quota as OpenCode Β· Codex when both CLIs are verified to use the same local ChatGPT account. See the OpenCode backend contract.

Archived sessions retain their original backend. Restoring an archive into a different backend performs a cross-agent pickup. CCBot parses the source JSONL into a bounded handoff, starts a fresh native target session, and records both the new target id and the source provenance. The source transcript is never modified.

Codex-on-Termux setup is documented in doc/install-termux.md.

The installer is per-event idempotent β€” re-running it on an older SessionStart-only install just adds the missing entry.

Or add manually to ~/.claude/settings.json:

{
  "hooks": {
    "SessionStart": [
      { "hooks": [{ "type": "command", "command": "ccbot hook", "timeout": 5 }] }
    ],
    "UserPromptSubmit": [
      { "hooks": [{ "type": "command", "command": "ccbot hook", "timeout": 5 }] }
    ]
  }
}

Usage

The bot exposes a small slash-command surface in the Telegram /-menu plus an inline ≑ Menu button on the most recent bot message:

Command Effect
/menu Open the inline ≑ Menu screen
/help Inline mini-doc with section buttons
/model Open the active backend's model picker
/fast Toggle Fast mode in the active Codex session

A few more commands work when typed but stay out of the /-menu: /new, /kill, /stop, /archive, /usage, /clear, /cost, /health, /login, /delivery, /requests.

/delivery shows final answers waiting for Telegram delivery. Connection failures retry after 1, 2, 4, 8, then at most 15 seconds, including after a bot restart. Telegram flood waits may be longer. If Telegram may have accepted a new message but its acknowledgement was lost, automatic resending stops: check the chat, then use /delivery to confirm receipt or explicitly retry.

/requests shows accepted voice requests awaiting recovery and requests queued behind them. Temporary Telegram outages retry in the background and survive a restart; switching sessions keeps each request bound to its original session. If agent submission cannot be confirmed, automatic resending stops. Check the original session, then use /requests ack <message-id> to confirm submission or /requests cancel <message-id> to release the queue without resending. A terminal error whose Telegram acknowledgement was lost also remains visible here; after reading it, acknowledge it with /requests ack <message-id>.

/login β€” re-authenticating Claude from the phone. When the OAuth login behind claude expires, every session starts failing and there is normally no way to fix it without a desktop. The bot needs no Claude auth of its own, so it notices the failure, posts a πŸ” notice, and /login runs the exchange for you: it hands you the OAuth link, you approve it in the phone browser (the redirect goes to platform.claude.com, not a localhost callback, so no tunnel is needed), and you send the code the page shows back as an ordinary message. The bot feeds it to the waiting process, confirms the new deadline, and deletes your message with the code. It then reposts the active session's card (or the Menu, if no session is active) so you carry on where you were instead of scrolling back past the exchange.

With the Codex backend, authentication starts automatically on a fresh bot launch. The bot checks account/read through Codex app-server; when no account is present it sends the official device-login URL and user code to Telegram, waits for account/login/completed, and then unlocks session creation. The code is entered on the OpenAI page and is never sent back to the chat. /login manually restarts the same flow.

The notice fires on Claude Code's own error entry (isApiErrorMessage / authentication_failed), not on the error text β€” a session that merely writes about a dead login won't trigger it. A fresh login moves the credential deadline out by ~30 days; that deadline is the only thing that matters, since refresh-token rotation keeps it fixed.

The four remaining actions live behind the menu - Sessions, Archive, New, Settings. The current quota table is embedded above them. Every Menu tap paints cached limits immediately, marks their age with ⏳, and refreshes them in the background. The active card has an Options button; when expanded it shows the configured actions above the session switcher. The screenshot action toggles terminal images globally, while Terminal opens only the current session. Terminal is hidden by default. Most users never type slash commands at all once they discover the menu.

Sessions and switcher

Send any text in the DM to start your first session β€” the bot opens a directory browser, you pick the project, and a tmux window with the selected agent starts there. Subsequent text in the DM is routed to the active session.

Opening Menu, New, Archive, or Settings gives that screen exclusive ownership of the current card message. The selected session keeps running in the background and buffers card updates until its card is shown again. Back from the new-session flow returns directly to that card; confirming a directory atomically turns the same message into the new session's card while the agent continues starting asynchronously.

Directory rows paint immediately from cached or shallow filesystem/Git metadata. One background pass computes nested-content recency for every visited directory at once; generated dependency/cache trees are ignored.

Sessions are named after the directory basename and renamed once after the first message of β‰₯ 20 chars by a small separate request: Haiku for Claude or CODEX_NAMING_MODEL for Codex (default gpt-5.6-luna). The result is a two-word intent summary such as token budget. Disable automatic names in Settings to retain the directory name and skip the extra model call.

The most recent bot message carries an inline session switcher (β–· session-A Β· session-B) with a paired [+ new] [≑ Menu] row anchored at the bottom β€” the two "go-elsewhere" affordances sit side-by-side so the slot stays put across views ([+ new] [Back] takes that spot in Menu β†’ Sessions / Archive).

Switcher buttons read oldest β†’ newest: each session keeps the same slot for its whole life and a newly created one appends to the right, so muscle memory survives switching. Restoring a session from the archive re-enters it as the newest button rather than in its original slot.

Tapping a non-active session paints the full transcript history of that session onto the carrier message and switches the active session in one go. Pagination buttons (β—€ Older / Newer β–Ά) keep the footer keyboard under them β€” they're the navigation affordance, so there is no separate "History" entry in the Menu. Tapping the already-active button is a no-op.

Reply-quoting a bot message belonging to a non-active session routes that single reply there without changing the active session.

Menu β†’ Archive shows a numbered list of past sessions, two buttons per row. Each row carries a short blurb made only from the user's first messages, so it's obvious at a glance what a session was about. A model-generated summary never replaces that text. Tap a session β€” the carrier paints the actual transcript read straight from the JSONL on disk; Restore / Delete stay in the footer.

Background sessions

Background sessions, including the selected session while a non-card screen is open, have no writable live card of their own β€” they never edit the current screen or surface an AskUserQuestion prompt in chat. Their state surfaces as a compact panel at the bottom of the active session's card:

🟦 session-A πŸ”Ά        ← working in background
πŸŸͺ scraper   βœ…        ← finished
🟧 chores    ❌        ← errored
🟨 frontend  ❓        ← needs user action (AskUserQuestion / permission)

The panel sticks across active-card edits so a finished bg session isn't lost above a long tool log. The first entry into a completed session keeps βœ…; only the second entry changes it to β˜‘οΈ. Actions inside it and leaving for another session do not increment that counter. If the badge shows ❓, the switcher tap paints the stashed AskUserQuestion / ExitPlanMode prompt with the same arrow/Enter/Esc keyboard you'd get on a foreground prompt.

On top of the badge, a background session can push a short one-liner (βœ… [scraper] task complete) on a state transition. Three independent toggles under Settings β†’ πŸ”” Notifications, all on by default: Bg: task complete, Bg: errors, Bg: needs action. Turn them off to keep background work entirely silent.

Live card

Each active session owns one live card message that the bot keeps editing β€” header, paginated body, bg panel, footer keyboard. Every message you send reposts the card below your text (there is one canonical behaviour; the old Card position setting was retired). Above the bg panel it prints the session's context: N% β€” Codex uses exact token_count rollout data, while Claude uses an approximation of Claude Code's /context computed from the JSONL, typically within Β±10 % of the modal.

Card knobs live under Settings β†’ πŸƒ Card / view:

Setting Default Effect
Card history 20 end-of-turn boundaries seeded into a fresh card from the JSONL (survives bot restarts)
Page size 20 lines max lines per card page; longer bodies chunk across pages on paragraph/sentence boundaries
Screenshot capture 48 KiB maximum newest terminal-text suffix used for the image
Screenshot quality 100%, optimized image scale and colour profile
Live lag 4s coalescing window for preview updates

Screenshot and Terminal button visibility lives under Settings β†’ Options buttons. Screenshot visibility defaults on, Terminal off. Expanding Options and tapping Screenshot toggles the global screenshot state without leaving the active card. The latest pane image persists through IDLE. Its order is body β†’ gap β†’ pane β†’ gap β†’ context β†’ background panel. Rich-capable Bot API servers keep text and media in one Rich Markdown message. If rich media is unavailable, the same carrier falls back to text-only and retries on a later ordinary card update. If an unfinished turn goes silent, the active card keeps its pane instead of inserting a warning or sending a push. The same condition on a background session is shown only as ⚠️ beside that session in the background panel.

Telegram's chat-header typing… indicator is driven by real claude events. As long as the active session keeps emitting (tool calls, thinking, text), typing… stays on; an idle session lets it fade within Telegram's ~5s window.

Other settings

≑ Menu β†’ Settings includes πŸƒ Card / view, πŸ”” Notifications, πŸŽ™ Voice, πŸ–₯ Local terminal, 🧩 Option buttons, and βš™ Behavior & language. Worth knowing:

  • Auto-approve (off by default) β€” auto-answers the interactive Yes/No prompts that --dangerously-skip-permissions doesn't cover (WebFetch domain trust and friends). When an auto-Yes doesn't clear the prompt, the bot escalates to the manual keyboard instead of looping.
  • Local terminal selects a Linux emulator where required. Button visibility is configured separately under Option buttons; terminals are never opened automatically for a new session.
  • Weekly reset β€” only needed for Claude, whose /usage reports a clock time but not a complete timestamp. Codex supplies its exact reset timestamp through app-server.
  • Language β€” en / ru / zh for the bot's own UI strings.

Quota in Menu

The quota table embedded in ≑ Menu uses the selected backend's authoritative source. There is no separate Status or Refresh button:

  • Claude: its live /usage modal through the dedicated ccbot-usage tmux window;
  • Codex: account/rateLimits/read from the supported app-server API, without typing into a working session.

Claude retains the compact display:

Claude Code
🟑 5h: 62% · 12.4%/h · 17:00
🟒 week: 28% · 4.0%/d · Mon 17:00
🟒 week (Sonnet): 12% · Mon 17:00

For Codex, the weekly block focuses on the actionable calendar-day budget:

OpenAI Codex

🟒 5h

Used: 12%

Reset: 14:30

🟒 week

Used: 50%

Today: another 10.0%

Reset: 05.08 17:00

At the start of each local calendar day, the remaining weekly quota is split equally across today and every remaining date through the reset date, inclusive. The day's allocation stays fixed while Today decreases by actual usage. Overspend is rendered as over by N%. On the next date, the real remaining pool is redistributed, so both over- and underspend adjust all following days. The daily baseline lives in $CCBOT_DIR/codex_quota_day.json and survives bot restarts.

Claude's background poll runs every QUOTA_ALERT_POLL_INTERVAL and pushes an alert when a 5h or weekly band crosses 50 / 75 / 90 %. Only settled reads are published, so a half-rendered modal can't fire a phantom alert.

Voice and media

  • Voice messages are transcribed locally (Parakeet by default; whisper.cpp / Apple Speech) and routed to the active session as if you typed them. The card shows a pending marker while the transcription runs, then the transcribed text in place, so you can verify what Claude received. On the arm64 reference host a voice message costs ~9s end to end: quantised ggml-medium-q8_0 (1.8Γ— faster than fp16, identical transcripts on the ru/en samples) plus a ggml-tiny language-detect pre-pass that lets the real run pin -l and encode once. Missing binary or model? Settings β†’ πŸŽ™ Voice offers a one-tap install (builds whisper.cpp, downloads both models).
  • Ordered voice retry routes: set TG_MEDIA_PROXY_URLS to a JSON array, for example ["http://127.0.0.1:1081", "socks5://127.0.0.1:1082"], using only your reachable proxies. The first attempt is always direct, regardless of the polling proxy; then each proxy in order, then the cycle repeats. Exact duplicate URLs are removed. An empty array explicitly selects direct-only retries. This setting takes precedence over the older single-proxy option. There are at most 10 total download attempts, including the single optional MTProto attempt and rate-limit responses. A rate limit's prescribed delay is respected before the next attempt. getFile and its file read share a route; successful downloads and permanent errors stop the cycle immediately. The existing recovery journal preserves the consumed budget and MTProto state across restart, including interrupted attempts. Explicit manual retry resets the budget. Polling, message delivery and STT configuration stay unchanged. This does not shorten timeouts or race requests; a slow successful response can still delay the download.
  • Legacy single-proxy voice routes: set TG_MEDIA_PROXY_URL to a reachable proxy to alternate failed voice download attempts between proxy and direct. The first attempt uses the bot's normal route (TG_PROXY_URL, or direct). If the normal route already uses a proxy, that proxy is reused. Each subsequent network failure switches route, including the single optional MTProto attempt. getFile and its file download stay on the same route. Polling, message delivery, and speech recognition keep their existing configuration. The limit remains five Bot API network failures plus at most one MTProto attempt; rate limits wait on the same route and permanent errors are not retried. This does not race requests or shorten timeouts, so a slow successful response may still take time.
  • Optional voice download recovery: install the voice-mtproto extra and set TG_MEDIA_MTPROTO_FALLBACK=1, TG_API_ID and TG_API_HASH in the bot's service configuration. After the first Bot API network failure, one bounded MTProto download is attempted using the same bot token and TG_PROXY_URL (or the next route when alternating voice routes are enabled). No user account or second update poller is involved. The temporary authorization stays in RAM and is logged out after the attempt; API credentials are removed from child-process environments. Only v4 voice document IDs and declared Ogg payloads up to 20 MiB are accepted. Unsupported data, missing dependencies, or fallback errors leave the original bounded retry/queue recovery in place. The fallback is off by default. Permanent Bot API errors and rate limits do not trigger it.
  • Photos and documents drop into <workdir>/.ccbot-inbox/ and Claude is told via tmux. Files are auto-cleaned 24h after upload.
  • Forwarded posts with media (channel posts with video / GIF / sticker that carry a caption) have the caption + any hidden text_link URLs extracted and routed to the active session, prefixed with [forwarded from @channel]. The media payload itself is dropped β€” Claude can't consume it.

Architecture

The full module map is .claude/rules/architecture.md; the responsibility-level extension guide is doc/refactor-architecture.md. At a glance:

src/ccbot/
β”œβ”€β”€ main.py                 β€” CLI entry point (`ccbot`, `ccbot hook`)
β”œβ”€β”€ config.py               β€” env-var loader (singleton)
β”œβ”€β”€ session.py              β€” SessionManager compatibility facade / resume flow
β”œβ”€β”€ session_state.py        β€” routing, lifecycle, settings, state.json
β”œβ”€β”€ session_map.py          β€” hook/window binding reconciliation
β”œβ”€β”€ session_monitor.py      β€” JSONL polling, NewMessage callbacks
β”œβ”€β”€ codex_session_io.py     β€” Codex rollout JSONL discovery and reading
β”œβ”€β”€ codex_auth.py           β€” account/read + device-code login
β”œβ”€β”€ codex_usage.py          β€” Codex app-server rate limits
β”œβ”€β”€ session_import.py       β€” cross-agent restore handoff
β”œβ”€β”€ transcript_parser.py    β€” JSONL parser compatibility facade
β”œβ”€β”€ transcript_*.py         β€” message/Codex/type-specific parsing
β”œβ”€β”€ terminal_parser.py      β€” interactive-UI + status-line detection
β”œβ”€β”€ terminal_usage.py       β€” /usage models and parsing
β”œβ”€β”€ tmux_manager.py         β€” libtmux wrapper
β”œβ”€β”€ rich.py                 β€” Bot API 10.1 rich messages (native markdown)
β”œβ”€β”€ markdown_v2.py          β€” MD β†’ Telegram MarkdownV2 (fallback path)
β”œβ”€β”€ telegram_sender.py      β€” split_message at 4096-char limit
β”œβ”€β”€ transcribe.py           β€” voice β†’ text dispatcher
β”œβ”€β”€ voice_install.py        β€” whisper.cpp + model auto-installer
β”œβ”€β”€ local_terminal.py       β€” native-terminal attach helper
β”œβ”€β”€ usage.py                β€” token aggregator, context %, alert logic
β”œβ”€β”€ i18n.py                 β€” translation service compatibility facade
β”œβ”€β”€ i18n_locales/           β€” en / ru / zh UI catalogs
β”œβ”€β”€ bot/                    β€” Telegram-facing handlers (≀ 600 LOC each)
β”‚   β”œβ”€β”€ app.py              β€” bootstrap/watchdog compatibility facade
β”‚   β”œβ”€β”€ _app_*.py           β€” lifecycle and handler registration
β”‚   β”œβ”€β”€ messages.py         β€” inbound compatibility facade
β”‚   β”œβ”€β”€ _messages_*.py      β€” text / voice / media / shared delivery
β”‚   β”œβ”€β”€ session_events.py   β€” claude β†’ TG dispatch
β”‚   β”œβ”€β”€ commands/           β€” slash command bodies
β”‚   └── callbacks/          β€” one file per CB_* prefix
└── handlers/
    β”œβ”€β”€ notifications.py    β€” live-card compatibility facade
    β”œβ”€β”€ card_model.py       β€” card-model compatibility facade
    β”œβ”€β”€ card_*.py           β€” state / render / paginate / transport / lifecycle
    β”œβ”€β”€ bg_status.py        β€” background-session status panel
    β”œβ”€β”€ archive.py          β€” /archive page rendering + idle sweeps
    β”œβ”€β”€ quota_alerts.py     β€” background /usage poll
    β”œβ”€β”€ interactive_ui.py   β€” AskUserQuestion / ExitPlanMode
    β”œβ”€β”€ menu.py             β€” inline-keyboard composition
    └── …

State is kept under $CCBOT_DIR (defaults to ~/.ccbot/):

File Contents
state.json sessions, active_sessions, window states, user settings
session_map.json hook-generated tmux-window β†’ agent-session map
monitor_state.json per-JSONL byte offsets (prevents duplicate notifications on restart)
codex_quota_day.json Codex daily baseline and allocation
ccbot.lock exclusive flock held by the running bot; a second start refuses with exit 1

Reliability

  • Single instance. main.py holds an exclusive flock on ccbot.lock for its whole lifetime, so a supervisor restart racing a manual launch can't produce two bots fighting over getUpdates.
  • Long-poll watchdog. A thread-based liveness check notices a silently hung long-poll, and a sustained network outage makes the process exit rather than sit there mute β€” the supervisor/systemd restarts it once the network is back.
  • Startup recovery. Sessions whose tmux window survived are re-attached, vanished ones are marked lost (with a Restore button), and tmux windows bound to nothing are logged as orphans rather than killed.

Deployment

A systemd unit is at scripts/ccbot.service; hosts with a flaky uplink can instead run scripts/ccbot-supervisor.sh, which waits for network before each start and restarts with backoff. For VPS hosts that can't reach api.telegram.org directly, see doc/deploy.md for the TG_PROXY_URL SSH-tunnel recipe.

Contributing

See CONTRIBUTING.md. The short version: PRs that align with the DM-only / personal-allowlist / bypass-only invariants are welcome. CI must be green; pre-commit hooks must pass; one PR, one purpose.

Security

See SECURITY.md for the threat model and reporting process. Vulnerabilities go through GitHub Security Advisories, not public issues.

License

See LICENSE.

About

DM-only Telegram bot for driving multiple parallel Claude Code sessions in tmux. Single user, bypass-only, MarkdownV2.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages