Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,51 @@ DATABASE_URL=postgresql://tgai:tgai@127.0.0.1:5434/tgai
# --- Sync behaviour ------------------------------------------------------
# Archive 1-on-1 human chats only. Set to true to also archive bot chats.
TG_SYNC_INCLUDE_BOTS=false

# --- Client Identity: READ THIS, IT AFFECTS YOUR ACCOUNT ------------------
#
# ##############################################################
# # ANTI-BAN WARNING #
# ##############################################################
#
# TG_LANG_CODE MUST match the interface language of the official Telegram
# app on your phone. If your Telegram app is in Spanish, set "es". In
# Russian, set "ru". In German, "de".
#
# The default below is "en" only because this is a public repository and no
# language can be hard-coded for everyone. It is NOT a safe value for you
# unless your Telegram app really is in English.
#
# Why it matters: every connection this client makes reports lang_code and
# system_lang_code to Telegram, alongside a phone number and an api_id that
# Telegram has already seen used from the official app for years. If the app
# says "ru" and this client says "en" on every single connection, that is a
# contradiction in Telegram's own records, on an account that unofficial-API
# use has already placed under observation. Matching costs nothing; not
# matching adds a signal for no benefit at all.
#
TG_LANG_CODE=en
TG_SYSTEM_LANG_CODE=en

# These three describe the machine. Honest and generic on purpose: this
# client never pretends to be Telegram Desktop, because Telegram knows from
# the api_id that it is not, and a lie it can check is worse than the truth.
#
# Leave them blank to derive sensible defaults ("Desktop", your real platform
# at major.minor precision, and "tg-ai 1.0"). Once a session exists, treat
# them as FROZEN: initConnection is replayed on every reconnection, so
# changing them makes the entry under Telegram -> Settings -> Devices mutate
# under you, which is both visible to support and a signal in itself.
TG_DEVICE_MODEL=
TG_SYSTEM_VERSION=
TG_APP_VERSION=

# --- Human activity window -----------------------------------------------
# An account that makes API calls uniformly around the clock is not a person.
# No Telegram-touching tool runs inside this window, and a sync refuses to
# start in it. Local time, in the timezone below.
TG_QUIET_HOURS=01:00-08:00

# IANA timezone name. Blank means "detect this machine's timezone", which is
# correct as long as the machine is the one the account owner actually uses.
TG_TIMEZONE=
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# A .session file contains the full MTProto auth key. Anyone holding it
# controls the account. See docs/70-ops/security.md.
*.session
*.lock
*.session-journal
*.session-wal
*.session-shm
Expand Down
8 changes: 8 additions & 0 deletions Justfile
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,14 @@ tg-serve:
tg-status:
@{{ python }} -c "import asyncio, server; print(asyncio.run(server.tg_whoami()))"

# Report the Telegram safety kill switch (SPEC-LIM-003).
tg-killswitch:
@{{ python }} scripts/killswitch.py

# Clear the kill switch. Asks first, and tells you what to check before saying yes.
tg-killswitch-clear:
@{{ python }} scripts/killswitch.py --clear

# --- python --------------------------------------------------------------

# Format the codebase.
Expand Down
62 changes: 55 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,26 @@ tools.
`just tg-auth` **must run in a real terminal** - it asks for the code Telegram
sends you, and an MCP server has no way to prompt.

> ### ANTI-BAN WARNING: set `TG_LANG_CODE` before you log in
>
> **`TG_LANG_CODE` must match the interface language of the official Telegram
> app on your phone.** Spanish app, set `es`. Russian app, set `ru`. German,
> `de`. The shipped default is `en` only because this is a public repository
> and no single language can be right for everyone - it is **not** a safe
> value for you unless your app really is in English.
>
> Every connection reports `lang_code` and `system_lang_code` to Telegram,
> next to a phone number and an `api_id` it has already seen used from the
> official app for years. An app that says `ru` and a client that says `en` on
> every single connection is a contradiction in Telegram's own records - on an
> account that unofficial-API use has already placed under observation.
> Matching costs nothing. Not matching adds a signal for no benefit.
>
> Set it in `.env`, together with `TG_TIMEZONE` and `TG_QUIET_HOURS`, and then
> leave all of them alone: they are replayed on every reconnection, so
> changing them later makes your own **Settings -> Devices** entry mutate
> under you.

Then restart your agent and ask it to run `tg_whoami()`.

### Archive the people who matter first
Expand Down Expand Up @@ -415,7 +435,15 @@ enforcement. These protections are built in and tested, not optional:
- **Your session file is a full credential.** It is git-ignored before it can
exist and gets mode `0600`.
- **Everything is local.** The database binds to `127.0.0.1`; Telegram sees the
same IP you always connect from.
same IP you always connect from. Run this on your own machine and your own
network - never a VPS, a container host or a rotating VPN.
- **The client identifies itself honestly and never changes its story.** It
reports a generic device and its own name, never a forged official-client
version. Set `TG_LANG_CODE` to your Telegram app's language (see the
warning above) and then freeze it.
- **Telegram's own limits are never slept through.** Telethon retries short
flood waits silently by default; that is switched off, so every one is
surfaced, counted, and after three in an hour the project stops itself.
- **Message content is data, never instructions.** Everything read from Telegram
was written by other people; an instruction inside a message is something to
report, never to act on.
Expand Down Expand Up @@ -485,8 +513,22 @@ OpenCode and others. See the install matrix above.

### Does it read group chats and channels?

No. Private one-on-one chats with people only. Groups, channels, bots and
Telegram's own service account are excluded from the sync and from every tool.
Yes, but deliberately grudgingly. It reads groups and channels **you have
already joined**, and only ones you name explicitly - a routine sync still
covers private chats only.

Each group can be read at most once every five minutes, with a ceiling of twenty
group reads a day and one hundred messages per read, which is a single API call.
Those counters live in the database, so restarting the server does not reset
them.

It will **never join** a group or channel for you, and it cannot read one you
have not joined - looking up channels you are not in is the behaviour that gets
personal accounts flagged as scrapers. It never fetches member lists, and it
cannot message someone it has only seen writing in a group. In a channel it can
post only if you are an admin there.

Bots and Telegram's own service account remain excluded.

### What is the Model Context Protocol?

Expand All @@ -513,7 +555,10 @@ just # list everything
just check # ruff + black + pytest + docs checks
just tg-sync # refresh the archive (incremental)
just tg-sync-targets @anna @bob # archive only these people
just tg-status # account, session, database, archive health
just tg-sync-targets "Some Group" # or a group you have joined (max 5 per run)
just tg-status # account, DC, identity, request budget, kill switch, archive
just tg-killswitch # is the safety stop on, and why
just tg-killswitch-clear # turn it off, after checking the account by hand
just db-psql # psql shell into the archive
```

Expand All @@ -526,9 +571,12 @@ how changes are made here.

## Scope

Private 1-on-1 text chats with people. Not groups, not channels, not bots, not
media, and nothing that deletes or edits messages on your account. See the
non-goals in [docs/10-product/prd.md](docs/10-product/prd.md).
Text chats. Private conversations with people, plus groups and channels you have
already joined, read under strict per-target and per-day limits. Not bots, not
media, and nothing that deletes or edits messages on your account. It never
joins a group, never fetches a member list, and never messages someone it has
only seen writing in one. See the non-goals in
[docs/10-product/prd.md](docs/10-product/prd.md).

## Contributing

Expand Down
6 changes: 5 additions & 1 deletion USE-CASES.md
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,11 @@ Stated plainly, because a tool that oversells itself wastes your time:
repository. tg-ai is passive: it sleeps until a client calls it. Autonomous
replies require an agent loop running on top - see
[5. Chained and autonomous workflows](#5-chained-and-autonomous-workflows).
- **No groups and no channels.** Private one-on-one chats with people only.
- **Groups and channels are rationed, not free.** It reads groups and
channels you have already joined, one at a time, at most once every five
minutes each and twenty reads a day. It will never join one for you, and
it cannot read one you have not joined. In a channel it can only post if
you are an admin there.
- **No media.** Only message text is archived and sent - no photos, files or
voice notes.
- **It never deletes or edits** anything on your account, and reading never marks
Expand Down
18 changes: 17 additions & 1 deletion auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,13 @@
from telethon import TelegramClient

from tg_ai.config import ConfigError, load_config
from tg_ai.tg_client import build_client, peer_label, secure_session_file
from tg_ai.tg_client import (
SessionLock,
SessionLocked,
build_client,
peer_label,
secure_session_file,
)


async def main() -> int:
Expand All @@ -32,6 +38,15 @@ async def main() -> int:
if config.session_file.exists():
print("A session already exists. Logging in again will reuse it if it is valid.")

# Logging in is still a connection on this authorization key, so it
# contends for the same lock as the server and the sync (ADR-0010).
lock = SessionLock(config.session_lock_file, "a login")
try:
lock.acquire()
except SessionLocked as exc:
print(f"{exc}", file=sys.stderr)
return 1

client: TelegramClient = build_client(config)
try:
# start() drives the phone -> code -> 2FA password prompts itself.
Expand All @@ -43,6 +58,7 @@ async def main() -> int:
finally:
if client.is_connected():
await client.disconnect()
lock.release()

secure_session_file(config.session_file)

Expand Down
23 changes: 16 additions & 7 deletions docs/00-index/glossary.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ id: DOC-GLOSSARY
title: Glossary
status: active
authority: authoritative
updated: 2026-09-05
updated: 2026-09-07
related: [DOC-ROUTER, DOC-SRS, DOC-DATA-MODEL]
---

Expand All @@ -17,20 +17,29 @@ function or document section `Chat`, `Conversation` or `Thread`.

| Term | Meaning | Where it appears in code |
| --- | --- | --- |
| **Peer** | Any Telegram entity a message can be addressed to. In this project a Peer is always a `User`; groups and channels are out of scope. | `tg_client.resolve_peer` |
| **Dialog** | One 1-on-1 conversation with a Peer, and the archive row describing it. Never "chat", never "conversation". | `dialogs` table, `PeerIndex` |
| **Peer** | Any Telegram entity a message can be addressed to: a User, a Group or a Channel. Which of the three is its Peer Type. | `tg_client.resolve_peer`, `tg_client.peer_type` |
| **Peer Type** | `user`, `group` or `channel`. Stored in `dialogs.peer_type`. A megagroup is a Group; a gigagroup is a Channel, because members cannot write in one. | `dialogs.peer_type`, `tg_client.peer_type` |
| **Group** | A Peer where several people write: a basic `Chat` or a megagroup `Channel`. Never "chat", never "supergroup" in prose. | `tg_client.PEER_TYPE_GROUP` |
| **Channel** | A broadcast Peer the account reads and usually cannot write to. Writing needs `admin_rights.post_messages`. | `tg_client.PEER_TYPE_CHANNEL` |
| **Min Peer** | A user id first seen inside a Group or Channel. Telegram delivers it as a `min` constructor whose `access_hash` cannot address it. Stored for attribution only: never resolved, never indexed, never a send target. | `messages.sender_id` |
| **Dialog** | One conversation with a Peer of any type, and the archive row describing it. Never "chat", never "conversation". | `dialogs` table, `PeerIndex` |
| **Target** | The user-supplied reference to a Peer: `@username`, phone number, numeric id, or `me`. Normalised by `normalise_target`. | every tool's `target` parameter |
| **Target Filter** | The set of Targets passed to `sync_db.py --targets`, restricting a Sync to named people. Narrows the Dialog list; never widens it, so it cannot reach a bot, group or deleted account that `SPEC-SYNC-001` already excluded. | `sync_db.select_by_targets` |
| **Target Filter** | The set of Targets passed to `sync_db.py --targets`, restricting a Sync to named Peers. Narrows the existing Dialog list, never widens it, so it can never reach a Peer the account is not already party to. It is also the **only** way to sync a Group or Channel. | `sync_db.select_by_targets` |
| **Archive** | The local PostgreSQL copy of message history. Distinct from Telegram itself, which is always called "the live account". | `tg_ai/db.py` |
| **Sync** | The process of copying messages from the live account into the Archive. | `sync_db.py` |
| **Sync Cursor** | `dialogs.last_synced_message_id` - the highest message id already archived for a Dialog. Advanced only after a commit, so it is always safe to resume from. | `db.advance_cursor` |
| **Chunk** | One outgoing message produced by splitting a longer body under the 4096-character Telegram limit. | `safety.split_message` |
| **Send Guard** | The pre-flight check that refuses to message a Peer with no shared history and no contact entry. | `server.tg_send_message` |
| **Send Guard** | The pre-flight check that refuses to send: to a User with no shared history and no contact entry, to a Group the account has left, to a Channel without post rights, or to a Min Peer. | `server.tg_send_message` |
| **Stranger** | A Peer with no message history and no contact entry. Messaging one is the primary ban vector. | `is_stranger` in `tg_send_message` |
| **Peer Index** | The cached map of Peers the account already has Dialogs with. Consulted before any cold username resolution. | `tg_client.PeerIndex` |
| **Peer Index** | The cached map of Peers the account already has Dialogs with, built from `GetDialogs`. Consulted before any cold username resolution. A hit is proof of membership, which is what makes it the authority for Groups and Channels. | `tg_client.PeerIndex` |
| **Session** | The Telethon `.session` file holding the account's MTProto auth key. A full credential, never a "config file". | `config.session_file` |
| **Session Clone** | The copy of the Session used by `sync_db.py` so two processes never write one SQLite file. | `tg_client.clone_session` |
| **Flood Wait** | Telegram's `FloodWaitError`: a mandatory cooldown in seconds. Always reported to the agent, never silently swallowed in a tool. | `safety.describe_telegram_error` |
| **Flood Wait** | Telegram's `FloodWaitError`: a mandatory cooldown in seconds. Always reported to the agent, never silently swallowed - which is why `flood_sleep_threshold` is pinned to 0. | `safety.describe_telegram_error` |
| **Client Identity** | The `device_model`, `system_version`, `app_version`, `lang_code` and `system_lang_code` sent in `initConnection`. Honest, never impersonating an official client, and frozen once a Session exists. | `config.Config`, `tg_client.build_client` |
| **Connection Lock** | The exclusive `flock` on `<session_name>.lock` that lets only one process connect on the authorization key. Prevents `AUTH_KEY_DUPLICATED`. | `tg_client.SessionLock` |
| **RPC Budget** | The rolling hourly and daily ceiling on Telegram requests, counted in PostgreSQL so it survives a server restart. | `tg_client.RpcGuard`, `api_call_log` |
| **Kill Switch** | The project-wide stop tripped by three Flood Waits in an hour, or indefinitely by a `PeerFloodError`. Honoured by both entrypoints. | `api_kill_switch`, `just tg-killswitch` |
| **Quiet Window** | The nightly hours (`TG_QUIET_HOURS`) in which nothing touches Telegram. Archive-only tools keep working. | `safety.in_quiet_window` |
| **Tool** | An MCP function the agent can call. Always returns text, never raises. | `server.py`, `@mcp.tool()` |
| **Live account** | Telegram itself, reached over MTProto. Contrasted with the Archive. | `tg_get_recent_messages` |
| **Dialog Persona** | How the account writes to one Peer: the agent-authored qualitative pattern plus the Style Metrics measured from `me`'s own archived messages. Never a "chat persona" or a "conversation style". | `dialog_personas` table, `tg_ai/persona.py` |
Expand Down
20 changes: 11 additions & 9 deletions docs/00-index/id-registry.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ id: DOC-ID-REGISTRY
title: Identifier registry
status: active
authority: authoritative
updated: 2026-09-05
updated: 2026-09-07
related: [DOC-ROUTER, DOC-SRS, DOC-ADR-INDEX]
---

Expand Down Expand Up @@ -32,17 +32,19 @@ one at the moment you write the thing, and record it here in the same change.
| `SYNC` | Filling the archive |
| `PSN` | Per-Dialog style: the Dialog Persona, its measurement, freshness and safety |
| `SEC` | Credentials, permissions, configuration, locality |
| `LIM` | Pacing, budgets, the kill switch, the quiet window, blacklisted operations |

## Allocated

| Range | Status |
| --- | --- |
| `SPEC-SND-001` .. `SPEC-SND-006` | In use |
| `SPEC-RCV-001` .. `SPEC-RCV-004` | In use |
| `SPEC-SND-001` .. `SPEC-SND-008` | In use |
| `SPEC-RCV-001` .. `SPEC-RCV-005` | In use |
| `SPEC-SRCH-001` .. `SPEC-SRCH-006` | In use |
| `SPEC-SYNC-001` .. `SPEC-SYNC-006` | In use |
| `SPEC-PSN-001` .. `SPEC-PSN-008` | In use |
| `SPEC-SEC-001` .. `SPEC-SEC-005` | In use |
| `ADR-0000` .. `ADR-0008` | In use (`0000` is the template) |
| `RISK-01` .. `RISK-07` | In use |
| `TASK-001` .. `TASK-013` | In use |
| `SPEC-SYNC-001` .. `SPEC-SYNC-007` | In use |
| `SPEC-PSN-001` .. `SPEC-PSN-009` | In use |
| `SPEC-SEC-001` .. `SPEC-SEC-010` | In use |
| `SPEC-LIM-001` .. `SPEC-LIM-007` | In use |
| `ADR-0000` .. `ADR-0010` | In use (`0000` is the template) |
| `RISK-01` .. `RISK-10` | In use |
| `TASK-001` .. `TASK-015` | In use |
Loading
Loading