Skip to content
Open
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
12 changes: 4 additions & 8 deletions GETTING_STARTED.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ You should see:
✅ Knowledge indexed
✅ Telegram: @your_agent connected
✅ TON Blockchain: connected
✅ Agent is ready! (131 base tools)
✅ Agent is ready! (102 base tools)
```

**Verify:** Send `/ping` to your agent on Telegram.
Expand Down Expand Up @@ -169,15 +169,11 @@ Admin commands are only available to users listed in `admin_ids`. All commands w

## Tool Categories

Teleton has **131 always-registered tools**, plus 5 optional system tools:
Teleton has **102 always-registered tools**, plus 5 optional system tools:

| Category | Count | Highlights |
|----------|-------|------------|
| **Telegram** | 85 | Messaging, media, chats, groups, polls, stickers, gifts, stars, stories, contacts, folders, profile, memory, tasks |
| **TON & Jettons** | 15 | W5R1 wallet, send/receive TON & jettons, balances, prices, holders, history, charts, NFTs, DEX quotes |
| **STON.fi DEX** | 5 | Swap, quote, search, trending tokens, liquidity pools |
| **DeDust DEX** | 5 | Swap, quote, pools, prices, token info |
| **TON DNS** | 8 | Domain check, auctions, bidding, resolution, TON Sites |
| **Telegram** | 83 | Messaging, media, chats, groups, polls, stickers, gifts, stars, stories, contacts, folders, profile, memory, tasks |
| **Journal** | 3 | Log trades/operations with reasoning and P&L |
| **Workspace** | 6 | Sandboxed file operations |
| **Web** | 2 | Search and page extraction |
Expand Down Expand Up @@ -323,7 +319,7 @@ For contributors, create a TypeScript tool in `src/agent/tools/` and register it
src/
├── index.ts # Main application entry point (TeletonApp)
├── agent/ # LLM runtime and tool registry
│ └── tools/ # telegram/, ton/, stonfi/, dedust/, dns/, journal/, workspace/
│ └── tools/ # telegram/, journal/, workspace/, web/, spotify/, exec/
├── telegram/ # GramJS bridge, message handlers, admin commands, debouncing
├── memory/ # SQLite database, RAG search (FTS5 + vector), compaction
├── ton/ # Wallet operations, payment verification, TON blockchain
Expand Down
103 changes: 103 additions & 0 deletions HUMANIZATION_IMPLEMENTED.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# 🎭 Реализованные улучшения для более человечного поведения

## ✅ Фаза 1: Variable Typing Delays (ГОТОВО)

### Что сделано

1. **Новый модуль `src/telegram/human-behavior.ts`**
- `calculateTypingDelay()` - расчет времени "печатания" на основе длины ответа
- `calculateReadDelay()` - задержка перед началом печати (чтение сообщения)
- `shouldShowTyping()` - интеллектуальное решение показывать ли typing
- `isSimpleAcknowledgment()` - детекция простых ответов типа "ок", "да"
- `calculateReactionDelay()` - естественная задержка перед реакцией

2. **Интеграция в message handler** (`src/telegram/handlers.ts`)
- Задержка перед началом typing (имитация чтения)
- Variable typing delay зависит от длины ответа
- Короткие ответы типа "ok" могут пропускать typing (50% шанс)
- Группы получают ответы на 40% быстрее (меньше думаем в groups)

3. **Интеграция в heartbeat** (`src/heartbeat.ts`)
- Проактивные сообщения тоже используют human-like delays
- Fallback на конфиг `reply_delay_ms` если typing отключен

### Параметры по умолчанию

```typescript
baseDelayMs: 800 // Базовое время "думания"
charsPerSecond: 25 // Скорость печати (реалистично)
minDelayMs: 500 // Минимум 0.5с
maxDelayMs: 8000 // Максимум 8с
variancePercent: 30 // ±30% рандомности

// Groups: все задержки × 0.6
```

### Примеры поведения

| Длина ответа | DM задержка | Group задержка | Примечание |
|--------------|-------------|----------------|------------|
| 20 chars (короткий) | ~1.2s | ~0.7s | Может пропустить typing |
| 100 chars | ~2.8s | ~1.7s | Типичный ответ |
| 500 chars (длинный) | ~7.5s | ~4.5s | Серьёзный ответ |
| "ok" (acknowledgment) | 0-1.2s | 0-0.7s | 50% без typing |

### Отключение TON функций (БОНУС)

Добавлен конфиг для отключения крипто-инструментов:

```yaml
# config.yaml
ton_features:
enabled: false # По умолчанию выключено
```

Экономия:
- ❌ Не создается createTonSDK (733 строки, complexity 102)
- ❌ Не грузятся blockchain зависимости
- ✅ Плагины получают `sdk.ton = null`

---

## 🚀 Следующие шаги (не реализовано)

### Фаза 2: Context-Aware Behavior
1. **Smart silence** - молчать в активных групповых дискуссиях
2. **Variable reply probability** - не отвечать на каждое сообщение в группах
3. **Time-of-day awareness** - стиль общения зависит от времени суток
4. **Conversational momentum** - быстрые ответы во время активного диалога

### Фаза 3: Advanced
5. **Read tracker** - читать сообщения без мгновенного ответа
6. **Sticker bank** - использовать стикеры вместо текста иногда
7. **Quiet hours** - сниженная активность ночью
8. **Proactive check-ins** - спросить как дела (осторожно)

---

## 🧪 Как протестировать

1. Включите `typing_simulation: true` в config
2. Отправьте короткое сообщение ("привет") → быстрый ответ
3. Отправьте длинный вопрос → более долгое "думание"
4. В группе ответы должны быть быстрее чем в DM
5. Простые "ок" иногда приходят без typing indicator

## 📊 Метрики

До улучшений:
- Фиксированная задержка `reply_delay_ms`
- Все сообщения одинаковые
- Не учитывается контекст (DM/group)

После:
- ✅ Динамические задержки (0.5s - 8s)
- ✅ Зависит от длины ответа
- ✅ Группы в 1.7× быстрее
- ✅ Простые ответы могут быть мгновенными
- ✅ ±30% variance для естественности

---

_Создано: 2025-01-XX_
_Автор: Claude (Kiro)_
Empty file added HUMANIZATION_ROADMAP.md
Empty file.
12 changes: 4 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

---

<p align="center">Teleton is an autonomous AI agent platform that operates as a real Telegram user account or a Telegram Bot. It thinks through an agentic loop with tool calling, remembers conversations across sessions with hybrid RAG, and natively integrates the TON blockchain: send crypto, swap on DEXs, bid on domains, verify payments - all from a chat message. It can schedule tasks to run autonomously at any time. It ships with 131 always-registered tools plus 5 optional system tools, supports 16 LLM providers, and exposes a Plugin SDK so you can build your own tools on top of the platform.</p>
<p align="center">Teleton is an autonomous AI agent platform that operates as a real Telegram user account or a Telegram Bot. It thinks through an agentic loop with tool calling, remembers conversations across sessions with hybrid RAG, and natively integrates the TON blockchain: verify payments and query on-chain state - all from a chat message. It can schedule tasks to run autonomously at any time. It ships with 102 always-registered tools plus 5 optional system tools, supports 16 LLM providers, and exposes a Plugin SDK so you can build your own tools on top of the platform.</p>

### Key Highlights

Expand Down Expand Up @@ -496,17 +496,13 @@ src/
├── agent/ # Core agent runtime
│ ├── runtime.ts # Budgeted agentic loop, tool calling, masking, compaction
│ ├── client.ts # Multi-provider LLM client
│ └── tools/ # 131 base tools plus 5 optional system tools
│ ├── register-all.ts # Central tool registration (9 categories)
│ └── tools/ # 102 base tools plus 5 optional system tools
│ ├── register-all.ts # Central tool registration (5 categories)
│ ├── registry.ts # Tool registry, scope filtering, provider limits
│ ├── module-loader.ts # Built-in module loading (TON Proxy + exec)
│ ├── plugin-loader.ts # External plugin discovery, validation, hot-reload
│ ├── mcp-loader.ts # MCP client (stdio/SSE), tool discovery, lifecycle
│ ├── telegram/ # Telegram operations (86 tools)
│ ├── ton/ # TON blockchain + jettons + DEX router (15 tools)
│ ├── stonfi/ # STON.fi DEX (5 tools)
│ ├── dedust/ # DeDust DEX (5 tools)
│ ├── dns/ # TON DNS (8 tools)
│ ├── telegram/ # Telegram operations (83 tools)
│ ├── exec/ # System execution — YOLO mode (4 tools)
│ ├── journal/ # Business journal (3 tools)
│ └── workspace/ # File operations (6 tools)
Expand Down
11 changes: 11 additions & 0 deletions bin/teleton.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,13 @@
#!/usr/bin/env node
import { execFileSync } from "node:child_process";

if (process.platform === "win32" && process.stdout.isTTY) {
try {
// chcp changes the attached console, so UTF-8 log output is not decoded as CP866/1251.
execFileSync("chcp.com", ["65001"], { stdio: "ignore" });
} catch {
// Logging still works on terminals where the console code page cannot be changed.
}
}

await import("../dist/cli/index.js");
92 changes: 69 additions & 23 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# Or run: teleton setup

agent:
provider: "anthropic" # anthropic | codex | grok-build | openai | google | xai | groq | openrouter
provider: "anthropic" # anthropic | codex | grok-build | openai | google | xai | groq | openrouter
api_key: "YOUR_API_KEY"
model: "claude-haiku-4-5-20251001" # Model ID (varies by provider)
# utility_model: "claude-3-5-haiku-20241022" # Optional: cheap model for summarization
Expand All @@ -13,46 +13,64 @@ agent:
max_agentic_iterations: 5
session_reset_policy:
daily_reset_enabled: true
daily_reset_hour: 4 # 0-23, hour of day to reset sessions
daily_reset_hour: 4 # 0-23, hour of day to reset sessions
idle_expiry_enabled: true
idle_expiry_minutes: 1440 # 24 hours
idle_expiry_minutes: 1440 # 24 hours

telegram:
mode: "user" # "user" (default) or "bot" — user requires phone auth, bot requires bot_token
api_id: 0 # From https://my.telegram.org/apps
mode: "user" # "user" (default) or "bot" — user requires phone auth, bot requires bot_token
api_id: 0 # From https://my.telegram.org/apps
api_hash: "YOUR_API_HASH"
phone: "+1234567890" # Phone number linked to Telegram account
session_name: "teleton_session" # GramJS session file name
session_path: "~/.teleton" # Directory for session files
dm_policy: "open" # open | allowlist | admin-only | disabled
allow_from: [] # Telegram user IDs (for allowlist policy)
group_policy: "open" # open | allowlist | disabled
group_allow_from: [] # Group chat IDs (for allowlist group policy)
require_mention: true # In groups, only respond when mentioned
phone: "+1234567890" # Phone number linked to Telegram account
session_name: "teleton_session" # GramJS session file name
session_path: "~/.teleton" # Directory for session files
dm_policy: "open" # open | allowlist | admin-only | disabled
allow_from: [] # Telegram user IDs (for allowlist policy)
group_policy: "open" # open | allowlist | disabled
group_allow_from: [] # Group chat IDs (for allowlist group policy)
require_mention: true # In groups, only respond when mentioned
# max_message_length: 4096 # MTProto limit, rarely needs changing
typing_simulation: true # Show "typing..." while processing
typing_simulation: true # Show "typing..." while processing
reaction_events: true # Let the bot receive reactions to its messages
rate_limit_messages_per_second: 1.0
rate_limit_groups_per_minute: 20
admin_ids: [123456789] # Your Telegram user ID (from @userinfobot)
admin_ids: [123456789] # Your Telegram user ID (from @userinfobot)
# agent_channel: null # Channel username or ID for announcements
owner_name: "Your Name"
owner_username: "your_username"
# owner_id: 123456789 # Owner's Telegram user ID
debounce_ms: 1500 # Group message batching delay (0 = disabled)
debounce_ms: 1500 # Group message batching delay (0 = disabled)
dm_debounce_ms: 1000 # Direct-message batching window: rapid DMs are merged into one context-aware reply (0 = disabled)

# Optional in user mode: plugin inline cards and callback handling
# bot_token: "123456:ABC-DEF..." # From @BotFather
# bot_username: "your_agent_bot"

# Optional: periodic heartbeat and proactive checks
heartbeat:
enabled: true
interval_ms: 3600000 # Every 60 min
# startup_prompt: "Greet me once at startup." # One-time prompt on first tick
min_interval_between_replies_ms: 30000 # Min time between two heartbeat replies to the same chat (0 = off)
reply_delay_ms: 1000 # Human-like delay before sending a heartbeat reply (0 = none)

# Optional: Enable TON blockchain features (wallet, DEX, DNS, jettons, NFTs)
# ton_features:
# enabled: false # Set to true to enable TON SDK in plugins

# Optional: TonAPI key for higher rate limits
# tonapi_key: "YOUR_TONAPI_KEY" # From @tonapi_bot

# Optional: Tavily API key for web search/fetch tools
# tavily_api_key: "YOUR_TAVILY_KEY" # From https://tavily.com

# Optional: MiniMax TTS keys for telegram_send_voice with ttsProvider: minimax
# MINIMAX_API_KEY: sk-cp-WJx00mS7JhhsX4PxDqVBBdHZAihV3_KEbbtnM-MRC1uNBYFfbhT3X9fPEKSd1etdPyk6BXPL3N3-hN83hKEitfSLiOodkp8k_IQQruxcqnvNAL_OUuyoGTA # From https://platform.minimax.io/
# MINIMAX_GROUP_ID: "YOUR_MINIMAX_GROUP_ID" # Account GroupId (see platform console)

# Embedding provider for RAG vector search
embedding:
provider: "local" # local | anthropic | none
provider: "local" # local | anthropic | none
# model: "Xenova/all-MiniLM-L6-v2" # Model override (auto-detected per provider)
#
# local = ONNX runtime, runs entirely on CPU, no API calls needed
Expand All @@ -61,14 +79,15 @@ embedding:

# Optional: WebUI dashboard (disabled by default for security)
webui:
enabled: false # Enable web dashboard
port: 7777 # HTTP server port
host: "127.0.0.1" # Localhost only (secure)
enabled: false # Enable web dashboard
port: 7777 # HTTP server port
host: "127.0.0.1" # Localhost only (secure)
# auth_token: "..." # Auto-generated if omitted
cors_origins:
- "http://localhost:5173" # Vite dev server
- "http://localhost:7777" # Production server
log_requests: false # Log HTTP requests
- "http://localhost:5173" # Vite dev server
- "http://localhost:7777" # Production server
log_requests: false # Log HTTP requests


# Tool RAG: semantic tool selection per message (ENABLED by default)
# Reduces tool definitions sent to the LLM from 120+ to ~25 most relevant.
Expand Down Expand Up @@ -106,8 +125,35 @@ webui:
# remote:
# url: http://localhost:3001/mcp

# Optional: Human-like behavior enhancements
# Makes the agent behave more like a real person
humanization:
enabled: true
reply_probability:
dm_base: 0.85 # 85% chance to reply in DMs
group_mentioned: 0.50 # 50% chance when mentioned in group
group_replied_to_us: 0.90 # 90% if someone replied to our message
group_unmentioned: 0.05 # 5% without mention (smart silence)
min_interval_ms: 3000 # Don't reply faster than 3s in same chat
high_activity_threshold: 5 # Messages/min threshold for "busy chat"
high_activity_multiplier: 0.3 # Reduce replies 70% in busy groups
time_of_day:
enabled: true
quiet_hours_start: 23 # 11 PM
quiet_hours_end: 6 # 6 AM
timezone_offset_minutes: 180 # UTC+3 (Moscow). Adjust for your zone
writing_style:
typo_probability: 0.03 # 3% chance of simulating a typo
edit_after_send_probability: 0.05 # 5% chance of edit after send
max_edit_delay_ms: 15000 # Max delay for edit simulation
staging_probability: 0.03 # 3% show typing but don't send
emoji_enabled: true
fillers_enabled: true

# Per-plugin configuration (key = plugin name)
# plugins:
# casino:
# min_bet: 0.1
# cooldown_seconds: 30
# Spotify search and track metadata (optional; create an app at developer.spotify.com)
# Set SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET in the environment.
Loading